Class: TemporalAgent
strands.TemporalAgent
A Strands Agent that routes every model call through a Temporal activity.
model is the name of a factory registered in
StrandsPlugin({ models: {...} }). The activityOptions apply to every
model invocation this agent makes. All other options are forwarded to
Strands' Agent constructor (tools, plugins, systemPrompt,
structuredOutputSchema, messages, etc.).
Strands' retryStrategy is disabled; configure retries via
activityOptions.retry here and on the activity options accepted by
activityAsTool, activityAsHook, and TemporalMCPClient.
Hierarchy
-
Agent↳
TemporalAgent
Constructors
constructor
• new TemporalAgent(options?): TemporalAgent
Parameters
| Name | Type |
|---|---|
options? | TemporalAgentOptions |
Returns
Overrides
Agent.constructor
Properties
_interruptState
• _interruptState: InterruptState
Interrupt state for human-in-the-loop workflows.
Inherited from
Agent._interruptState
appState
• Readonly appState: StateStore
App state storage accessible to tools and application logic. State is not passed to the model during inference.
Inherited from
Agent.appState
description
• Optional Readonly description: string
Optional description of what the agent does.
Inherited from
Agent.description
id
• Readonly id: string
The unique identifier of the agent instance.
Inherited from
Agent.id
memoryManager
• Optional Readonly memoryManager: MemoryManager
The memory manager for cross-session memory retrieval and storage, if configured.
Inherited from
Agent.memoryManager
messages
• messages: Message[]
The conversation history of messages between user and assistant.
Inherited from
Agent.messages
model
• model: Model<BaseModelConfig>
The model provider used by the agent for inference.
Inherited from
Agent.model
modelState
• Readonly modelState: 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.
Inherited from
Agent.modelState
name
• Readonly name: string
The name of the agent.
Inherited from
Agent.name
sessionManager
• Optional Readonly sessionManager: SessionManager
The session manager for saving and restoring agent sessions, if configured.
Inherited from
Agent.sessionManager
systemPrompt
• Optional systemPrompt: SystemPrompt
The system prompt to pass to the model provider.
Inherited from
Agent.systemPrompt
Accessors
cancelSignal
• get cancelSignal(): AbortSignal
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.
Returns
AbortSignal
Inherited from
Agent.cancelSignal
isInvoking
• get isInvoking(): boolean
Whether the agent is currently processing an invocation.
Returns
boolean
Inherited from
Agent.isInvoking
sandbox
• get sandbox(): Sandbox
Execution environment for running commands, code, and file operations.
Returns
Sandbox
Throws
DefaultNotConfiguredError if no sandbox is configured for this environment (e.g. browsers, where no host default is registered).
Inherited from
Agent.sandbox
tool
• get tool(): ToolCallerProxy
Direct tool calling accessor.
Returns a proxy where each property is a ToolHandle with
.invoke() and .stream() methods:
const result = await agent.tool.calculator!.invoke({ a: 5, b: 3 })
for await (const event of agent.tool.calculator!.stream({ a: 5, b: 3 })) {
console.log('progress:', event)
}
Supports underscore-to-hyphen and case-insensitive name resolution.
Results are recorded in message history by default (pass
{ recordDirectToolCall: false } to skip).
Returns
ToolCallerProxy
Inherited from
Agent.tool
toolRegistry
• get toolRegistry(): ToolRegistry
The tool registry for managing the agent's tools.
Returns
ToolRegistry
Inherited from
Agent.toolRegistry
tools
• get tools(): Tool[]
The tools this agent can use.
Returns
Tool[]
Inherited from
Agent.tools
Methods
addHook
▸ addHook<T>(eventType, callback, options?): HookCleanup
Register a hook callback for a specific event type.
Type parameters
| Name | Type |
|---|---|
T | extends HookableEvent |
Parameters
| Name | Type | Description |
|---|---|---|
eventType | HookableEventConstructor<T> | The event class constructor to register the callback for |
callback | HookCallback<T> | The callback function to invoke when the event occurs |
options? | HookCallbackOptions | Optional configuration including execution order |
Returns
HookCleanup
Cleanup function that removes the callback when invoked
Example
const agent = new Agent({ model })
const cleanup = agent.addHook(BeforeInvocationEvent, (event) => {
console.log('Invocation started')
})
// Later, to remove the hook:
cleanup()
Inherited from
Agent.addHook
addMiddleware
▸ addMiddleware<TContext, TResult, TEvent>(phase, handler): () => void
Register an Input phase handler that transforms context before execution. Input handlers run before Wrap and Output handlers.
Type parameters
| Name |
|---|
TContext |
TResult |
TEvent |
Parameters
| Name | Type |
|---|---|
phase | MiddlewareInputPhase<TContext, TResult, TEvent> |
handler | MiddlewareInputHandler<TContext> |
Returns
fn
▸ (): void
Returns
void
Example
agent.addMiddleware(InvokeModelStage.Input, async (context) => ({
...context,
systemPrompt: injectToSystemPrompt(context),
}))
Inherited from
Agent.addMiddleware
▸ addMiddleware<TContext, TResult, TEvent>(phase, handler): () => void
Register a Wrap phase handler via the explicit .Wrap sub-token.
Equivalent to passing the stage token directly.
Type parameters
| Name |
|---|
TContext |
TResult |
TEvent |
Parameters
| Name | Type |
|---|---|
phase | MiddlewareWrapPhase<TContext, TResult, TEvent> |
handler | MiddlewareHandler<TContext, TResult, TEvent> |
Returns
fn
▸ (): void
Returns
void
Inherited from
Agent.addMiddleware
▸ addMiddleware<TContext, TResult, TEvent>(phase, handler): () => void
Register an Output phase handler that transforms the result after execution. Output handlers see the result after Wrap handlers complete. Execution order: Input → Wrap → Output.
Type parameters
| Name |
|---|
TContext |
TResult |
TEvent |
Parameters
| Name | Type |
|---|---|
phase | MiddlewareOutputPhase<TContext, TResult, TEvent> |
handler | MiddlewareOutputHandler<TResult> |
Returns
fn
▸ (): void
Returns
void
Example
agent.addMiddleware(InvokeModelStage.Output, async (result) => {
log(`Model returned stopReason=${result.result.stopReason}`)
return result
})
Inherited from
Agent.addMiddleware
▸ addMiddleware<TContext, TResult, TEvent>(stage, handler): () => void
Register a middleware handler for a given stage (Wrap phase). Middleware wraps stage execution and can intercept, transform, or short-circuit operations.
Type parameters
| Name |
|---|
TContext |
TResult |
TEvent |
Parameters
| Name | Type | Description |
|---|---|---|
stage | MiddlewareStage<TContext, TResult, TEvent> | The stage token identifying the interception point |
handler | MiddlewareHandler<TContext, TResult, TEvent> | The middleware handler function (async generator) |
Returns
fn
A cleanup function that removes the middleware when called
▸ (): void
Returns
void
Example
const cleanup = agent.addMiddleware(InvokeModelStage, async function* (context, next) {
const start = Date.now()
const result = yield* next(context)
console.log(`Model call took ${Date.now() - start}ms`)
return result
})
// Later, remove the middleware:
cleanup()
Inherited from
Agent.addMiddleware
asTool
▸ asTool(options?): Tool
Returns a 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 AgentConfig.tools | tools array — it will be wrapped automatically via this method.
Parameters
| Name | Type | Description |
|---|---|---|
options? | AgentAsToolOptions | Optional configuration for the tool name, description, and context preservation |
Returns
Tool
A Tool wrapping this agent
Example
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] })
Inherited from
Agent.asTool
cancel
▸ cancel(): void
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 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.
Returns
void
Example
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'
Inherited from
Agent.cancel
initialize
▸ initialize(): Promise<void>
Returns
Promise<void>
Inherited from
Agent.initialize
invoke
▸ invoke(args, options?): Promise<AgentResult>
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.
Parameters
| Name | Type | Description |
|---|---|---|
args | InvokeArgs | Arguments for invoking the agent |
options? | InvokeOptions | Optional per-invocation options |
Returns
Promise<AgentResult>
Promise that resolves to the final AgentResult
Example
const agent = new Agent({ model, tools })
const result = await agent.invoke('What is 2 + 2?')
console.log(result.lastMessage) // Agent's response
Inherited from
Agent.invoke
loadSnapshot
▸ loadSnapshot(): never
Returns
never
Overrides
Agent.loadSnapshot
stream
▸ stream(args, options?): AsyncGenerator<AgentStreamEvent, AgentResult, undefined>
Streams the agent execution, yielding events and returning the final result.
The agent loop manages the conversation flow by:
- Streaming model responses and yielding all events
- Executing tools when the model requests them
- 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
Parameters
| Name | Type | Description |
|---|---|---|
args | InvokeArgs | Arguments for invoking the agent |
options? | InvokeOptions | Optional per-invocation options |
Returns
AsyncGenerator<AgentStreamEvent, AgentResult, undefined>
Async generator that yields AgentStreamEvent objects and returns AgentResult
Example
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
Inherited from
Agent.stream
takeSnapshot
▸ takeSnapshot(): never
Returns
never
Overrides
Agent.takeSnapshot