This repository was archived by the owner on Jun 3, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 104
Expand file tree
/
Copy pathagent.ts
More file actions
2147 lines (1951 loc) · 78.2 KB
/
Copy pathagent.ts
File metadata and controls
2147 lines (1951 loc) · 78.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
AgentResult,
type AgentStreamEvent,
type InvocationState,
type InvokableAgent,
type InvokeArgs,
type InvokeOptions,
type LocalAgent,
type localAgentSymbol,
} from '../types/agent.js'
import { BedrockModel } from '../models/bedrock.js'
import {
contentBlockFromData,
type ContentBlock,
type ContentBlockData,
Message,
type MessageData,
type SystemPrompt,
type SystemPromptData,
TextBlock,
ToolResultBlock,
type ToolResultBlockData,
ToolUseBlock,
} from '../types/messages.js'
import type { JSONValue } from '../types/json.js'
import { McpClient } from '../mcp.js'
import { isValidToolName, type Tool, type ToolContext } from '../tools/tool.js'
import type { ToolChoice } from '../tools/types.js'
import { systemPromptFromData } from '../types/messages.js'
import { normalizeError, ConcurrentInvocationError, StructuredOutputError } from '../errors.js'
import { Model } from '../models/model.js'
import type { BaseModelConfig, StreamAggregatedResult, StreamOptions } from '../models/model.js'
import { ModelPlugin } from '../plugins/model-plugin.js'
import { isModelStreamEvent } from '../models/streaming.js'
import { ToolRegistry } from '../registry/tool-registry.js'
import { StateStore } from '../state-store.js'
import { AgentPrinter, getDefaultAppender, type Printer } from './printer.js'
import type { Plugin } from '../plugins/plugin.js'
import { PluginRegistry } from '../plugins/registry.js'
import { SlidingWindowConversationManager } from '../conversation-manager/sliding-window-conversation-manager.js'
import { NullConversationManager } from '../conversation-manager/null-conversation-manager.js'
import { ConversationManager } from '../conversation-manager/conversation-manager.js'
import { HookRegistryImplementation } from '../hooks/registry.js'
import type { HookableEventConstructor, HookCallback, HookCallbackOptions, HookCleanup } from '../hooks/types.js'
import {
InitializedEvent,
AfterInvocationEvent,
AfterModelCallEvent,
AfterToolCallEvent,
AfterToolsEvent,
BeforeInvocationEvent,
BeforeModelCallEvent,
BeforeToolCallEvent,
BeforeToolsEvent,
HookableEvent,
MessageAddedEvent,
ModelStreamUpdateEvent,
ContentBlockEvent,
ModelMessageEvent,
ToolResultEvent,
AgentResultEvent,
ToolStreamUpdateEvent,
InterruptEvent,
type ModelStopData,
} from '../hooks/events.js'
import { StructuredOutputTool, STRUCTURED_OUTPUT_TOOL_NAME } from '../tools/structured-output-tool.js'
import { AgentAsTool } from './agent-as-tool.js'
import type { AgentAsToolOptions } from './agent-as-tool.js'
import type { z } from 'zod'
import { MemoryManager } from '../memory/memory-manager.js'
import type { MemoryManagerConfig } from '../memory/index.js'
import { SessionManager } from '../session/session-manager.js'
import { Tracer } from '../telemetry/tracer.js'
import { Meter } from '../telemetry/meter.js'
import type { AttributeValue } from '@opentelemetry/api'
import { logger } from '../logging/logger.js'
import { CancelledError } from '../errors.js'
import { DefaultModelRetryStrategy } from '../retry/default-model-retry-strategy.js'
import type { RetryStrategy } from '../retry/retry-strategy.js'
import { warnOnDuplicateRetryStrategyTypes } from '../retry/retry-strategy.js'
import { InterruptError, InterruptState, interruptFromAgent } from '../interrupt.js'
import type { InterruptParams } from '../types/interrupt.js'
import { isInterruptResponseContent, type InterruptResponseContent } from '../types/interrupt.js'
import { takeSnapshot as takeSnapshotInternal, loadSnapshot as loadSnapshotInternal } from './snapshot.js'
import type { TakeSnapshotOptions } from './snapshot.js'
import type { Snapshot } from '../types/snapshot.js'
/**
* Recursive type definition for nested tool arrays.
* Allows tools to be organized in nested arrays of any depth.
*
* {@link Agent} instances in the array are automatically wrapped via
* {@link Agent.asTool}, so they can be passed directly without calling
* `.asTool()` explicitly.
*/
export type ToolList = (Tool | McpClient | Agent | ToolList)[]
/**
* Strategy for executing tool calls that the model emits in a single assistant turn.
*
* - `'concurrent'` (default) — runs all tool calls from a single turn in parallel. Per-tool event
* order (`BeforeToolCallEvent` → `ToolStreamUpdateEvent*` → `AfterToolCallEvent` →
* `ToolResultEvent`) is preserved, while cross-tool events may interleave.
* - `'sequential'` — runs tool calls one at a time
*
* Cancellation works identically in both modes: {@link Agent.cancel} flips
* {@link Agent.cancelSignal} and tools must observe it cooperatively to stop early.
* In concurrent mode, prompt batch-wide cancellation requires every in-flight tool
* to honor the signal.
*/
export type ToolExecutorStrategy = 'sequential' | 'concurrent'
/**
* Configuration object for creating a new Agent.
*/
export type AgentConfig = {
/**
* The model instance that the agent will use to make decisions.
* Accepts either a Model instance or a string representing a Bedrock model ID.
* When a string is provided, it will be used to create a BedrockModel instance.
*
* @example
* ```typescript
* // Using a string model ID (creates BedrockModel)
* const agent = new Agent({
* model: 'anthropic.claude-3-5-sonnet-20240620-v1:0'
* })
*
* // Using an explicit BedrockModel instance with configuration
* const agent = new Agent({
* model: new BedrockModel({
* modelId: 'anthropic.claude-3-5-sonnet-20240620-v1:0',
* temperature: 0.7,
* maxTokens: 2048
* })
* })
* ```
*/
model?: Model<BaseModelConfig> | string
/** An initial set of messages to seed the agent's conversation history. */
messages?: Message[] | MessageData[]
/**
* An initial set of tools to register with the agent.
* Accepts nested arrays of tools at any depth, which will be flattened automatically.
* {@link Agent} instances are automatically wrapped as tools via {@link Agent.asTool}.
*/
tools?: ToolList
/**
* A system prompt which guides model behavior.
*/
systemPrompt?: SystemPrompt | SystemPromptData
/** Optional initial state values for the agent. */
appState?: Record<string, JSONValue>
/**
* Optional initial model-provider state (e.g., restoring `responseId` from a
* prior session). Typically only set when hydrating from a snapshot.
*/
modelState?: Record<string, JSONValue>
/**
* Enable automatic printing of agent output to console.
* When true, prints text generation, reasoning, and tool usage as they occur.
* Defaults to true.
*/
printer?: boolean
/**
* Conversation manager for handling message history and context overflow.
* Defaults to SlidingWindowConversationManager with windowSize of 40.
*/
conversationManager?: ConversationManager
/**
* Plugins to register with the agent.
*/
plugins?: Plugin[]
/**
* Retry strategy (or strategies) for failed model/tool calls.
*
* - Omitted: a sensible default {@link DefaultModelRetryStrategy} with exponential backoff is used.
* - Single strategy: the given strategy is used.
* - Array of strategies: all are registered, in the given order. Passing two
* instances of the same concrete class logs a warning — they will collide
* on `plugin.name` when the plugin registry initializes.
* - `null` or `[]`: retries are explicitly disabled; failures propagate to the caller.
*/
retryStrategy?: RetryStrategy | RetryStrategy[] | null
/**
* Zod schema for structured output validation.
*/
structuredOutputSchema?: z.ZodSchema
/**
* Session manager for saving and restoring agent sessions.
*/
sessionManager?: SessionManager
/**
* Memory manager for cross-session knowledge retrieval and storage.
* Manages one or more knowledge stores and exposes search/store tools.
* Accepts a {@link MemoryManager} instance or a {@link MemoryManagerConfig} object (auto-wrapped).
*/
memoryManager?: MemoryManager | MemoryManagerConfig
/**
* Custom trace attributes to include in all spans.
* These attributes are merged with standard attributes in telemetry spans.
* Telemetry must be enabled globally via telemetry.setupTracer() for these to take effect.
*/
traceAttributes?: Record<string, AttributeValue>
/**
* Optional name for the agent. Defaults to "Strands Agent".
*/
name?: string
/**
* Optional description of what the agent does.
*/
description?: string
/**
* Optional unique identifier for the agent. Defaults to "agent".
*/
id?: string
/**
* Strategy for executing tool calls from a single assistant turn.
* Defaults to `'concurrent'`. See {@link ToolExecutorStrategy} for details.
*/
toolExecutor?: ToolExecutorStrategy
}
/** Default name assigned to agents when none is provided. */
const DEFAULT_AGENT_NAME = 'Strands Agent'
/** Default identifier assigned to agents when none is provided. */
const DEFAULT_AGENT_ID = 'agent'
/** Result returned by tool-execution generators, threading the AfterToolsEvent back to the main loop. */
type ToolsExecutionResult = { message: Message; afterToolsEvent: AfterToolsEvent }
/**
* Orchestrates the interaction between a model, a set of tools, and MCP clients.
* The Agent is responsible for managing the lifecycle of tools and clients
* and invoking the core decision-making loop.
*/
export class Agent implements LocalAgent, InvokableAgent {
/** @internal */
declare readonly [localAgentSymbol]: true
/**
* The conversation history of messages between user and assistant.
*/
public messages: Message[]
/**
* App state storage accessible to tools and application logic.
* State is not passed to the model during inference.
*/
public readonly appState: StateStore
/**
* Runtime state for the model provider. Used by stateful models to persist
* provider-specific data (e.g., response IDs for conversation chaining)
* across invocations.
*/
public readonly modelState: StateStore
private readonly _conversationManager: ConversationManager
/**
* The model provider used by the agent for inference.
*/
public model: Model
/**
* The system prompt to pass to the model provider.
*/
public systemPrompt?: SystemPrompt
/**
* The name of the agent.
*/
public readonly name: string
/**
* The unique identifier of the agent instance.
*/
public readonly id: string
/**
* Optional description of what the agent does.
*/
public readonly description?: string
/**
* The session manager for saving and restoring agent sessions, if configured.
*/
public readonly sessionManager?: SessionManager | undefined
/**
* The memory manager for cross-session knowledge retrieval and storage, if configured.
*/
public readonly memoryManager?: MemoryManager | undefined
private readonly _hooksRegistry: HookRegistryImplementation
private readonly _pluginRegistry: PluginRegistry
private _toolRegistry: ToolRegistry
private _mcpClients: McpClient[]
private _initialized: boolean
private _isInvoking: boolean = false
private _abortController = new AbortController()
private _abortSignal: AbortSignal = this._abortController.signal
private _printer?: Printer
private _structuredOutputSchema?: z.ZodSchema | undefined
/** Tracer instance for creating and managing OpenTelemetry spans. */
private _tracer: Tracer
/** Meter instance for accumulating loop metrics during invocation. */
private _meter: Meter
/** Interrupt state for human-in-the-loop workflows. */
_interruptState: InterruptState
/** Strategy for executing tool calls from a single assistant turn. */
private readonly _toolExecutor: ToolExecutorStrategy
/**
* Creates an instance of the Agent.
* @param config - The configuration for the agent.
*/
constructor(config?: AgentConfig) {
// Initialize public fields
this.messages = (config?.messages ?? []).map((msg) => (msg instanceof Message ? msg : Message.fromMessageData(msg)))
this.appState = new StateStore(config?.appState)
this.modelState = new StateStore(config?.modelState)
this.name = config?.name ?? DEFAULT_AGENT_NAME
this.id = config?.id ?? DEFAULT_AGENT_ID
if (config?.description !== undefined) this.description = config.description
this.sessionManager = config?.sessionManager
this.memoryManager =
config?.memoryManager instanceof MemoryManager
? config.memoryManager
: config?.memoryManager
? new MemoryManager(config.memoryManager)
: undefined
if (typeof config?.model === 'string') {
this.model = new BedrockModel({ modelId: config.model })
} else {
this.model = config?.model ?? new BedrockModel()
}
// Validate and assign conversation manager
if (this.model.stateful) {
if (config?.conversationManager) {
throw new Error(
'Cannot use a conversationManager with a stateful model. The model manages conversation state server-side.'
)
}
this._conversationManager = new NullConversationManager()
} else {
this._conversationManager =
config?.conversationManager ?? new SlidingWindowConversationManager({ windowSize: 40 })
}
const { tools, mcpClients } = flattenTools(config?.tools ?? [])
this._toolRegistry = new ToolRegistry(tools)
this._mcpClients = mcpClients
// Initialize hooks registry
this._hooksRegistry = new HookRegistryImplementation()
// `undefined` (omitted) → install the default; `null`/`[]` → explicit opt-out.
const retryStrategies: RetryStrategy[] =
config?.retryStrategy === null
? []
: config?.retryStrategy === undefined
? [new DefaultModelRetryStrategy()]
: Array.isArray(config.retryStrategy)
? config.retryStrategy
: [config.retryStrategy]
warnOnDuplicateRetryStrategyTypes(retryStrategies)
// Initialize plugin registry with all plugins to be initialized during initialize().
// Ordering notes:
// - ModelPlugin is registered last so that on AfterInvocationEvent (which uses
// reverse callback ordering), it runs first — clearing messages before
// SessionManager saves.
// - Retry-strategy ordering is not load-bearing for correctness: `DefaultModelRetryStrategy`
// guards on `event.retry`, so a user hook that already set it short-circuits
// the strategy regardless of registration order.
this._pluginRegistry = new PluginRegistry([
this._conversationManager,
...retryStrategies,
...(config?.plugins ?? []),
...(this.memoryManager ? [this.memoryManager] : []),
...(config?.sessionManager ? [config.sessionManager] : []),
new ModelPlugin(this.model),
])
if (config?.systemPrompt !== undefined) {
this.systemPrompt = systemPromptFromData(config.systemPrompt)
}
// Create printer if printer is enabled (default: true)
const printer = config?.printer ?? true
if (printer) {
this._printer = new AgentPrinter(getDefaultAppender())
}
// Store structured output schema
this._structuredOutputSchema = config?.structuredOutputSchema
// Initialize tracer - OTEL returns no-op tracer if not configured
this._tracer = new Tracer(config?.traceAttributes)
// Initialize meter for local metrics accumulation
this._meter = new Meter()
// Initialize interrupt state for human-in-the-loop workflows
this._interruptState = new InterruptState()
this._toolExecutor = config?.toolExecutor ?? 'concurrent'
this._initialized = false
}
/**
* Register a hook callback for a specific event type.
*
* @param eventType - The event class constructor to register the callback for
* @param callback - The callback function to invoke when the event occurs
* @param options - Optional configuration including execution order
* @returns Cleanup function that removes the callback when invoked
*
* @example
* ```typescript
* const agent = new Agent({ model })
*
* const cleanup = agent.addHook(BeforeInvocationEvent, (event) => {
* console.log('Invocation started')
* })
*
* // Later, to remove the hook:
* cleanup()
* ```
*/
addHook<T extends HookableEvent>(
eventType: HookableEventConstructor<T>,
callback: HookCallback<T>,
options?: HookCallbackOptions
): HookCleanup {
return this._hooksRegistry.addCallback(eventType, callback, options)
}
public async initialize(): Promise<void> {
if (this._initialized) {
return
}
// Initialize MCP clients and register their tools
await Promise.all(
this._mcpClients.map(async (client) => {
const tools = await client.listTools()
this._toolRegistry.add(tools)
client.onToolsChanged = (oldTools, newTools): void => {
oldTools.forEach((name) => this._toolRegistry.remove(name))
this._toolRegistry.addOrReplace(newTools)
}
})
)
await this._pluginRegistry.initialize(this)
await this._hooksRegistry.invokeCallbacks(new InitializedEvent({ agent: this }))
this._initialized = true
}
/**
* Acquires a lock to prevent concurrent invocations.
* Returns a Disposable that releases the lock when disposed.
*/
private acquireLock(): { [Symbol.dispose]: () => void } {
if (this._isInvoking) {
throw new ConcurrentInvocationError(
'Agent is already processing an invocation. Wait for the current invoke() or stream() call to complete before invoking again.'
)
}
this._isInvoking = true
return {
[Symbol.dispose]: (): void => {
this._isInvoking = false
},
}
}
/**
* Throws {@link CancelledError} if cancellation has been requested.
* Called at cancellation checkpoints within the agent loop.
*/
private _throwIfCancelled(): void {
if (this.isCancelled) {
throw new CancelledError()
}
}
/**
* The tools this agent can use.
*/
get tools(): Tool[] {
return this._toolRegistry.list()
}
/**
* The tool registry for managing the agent's tools.
*/
get toolRegistry(): ToolRegistry {
return this._toolRegistry
}
/**
* The cancellation signal for the current invocation.
*
* Tools can pass this to cancellable operations (e.g., `fetch(url, { signal: agent.cancelSignal })`).
* Hooks can check `event.agent.cancelSignal.aborted` to detect cancellation.
*/
get cancelSignal(): AbortSignal {
return this._abortSignal
}
/**
* Cancels the current agent invocation cooperatively.
*
* The agent will stop at the next cancellation checkpoint:
* - During model response streaming
* - Before tool execution
* - Between sequential tool executions
* - At the top of each agent loop cycle
*
* If a tool is already executing, it will run to completion unless
* the tool checks {@link LocalAgent.cancelSignal | cancelSignal} internally.
*
* Hook callbacks can check `event.agent.cancelSignal.aborted` to detect
* cancellation and adjust their behavior accordingly.
*
* The stream/invoke call will return an AgentResult with `stopReason: 'cancelled'`.
* If the agent is not currently invoking, this is a no-op.
*
* @example
* ```typescript
* const agent = new Agent({ model, tools })
*
* // Cancel after 5 seconds
* setTimeout(() => agent.cancel(), 5000)
* const result = await agent.invoke('Do something')
* console.log(result.stopReason) // 'cancelled'
* ```
*/
public cancel(): void {
if (this._isInvoking) {
this._abortController.abort()
}
}
/**
* Whether the current invocation has been cancelled.
* Returns `false` when the agent is idle.
*/
private get isCancelled(): boolean {
return this._abortSignal.aborted
}
/**
* Invokes the agent and returns the final result.
*
* This is a convenience method that consumes the stream() method and returns
* only the final AgentResult. Use stream() if you need access to intermediate
* streaming events.
*
* @param args - Arguments for invoking the agent
* @param options - Optional per-invocation options
* @returns Promise that resolves to the final AgentResult
*
* @example
* ```typescript
* const agent = new Agent({ model, tools })
* const result = await agent.invoke('What is 2 + 2?')
* console.log(result.lastMessage) // Agent's response
* ```
*/
public async invoke(args: InvokeArgs, options?: InvokeOptions): Promise<AgentResult> {
const gen = this.stream(args, options)
let result = await gen.next()
while (!result.done) {
result = await gen.next()
}
return result.value
}
/**
* Streams the agent execution, yielding events and returning the final result.
*
* The agent loop manages the conversation flow by:
* 1. Streaming model responses and yielding all events
* 2. Executing tools when the model requests them
* 3. Continuing the loop until the model completes without tool use
*
* Use this method when you need access to intermediate streaming events.
* For simple request/response without streaming, use invoke() instead.
*
* An explicit goal of this method is to always leave the message array in a way that
* the agent can be reinvoked with a user prompt after this method completes. To that end
* assistant messages containing tool uses are only added after tool execution succeeds
* with valid toolResponses
*
* @param args - Arguments for invoking the agent
* @param options - Optional per-invocation options
* @returns Async generator that yields AgentStreamEvent objects and returns AgentResult
*
* @example
* ```typescript
* const agent = new Agent({ model, tools })
*
* for await (const event of agent.stream('Hello')) {
* console.log('Event:', event.type)
* }
* // Messages array is mutated in place and contains the full conversation
* ```
*/
public async *stream(
args: InvokeArgs,
options?: InvokeOptions
): AsyncGenerator<AgentStreamEvent, AgentResult, undefined> {
using _lock = this.acquireLock()
await this.initialize()
let currentArgs: InvokeArgs = args
// Outer loop: re-enters _stream when a hook sets AfterInvocationEvent.resume.
// One invocation lock spans the whole resume chain.
while (true) {
// Fresh AbortController per invocation iteration, composed with any external signal.
this._abortController = new AbortController()
this._abortSignal = options?.cancelSignal
? AbortSignal.any([this._abortController.signal, options.cancelSignal])
: this._abortController.signal
const streamGenerator = this._stream(currentArgs, options)
let caughtError: Error | undefined
let lastAfterInvocation: AfterInvocationEvent | undefined
let iterationResult: IteratorResult<AgentStreamEvent, AgentResult>
try {
iterationResult = await streamGenerator.next()
while (!iterationResult.done) {
try {
const processed = await this._invokeCallbacks(iterationResult.value)
if (processed instanceof AfterInvocationEvent) {
lastAfterInvocation = processed
}
yield processed
iterationResult = await streamGenerator.next()
} catch (error) {
// Throw interrupt errors back into _stream so executeTools can store the
// assistant message as pending execution state for resume.
if (error instanceof InterruptError) {
iterationResult = await streamGenerator.throw(error)
} else {
throw error
}
}
}
// Suppress AgentResultEvent for resumed iterations — only the final
// invocation in a resume chain reports an agent result.
if (lastAfterInvocation?.resume === undefined) {
yield await this._invokeCallbacks(
new AgentResultEvent({
agent: this,
result: iterationResult.value,
invocationState: iterationResult.value.invocationState,
})
)
}
} catch (error) {
caughtError = error as Error
throw error
} finally {
// Drain _stream() so cleanup hooks and printer still fire.
// Yield only on error (consumer may still be iterating); on a consumer
// break, yielding would suspend the generator and leak the lock.
let drainResult = await streamGenerator.return(undefined as never)
while (!drainResult.done) {
try {
if (caughtError) {
yield await this._invokeCallbacks(drainResult.value)
} else {
await this._invokeCallbacks(drainResult.value)
}
} catch (error) {
logger.warn(
`event_type=<${drainResult.value.type}>, error=<${error}> | error invoking callbacks during cleanup`
)
}
drainResult = await streamGenerator.next()
}
// Reset controller and signal for next iteration / invocation
this._abortController = new AbortController()
this._abortSignal = this._abortController.signal
}
// Resume only on a clean invocation — errors propagate above.
if (lastAfterInvocation?.resume !== undefined) {
currentArgs = lastAfterInvocation.resume
continue
}
return iterationResult.value
}
}
/**
* Returns a {@link Tool} that wraps this agent, allowing it to be used
* as a tool by another agent.
*
* The returned tool accepts a single `input` string parameter, invokes
* this agent, and returns the text response as a tool result.
*
* **Note:** You can also pass an Agent directly in another agent's
* {@link AgentConfig.tools | tools} array — it will be wrapped
* automatically via this method.
*
* @param options - Optional configuration for the tool name, description, and context preservation
* @returns A Tool wrapping this agent
*
* @example
* ```typescript
* const researcher = new Agent({ name: 'researcher', description: 'Finds info', printer: false })
*
* // Explicit wrapping
* const writer = new Agent({ tools: [researcher.asTool()] })
*
* // Automatic wrapping (equivalent)
* const writer = new Agent({ tools: [researcher] })
* ```
*/
public asTool(options?: AgentAsToolOptions): Tool {
return new AgentAsTool({ agent: this, ...options })
}
/**
* Captures a point-in-time snapshot of the agent's current state.
*
* Use snapshots to checkpoint agent state for later restoration, enabling
* use cases like undo/redo, branching conversations, and session persistence.
*
* Fields are selected via a preset/include/exclude model:
* 1. Start with preset fields (e.g. `'session'` captures all fields)
* 2. Add any `include` fields
* 3. Remove any `exclude` fields
*
* @param options - Controls which fields to capture and optional app data to store
* @returns A {@link Snapshot} containing the captured agent state
* @throws Error if no fields would be included after applying options
*
* @example
* ```typescript
* // Capture all session-relevant state
* const snapshot = agent.takeSnapshot({ preset: 'session' })
*
* // Capture only messages and state
* const partial = agent.takeSnapshot({ include: ['messages', 'state'] })
*
* // Capture session state but exclude interrupts
* const noInterrupts = agent.takeSnapshot({ preset: 'session', exclude: ['interrupts'] })
*
* // Attach application-owned metadata
* const withMeta = agent.takeSnapshot({ preset: 'session', appData: { userId: 'u-123' } })
* ```
*/
public takeSnapshot(options: TakeSnapshotOptions): Snapshot {
return takeSnapshotInternal(this, options)
}
/**
* Restores agent state from a previously captured snapshot.
*
* Only fields present in `snapshot.data` are restored; absent fields are left
* unchanged. This allows partial snapshots to update specific aspects of state
* without affecting others.
*
* @param snapshot - The snapshot to restore from
* @throws Error if `snapshot.schemaVersion` is incompatible or scope is wrong
*
* @example
* ```typescript
* // Save and restore a conversation checkpoint
* const checkpoint = agent.takeSnapshot({ preset: 'session' })
*
* // ... agent continues processing ...
*
* // Restore to the checkpoint
* agent.loadSnapshot(checkpoint)
*
* // Restore from a JSON-serialized snapshot (e.g. from storage)
* const stored = JSON.parse(savedSnapshotJson)
* agent.loadSnapshot(stored)
* ```
*/
public loadSnapshot(snapshot: Snapshot): void {
loadSnapshotInternal(this, snapshot)
}
/**
* Invokes hook callbacks and printer for a stream event.
*
* @param event - The event to process
* @returns The event after processing
*/
private async _invokeCallbacks(event: AgentStreamEvent): Promise<AgentStreamEvent> {
if (event instanceof HookableEvent) {
await this._hooksRegistry.invokeCallbacks(event)
}
this._printer?.processEvent(event)
return event
}
/**
* Internal implementation of the agent streaming logic.
* Separated to centralize printer event processing in the public stream method.
*
* @param args - Arguments for invoking the agent
* @param options - Optional per-invocation options
* @returns Async generator that yields AgentStreamEvent objects and returns AgentResult
*/
private async *_stream(
args: InvokeArgs,
options?: InvokeOptions
): AsyncGenerator<AgentStreamEvent, AgentResult, undefined> {
let currentArgs: InvokeArgs | undefined = args
let result: AgentResult | undefined
// Resolve structured output schema from per-invocation options or constructor config
const structuredOutputSchema = options?.structuredOutputSchema ?? this._structuredOutputSchema
const structuredOutputTool = structuredOutputSchema ? new StructuredOutputTool(structuredOutputSchema) : undefined
let structuredOutputChoice: ToolChoice | undefined
// Resolve per-invocation state once. The same object is threaded through
// every lifecycle hook event, every tool context, and is surfaced on the
// AgentResult. Mutations by hooks/tools are visible across all recursive
// agent loop cycles within this invocation.
const invocationState: InvocationState = options?.invocationState ?? {}
// Handle interrupt responses if present in input
const interruptResponses = this._extractInterruptResponses(args)
if (interruptResponses.length > 0) {
this._interruptState.resume(interruptResponses)
}
// Reject non-interrupt input while in interrupted state
if (this._interruptState.activated && interruptResponses.length === 0) {
throw new TypeError('Agent is in an interrupted state. Resume by invoking with interruptResponse content blocks.')
}
const beforeInvocationEvent = new BeforeInvocationEvent({ agent: this, invocationState })
yield beforeInvocationEvent
if (beforeInvocationEvent.cancel) {
const cancelText =
typeof beforeInvocationEvent.cancel === 'string' ? beforeInvocationEvent.cancel : 'invocation denied by hook'
const message = new Message({ role: 'assistant', content: [new TextBlock(cancelText)] })
yield this._appendMessage(message, invocationState)
yield new AfterInvocationEvent({ agent: this, invocationState })
return new AgentResult({
stopReason: 'endTurn',
lastMessage: message,
traces: this._tracer.localTraces,
metrics: this._meter.metrics,
invocationState,
})
}
// Normalize input to get the user messages for telemetry
const inputMessages = this._normalizeInput(args)
// Start agent trace span
this._meter.startNewInvocation()
const agentModelId = this.model.modelId
const agentSpanOptions: Parameters<Tracer['startAgentSpan']>[0] = {
messages: inputMessages,
agentName: this.name,
agentId: this.id,
tools: this.tools,
}
if (agentModelId) agentSpanOptions.modelId = agentModelId
if (this.systemPrompt !== undefined) agentSpanOptions.systemPrompt = this.systemPrompt
const agentSpan = this._tracer.startAgentSpan(agentSpanOptions)
let caughtError: Error | undefined
try {
// Register structured output tool if schema provided
if (structuredOutputTool) {
this._toolRegistry.add(structuredOutputTool)
}
// Main agent loop - continues until model stops without requesting tools
while (true) {
this._throwIfCancelled()
// Start metrics cycle tracking
const { cycleId, startTime: cycleStartTime } = this._meter.startCycle()
// Create agent loop cycle span within agent span context
const cycleSpan = this._tracer.startAgentLoopSpan({
cycleId,
messages: this.messages,
})
try {
// Normalize input and append user messages on first invocation only
if (currentArgs !== undefined) {
const messagesToAppend = this._normalizeInput(currentArgs)
for (const message of messagesToAppend) {
yield this._appendMessage(message, invocationState)
}
currentArgs = undefined
}
// Check if we're resuming from a tool interrupt
const pendingExecution = this._interruptState.getPendingExecution()
let assistantMessage: Message
let completedToolResults: Map<string, ToolResultBlock> | undefined
if (pendingExecution) {
// Resume from stored state - skip model call
assistantMessage = pendingExecution.assistantMessage
completedToolResults = pendingExecution.completedToolResults
this._interruptState.clearPendingToolExecution()
} else {
const modelResult = yield* this._invokeModel(invocationState, structuredOutputChoice)
if (modelResult.stopReason !== 'toolUse') {
// Schema set, we already forced, and the model still refused.
// Throw before closing the span so the cycle span records the error.
if (structuredOutputTool && structuredOutputChoice) {
throw new StructuredOutputError(
'The model failed to invoke the structured output tool even after it was forced.'
)
}
this._meter.endCycle(cycleStartTime)
this._tracer.endAgentLoopSpan(cycleSpan)
// Schema set, model ignored the tool — drop the response and force the tool next cycle.
// Appending the plain-text turn here would leave the conversation ending on an
// assistant message, which providers like Bedrock reject as assistant prefill.
if (structuredOutputTool) {
structuredOutputChoice = { tool: { name: STRUCTURED_OUTPUT_TOOL_NAME } }
logger.debug(
'structured output schema set but model responded with plain text; forcing tool use on next cycle'
)
continue
}
// Normal end of turn.
yield this._appendMessage(modelResult.message, invocationState)
result = new AgentResult({
stopReason: modelResult.stopReason,
lastMessage: modelResult.message,
traces: this._tracer.localTraces,
metrics: this._meter.metrics,
invocationState,
})
return result
}
// Cancel before tool execution: create error results for all pending tools
if (this.isCancelled) {
const toolUseBlocks = modelResult.message.content.filter(
(block): block is ToolUseBlock => block.type === 'toolUseBlock'
)
const cancelBlocks = toolUseBlocks.map(
(block) =>
new ToolResultBlock({
toolUseId: block.toolUseId,
status: 'error',
content: [new TextBlock('Tool execution cancelled')],
})
)
const toolResultMessage = new Message({ role: 'user', content: cancelBlocks })
yield this._appendMessage(modelResult.message, invocationState)
yield this._appendMessage(toolResultMessage, invocationState)
this._meter.endCycle(cycleStartTime)
this._tracer.endAgentLoopSpan(cycleSpan)
result = new AgentResult({
stopReason: 'cancelled',
lastMessage: modelResult.message,
traces: this._tracer.localTraces,
metrics: this._meter.metrics,
invocationState,
})
return result
}
assistantMessage = modelResult.message
}