@mastra/mcp-docs-server 1.1.42 → 1.1.43-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.docs/docs/agents/acp.md +21 -158
- package/.docs/docs/agents/processors.md +143 -0
- package/.docs/docs/agents/signals.md +229 -9
- package/.docs/docs/build-with-ai/skills.md +3 -3
- package/.docs/docs/editor/overview.md +11 -10
- package/.docs/docs/getting-started/build-with-ai.md +37 -0
- package/.docs/docs/mastra-platform/observability.md +4 -4
- package/.docs/docs/memory/multi-user-threads.md +1 -1
- package/.docs/docs/memory/working-memory.md +27 -0
- package/.docs/docs/observability/metrics/querying.md +1 -1
- package/.docs/docs/server/pubsub.md +124 -0
- package/.docs/docs/studio/auth.md +20 -0
- package/.docs/reference/acp/acp-agent.md +228 -0
- package/.docs/reference/acp/create-acp-tool.md +131 -0
- package/.docs/reference/agents/agent.md +51 -1
- package/.docs/reference/agents/durable-agent.md +239 -0
- package/.docs/reference/cli/mastra.md +5 -5
- package/.docs/reference/client-js/agents.md +41 -7
- package/.docs/reference/index.md +9 -0
- package/.docs/reference/processors/response-cache.md +2 -2
- package/.docs/reference/pubsub/base.md +168 -0
- package/.docs/reference/pubsub/caching-pubsub.md +102 -0
- package/.docs/reference/pubsub/event-emitter.md +72 -0
- package/.docs/reference/pubsub/google-cloud-pubsub.md +94 -0
- package/.docs/reference/pubsub/redis-streams.md +108 -0
- package/.docs/reference/pubsub/unix-socket-pubsub.md +52 -0
- package/.docs/reference/storage/libsql.md +6 -0
- package/.docs/reference/storage/mongodb.md +3 -0
- package/.docs/reference/storage/postgresql.md +3 -0
- package/CHANGELOG.md +8 -0
- package/package.json +5 -5
- package/.docs/docs/agents/response-caching.md +0 -150
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
# AcpAgent class
|
|
2
|
+
|
|
3
|
+
The `AcpAgent` class wraps an Agent Client Protocol (ACP)-compatible coding agent as a Mastra subagent. Use it when a parent Mastra agent should delegate repository inspection, code edits, or other ACP-backed tasks to a named subagent.
|
|
4
|
+
|
|
5
|
+
If you want the parent agent to call the ACP agent as a tool instead, use [`createACPTool()`](https://mastra.ai/reference/acp/create-acp-tool).
|
|
6
|
+
|
|
7
|
+
## Usage example
|
|
8
|
+
|
|
9
|
+
Register an ACP-compatible coding agent in a parent agent's `agents` map:
|
|
10
|
+
|
|
11
|
+
```typescript
|
|
12
|
+
import { AcpAgent } from '@mastra/acp'
|
|
13
|
+
import { Agent } from '@mastra/core/agent'
|
|
14
|
+
|
|
15
|
+
const codeAgent = new AcpAgent({
|
|
16
|
+
id: 'code-agent',
|
|
17
|
+
name: 'Code Agent',
|
|
18
|
+
description: 'An ACP-compatible coding agent that can inspect and edit files',
|
|
19
|
+
command: 'acp-agent',
|
|
20
|
+
args: ['--stdio'],
|
|
21
|
+
cwd: process.cwd(),
|
|
22
|
+
})
|
|
23
|
+
|
|
24
|
+
export const codeSupervisor = new Agent({
|
|
25
|
+
id: 'code-supervisor',
|
|
26
|
+
name: 'Code Supervisor',
|
|
27
|
+
instructions: 'Delegate code editing tasks to the code-agent subagent.',
|
|
28
|
+
model: 'openai/gpt-5.5',
|
|
29
|
+
agents: {
|
|
30
|
+
codeAgent,
|
|
31
|
+
},
|
|
32
|
+
})
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
For Claude Code, ACP support is provided by the `@agentclientprotocol/claude-agent-acp` bridge package. Configure the ACP agent command to run the bridge, then select a Claude model after session creation:
|
|
36
|
+
|
|
37
|
+
```typescript
|
|
38
|
+
import { AcpAgent } from '@mastra/acp'
|
|
39
|
+
|
|
40
|
+
export const claudeCodeAgent = new AcpAgent({
|
|
41
|
+
id: 'claude-code-agent',
|
|
42
|
+
name: 'Claude Code Agent',
|
|
43
|
+
description: 'Use Claude Code through ACP.',
|
|
44
|
+
command: 'npx',
|
|
45
|
+
args: ['@agentclientprotocol/claude-agent-acp'],
|
|
46
|
+
cwd: process.cwd(),
|
|
47
|
+
model: 'claude-sonnet-4-6',
|
|
48
|
+
})
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
## Constructor parameters
|
|
52
|
+
|
|
53
|
+
**id** (`string`): Unique identifier for the subagent.
|
|
54
|
+
|
|
55
|
+
**name** (`string`): Display name used during agent delegation. Defaults to \`id\`.
|
|
56
|
+
|
|
57
|
+
**description** (`string`): Description shown to the model when it can delegate to this subagent.
|
|
58
|
+
|
|
59
|
+
**command** (`string`): ACP agent executable to spawn.
|
|
60
|
+
|
|
61
|
+
**args** (`string[]`): Arguments passed to the ACP agent executable. (Default: `[]`)
|
|
62
|
+
|
|
63
|
+
**env** (`Record<string, string>`): Environment variables to merge with the current process environment when spawning the ACP process.
|
|
64
|
+
|
|
65
|
+
**cwd** (`string`): Working directory for the ACP process and ACP session. Also used as the default local filesystem base path. (Default: `process.cwd()`)
|
|
66
|
+
|
|
67
|
+
**session** (`Partial<NewSessionRequest>`): ACP session creation options. Defaults to \`cwd\` or \`process.cwd()\` and an empty MCP server list.
|
|
68
|
+
|
|
69
|
+
**initialize** (`Partial<InitializeRequest>`): ACP initialization options. Defaults to Mastra client information, the current ACP protocol version, and read/write filesystem capabilities.
|
|
70
|
+
|
|
71
|
+
**authMethodId** (`string`): ACP authentication method ID to invoke after initialization and before session creation.
|
|
72
|
+
|
|
73
|
+
**persistSession** (`boolean`): Whether to keep the ACP process and session alive after each prompt. Set to \`false\` to stop the process after each prompt completes. (Default: `true`)
|
|
74
|
+
|
|
75
|
+
**onPermissionRequest** (`(request: RequestPermissionRequest) => Promise<RequestPermissionResponse>`): Callback invoked when the ACP agent requests permission. Defaults to selecting the first permission option, or cancelling when no option is available.
|
|
76
|
+
|
|
77
|
+
**workspace** (`Workspace`): Workspace used for ACP file read and write requests. Defaults to a \`Workspace\` backed by \`LocalFilesystem\` at \`cwd\` or \`process.cwd()\`.
|
|
78
|
+
|
|
79
|
+
**model** (`ModelId`): Model ID to select after ACP session creation using the ACP \`session/set\_model\` method.
|
|
80
|
+
|
|
81
|
+
## Properties
|
|
82
|
+
|
|
83
|
+
**id** (`TId`): Readonly subagent identifier from the constructor options.
|
|
84
|
+
|
|
85
|
+
**name** (`string`): Readonly display name for this subagent.
|
|
86
|
+
|
|
87
|
+
**description** (`string`): Readonly description shown when the parent agent can delegate to this subagent.
|
|
88
|
+
|
|
89
|
+
**connection** (`ACPConnection`): Readonly ACP connection used to start the agent process, create sessions, send prompts, stream updates, and manage models.
|
|
90
|
+
|
|
91
|
+
## Methods
|
|
92
|
+
|
|
93
|
+
### Generation
|
|
94
|
+
|
|
95
|
+
#### `generate(messages, options?)`
|
|
96
|
+
|
|
97
|
+
Sends the prompt to the ACP agent, buffers text chunks from the ACP response, and returns a Mastra subagent generate result.
|
|
98
|
+
|
|
99
|
+
```typescript
|
|
100
|
+
const result = await codeAgent.generate('Inspect the repository and summarize the test setup')
|
|
101
|
+
|
|
102
|
+
console.log(result.text)
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
#### `stream(messages, options?)`
|
|
106
|
+
|
|
107
|
+
Sends the prompt to the ACP agent and returns a Mastra subagent stream result. ACP `agent_message_chunk` updates are emitted as Mastra `text-delta` chunks.
|
|
108
|
+
|
|
109
|
+
```typescript
|
|
110
|
+
const result = await codeAgent.stream('Refactor the selected module and explain each change')
|
|
111
|
+
|
|
112
|
+
for await (const chunk of result.fullStream) {
|
|
113
|
+
if (chunk.type === 'text-delta') {
|
|
114
|
+
process.stdout.write(chunk.payload.text)
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
`resumeGenerate()` and `resumeStream()` are not supported and throw an error when called.
|
|
120
|
+
|
|
121
|
+
### Model management
|
|
122
|
+
|
|
123
|
+
#### `getAvailableModels()`
|
|
124
|
+
|
|
125
|
+
Starts the ACP process if needed and returns the model list advertised by the ACP session.
|
|
126
|
+
|
|
127
|
+
```typescript
|
|
128
|
+
const models = await codeAgent.getAvailableModels()
|
|
129
|
+
// [{ modelId: 'claude-sonnet-4-6', name: 'Claude Sonnet' }, ...]
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
#### `setModel(modelId)`
|
|
133
|
+
|
|
134
|
+
Selects a model for the active ACP session. If the ACP agent advertises available models, the model ID must match one of them.
|
|
135
|
+
|
|
136
|
+
```typescript
|
|
137
|
+
await codeAgent.setModel('claude-sonnet-4-6')
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
## Session lifecycle
|
|
141
|
+
|
|
142
|
+
`AcpAgent` starts the configured `command` on first use, initializes the ACP client, and creates an ACP session. By default, `persistSession` is `true`, so the process and session stay alive across `generate()`, `stream()`, `getAvailableModels()`, and `setModel()` calls.
|
|
143
|
+
|
|
144
|
+
Set `persistSession: false` when each prompt should run in a fresh ACP process:
|
|
145
|
+
|
|
146
|
+
```typescript
|
|
147
|
+
import { AcpAgent } from '@mastra/acp'
|
|
148
|
+
|
|
149
|
+
export const codeAgent = new AcpAgent({
|
|
150
|
+
id: 'code-agent',
|
|
151
|
+
description: 'Run one isolated ACP coding task',
|
|
152
|
+
command: 'acp-agent',
|
|
153
|
+
args: ['--stdio'],
|
|
154
|
+
cwd: process.cwd(),
|
|
155
|
+
persistSession: false,
|
|
156
|
+
})
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
With `persistSession: false`, `@mastra/acp` stops the ACP process after each prompt completes.
|
|
160
|
+
|
|
161
|
+
## Workspace integration
|
|
162
|
+
|
|
163
|
+
ACP file operations go through Mastra's `Workspace` abstraction. If you do not pass `workspace`, `@mastra/acp` creates a `Workspace` backed by `LocalFilesystem` and uses `cwd` or `process.cwd()` as the filesystem base path.
|
|
164
|
+
|
|
165
|
+
Pass a custom `Workspace` when the ACP agent should read and write through a specific filesystem implementation:
|
|
166
|
+
|
|
167
|
+
```typescript
|
|
168
|
+
import { AcpAgent } from '@mastra/acp'
|
|
169
|
+
import { LocalFilesystem, Workspace } from '@mastra/core/workspace'
|
|
170
|
+
|
|
171
|
+
const workspace = new Workspace({
|
|
172
|
+
filesystem: new LocalFilesystem({
|
|
173
|
+
basePath: process.cwd(),
|
|
174
|
+
}),
|
|
175
|
+
})
|
|
176
|
+
|
|
177
|
+
export const codeAgent = new AcpAgent({
|
|
178
|
+
id: 'code-agent',
|
|
179
|
+
description: 'Run coding tasks in a controlled workspace',
|
|
180
|
+
command: 'acp-agent',
|
|
181
|
+
args: ['--stdio'],
|
|
182
|
+
workspace,
|
|
183
|
+
})
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
Use `cwd` and `workspace` together when the ACP process should start in one directory but file operations should use an explicitly configured workspace root.
|
|
187
|
+
|
|
188
|
+
## Permission handling
|
|
189
|
+
|
|
190
|
+
ACP agents may ask the client to choose a permission option before they continue. By default, `AcpAgent` selects the first option returned by the ACP agent, or cancels when no option is available.
|
|
191
|
+
|
|
192
|
+
Pass `onPermissionRequest` to inspect the request and return your own permission response:
|
|
193
|
+
|
|
194
|
+
```typescript
|
|
195
|
+
import { AcpAgent } from '@mastra/acp'
|
|
196
|
+
|
|
197
|
+
export const codeAgent = new AcpAgent({
|
|
198
|
+
id: 'code-agent',
|
|
199
|
+
description: 'Use an ACP-compatible coding agent',
|
|
200
|
+
command: 'acp-agent',
|
|
201
|
+
args: ['--stdio'],
|
|
202
|
+
async onPermissionRequest(request) {
|
|
203
|
+
const allowOption = request.options.find(option => option.name === 'Allow')
|
|
204
|
+
|
|
205
|
+
if (!allowOption) {
|
|
206
|
+
return { outcome: { outcome: 'cancelled' } }
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
return {
|
|
210
|
+
outcome: {
|
|
211
|
+
outcome: 'selected',
|
|
212
|
+
optionId: allowOption.optionId,
|
|
213
|
+
},
|
|
214
|
+
}
|
|
215
|
+
},
|
|
216
|
+
})
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
Use this callback to enforce local policy, inspect the permission title, or route the decision to your own approval flow.
|
|
220
|
+
|
|
221
|
+
## Related
|
|
222
|
+
|
|
223
|
+
- [Agent Client Protocol docs](https://mastra.ai/docs/agents/acp)
|
|
224
|
+
- [createACPTool() reference](https://mastra.ai/reference/acp/create-acp-tool)
|
|
225
|
+
- [Agent reference](https://mastra.ai/reference/agents/agent)
|
|
226
|
+
- [Subagents](https://mastra.ai/docs/agents/supervisor-agents)
|
|
227
|
+
- [Agent Client Protocol introduction](https://agentclientprotocol.com/overview/introduction)
|
|
228
|
+
- [Agent Client Protocol schema](https://agentclientprotocol.com/protocol/schema)
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
# createACPTool()
|
|
2
|
+
|
|
3
|
+
The `createACPTool()` function creates a Mastra tool that sends a `task` string to an Agent Client Protocol (ACP)-compatible coding agent and returns the final ACP response as `output`. Use it when a parent agent should decide when to call the ACP agent as a tool.
|
|
4
|
+
|
|
5
|
+
If you want to register the ACP agent as a Mastra subagent instead, use the [`AcpAgent` class](https://mastra.ai/reference/acp/acp-agent).
|
|
6
|
+
|
|
7
|
+
## Usage example
|
|
8
|
+
|
|
9
|
+
Create a code editing tool and register it on a parent agent:
|
|
10
|
+
|
|
11
|
+
```typescript
|
|
12
|
+
import { createACPTool } from '@mastra/acp'
|
|
13
|
+
import { Agent } from '@mastra/core/agent'
|
|
14
|
+
|
|
15
|
+
const codeAgentTool = createACPTool({
|
|
16
|
+
id: 'code-agent',
|
|
17
|
+
description: 'Use an ACP-compatible coding agent to inspect and edit code',
|
|
18
|
+
command: 'acp-agent',
|
|
19
|
+
args: ['--stdio'],
|
|
20
|
+
cwd: process.cwd(),
|
|
21
|
+
})
|
|
22
|
+
|
|
23
|
+
export const codeSupervisor = new Agent({
|
|
24
|
+
id: 'code-supervisor',
|
|
25
|
+
name: 'Code Supervisor',
|
|
26
|
+
instructions: 'Use the code-agent tool when a task requires repository inspection or code edits.',
|
|
27
|
+
model: 'openai/gpt-5.5',
|
|
28
|
+
tools: {
|
|
29
|
+
codeAgentTool,
|
|
30
|
+
},
|
|
31
|
+
})
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Parameters
|
|
35
|
+
|
|
36
|
+
**id** (`string`): Unique identifier for the Mastra tool.
|
|
37
|
+
|
|
38
|
+
**description** (`string`): Description shown to the model when it can call this tool.
|
|
39
|
+
|
|
40
|
+
**command** (`string`): ACP agent executable to spawn.
|
|
41
|
+
|
|
42
|
+
**args** (`string[]`): Arguments passed to the ACP agent executable. (Default: `[]`)
|
|
43
|
+
|
|
44
|
+
**env** (`Record<string, string>`): Environment variables to merge with the current process environment when spawning the ACP process.
|
|
45
|
+
|
|
46
|
+
**cwd** (`string`): Working directory for the ACP process and ACP session. Also used as the default local filesystem base path. (Default: `process.cwd()`)
|
|
47
|
+
|
|
48
|
+
**session** (`Partial<NewSessionRequest>`): ACP session creation options. Defaults to \`cwd\` or \`process.cwd()\` and an empty MCP server list.
|
|
49
|
+
|
|
50
|
+
**initialize** (`Partial<InitializeRequest>`): ACP initialization options. Defaults to Mastra client information, the current ACP protocol version, and read/write filesystem capabilities.
|
|
51
|
+
|
|
52
|
+
**authMethodId** (`string`): ACP authentication method ID to invoke after initialization and before session creation.
|
|
53
|
+
|
|
54
|
+
**persistSession** (`boolean`): Whether the ACP connection created for a tool execution disconnects after the prompt. Set to \`false\` to stop the process after each prompt completes. (Default: `true`)
|
|
55
|
+
|
|
56
|
+
**onPermissionRequest** (`(request: RequestPermissionRequest) => Promise<RequestPermissionResponse>`): Callback invoked when the ACP agent requests permission. Defaults to selecting the first permission option, or cancelling when no option is available.
|
|
57
|
+
|
|
58
|
+
**workspace** (`Workspace`): Workspace option from the shared ACP connection options. During tool execution, \`createACPTool()\` passes the current Mastra workspace from the execution context when one is available; otherwise the ACP connection falls back to a local filesystem workspace. Use \`AcpAgent\` when you need to provide an explicit workspace instance.
|
|
59
|
+
|
|
60
|
+
**model** (`ModelId`): Model ID to select after ACP session creation using the ACP \`session/set\_model\` method.
|
|
61
|
+
|
|
62
|
+
## Input schema
|
|
63
|
+
|
|
64
|
+
**task** (`string`): The task to send to the ACP agent.
|
|
65
|
+
|
|
66
|
+
## Output schema
|
|
67
|
+
|
|
68
|
+
**output** (`string`): The final text output returned by the ACP agent.
|
|
69
|
+
|
|
70
|
+
## Suspend and resume schema
|
|
71
|
+
|
|
72
|
+
`createACPTool()` defines suspend and resume schemas for permission request payloads. Permission decisions are returned through `onPermissionRequest`; by default, `@mastra/acp` selects the first option returned by the ACP agent, or cancels when no option is available.
|
|
73
|
+
|
|
74
|
+
### Suspend payload
|
|
75
|
+
|
|
76
|
+
**permissionRequest** (`{ title: string; options: { optionId: string; name: string }[] }`): Permission request title and selectable options returned by the ACP agent.
|
|
77
|
+
|
|
78
|
+
### Resume payload
|
|
79
|
+
|
|
80
|
+
**optionId** (`string`): Permission option ID to select when resuming with \`outcome: "selected"\`.
|
|
81
|
+
|
|
82
|
+
**outcome** (`"selected" | "cancelled"`): Permission decision used to continue or cancel the ACP request.
|
|
83
|
+
|
|
84
|
+
## Session lifecycle
|
|
85
|
+
|
|
86
|
+
Each tool execution creates an ACP connection, starts the configured `command`, initializes the ACP client, creates an ACP session, and sends the `task` with ACP `session/prompt`.
|
|
87
|
+
|
|
88
|
+
By default, `persistSession` is `true` for the ACP connection created during tool execution. Set `persistSession: false` when the ACP process should stop as soon as that prompt completes.
|
|
89
|
+
|
|
90
|
+
Use [`AcpAgent`](https://mastra.ai/reference/acp/acp-agent) when you need a reusable ACP subagent instance with explicit session lifecycle control across calls.
|
|
91
|
+
|
|
92
|
+
## Permission handling
|
|
93
|
+
|
|
94
|
+
ACP agents may ask the client to choose a permission option before they continue. By default, `@mastra/acp` selects the first option returned by the ACP agent, or cancels when no option is available.
|
|
95
|
+
|
|
96
|
+
Pass `onPermissionRequest` to inspect the request and return your own permission response:
|
|
97
|
+
|
|
98
|
+
```typescript
|
|
99
|
+
import { createACPTool } from '@mastra/acp'
|
|
100
|
+
|
|
101
|
+
export const codeAgentTool = createACPTool({
|
|
102
|
+
id: 'code-agent',
|
|
103
|
+
description: 'Use an ACP-compatible coding agent',
|
|
104
|
+
command: 'acp-agent',
|
|
105
|
+
args: ['--stdio'],
|
|
106
|
+
async onPermissionRequest(request) {
|
|
107
|
+
const allowOption = request.options.find(option => option.name === 'Allow')
|
|
108
|
+
|
|
109
|
+
if (!allowOption) {
|
|
110
|
+
return { outcome: { outcome: 'cancelled' } }
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
return {
|
|
114
|
+
outcome: {
|
|
115
|
+
outcome: 'selected',
|
|
116
|
+
optionId: allowOption.optionId,
|
|
117
|
+
},
|
|
118
|
+
}
|
|
119
|
+
},
|
|
120
|
+
})
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
Use this callback to enforce local policy, inspect the permission title, or route the decision to your own approval flow.
|
|
124
|
+
|
|
125
|
+
## Related
|
|
126
|
+
|
|
127
|
+
- [Agent Client Protocol docs](https://mastra.ai/docs/agents/acp)
|
|
128
|
+
- [AcpAgent class reference](https://mastra.ai/reference/acp/acp-agent)
|
|
129
|
+
- [Tool reference](https://mastra.ai/reference/tools/create-tool)
|
|
130
|
+
- [Agent Client Protocol introduction](https://agentclientprotocol.com/overview/introduction)
|
|
131
|
+
- [Agent Client Protocol schema](https://agentclientprotocol.com/protocol/schema)
|
|
@@ -141,7 +141,7 @@ The model receives this as:
|
|
|
141
141
|
<user name="Devin" from="slack">Can we simplify the API surface?</user>
|
|
142
142
|
```
|
|
143
143
|
|
|
144
|
-
The UI sees
|
|
144
|
+
The UI sees the message contents and can also read `attributes` and `metadata` off the signal message for custom rendering (e.g. showing user names, avatars, or platform badges).
|
|
145
145
|
|
|
146
146
|
### `sendMessage(message, options)`
|
|
147
147
|
|
|
@@ -196,6 +196,54 @@ Sends a signal to an active run or memory thread.
|
|
|
196
196
|
|
|
197
197
|
Returns `{ accepted: true, runId: string, signal: CreatedAgentSignal, persisted?: Promise<void> }`. `persisted` is only present for `persist` behavior and resolves when Mastra finishes writing the signal to memory.
|
|
198
198
|
|
|
199
|
+
### `sendNotificationSignal(notification, options)`
|
|
200
|
+
|
|
201
|
+
Creates or coalesces a notification inbox record, resolves the notification delivery policy, and sends a notification signal when the decision is immediate.
|
|
202
|
+
|
|
203
|
+
```typescript
|
|
204
|
+
const result = await agent.sendNotificationSignal(
|
|
205
|
+
{
|
|
206
|
+
source: 'github',
|
|
207
|
+
kind: 'ci-status',
|
|
208
|
+
priority: 'high',
|
|
209
|
+
summary: 'CI failed on main: 3 tests failed.',
|
|
210
|
+
dedupeKey: 'github:acme/app:main:ci',
|
|
211
|
+
},
|
|
212
|
+
{
|
|
213
|
+
resourceId: 'user-123',
|
|
214
|
+
threadId: 'thread-abc',
|
|
215
|
+
},
|
|
216
|
+
)
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
**notification.source** (`string`): External system that produced the notification, such as \`github\`, \`slack\`, or \`email\`.
|
|
220
|
+
|
|
221
|
+
**notification.kind** (`string`): Notification kind within the source, such as \`ci-status\`, \`mention\`, or \`direct-message\`.
|
|
222
|
+
|
|
223
|
+
**notification.summary** (`string`): LLM-facing summary used as the notification signal contents.
|
|
224
|
+
|
|
225
|
+
**notification.priority** (`'low' | 'medium' | 'high' | 'urgent'`): Priority used by the notification delivery policy. Defaults to \`medium\`.
|
|
226
|
+
|
|
227
|
+
**notification.payload** (`unknown`): Structured payload stored on the inbox record for tools or application code.
|
|
228
|
+
|
|
229
|
+
**notification.dedupeKey** (`string`): Key used to coalesce duplicate pending notifications from the same source and thread.
|
|
230
|
+
|
|
231
|
+
**notification.coalesceKey** (`string`): Key used to combine related pending notifications from the same source and thread.
|
|
232
|
+
|
|
233
|
+
**notification.attributes** (`Record<string, JSONValue>`): Extra attributes copied onto the emitted notification signal.
|
|
234
|
+
|
|
235
|
+
**notification.metadata** (`Record<string, unknown>`): Application metadata stored on the inbox record.
|
|
236
|
+
|
|
237
|
+
**options.resourceId** (`string`): Resource ID for the notification inbox and target memory thread.
|
|
238
|
+
|
|
239
|
+
**options.threadId** (`string`): Thread ID for the notification inbox and target memory thread.
|
|
240
|
+
|
|
241
|
+
**options.ifIdle.streamOptions** (`AgentExecutionOptions`): Options for the stream that starts when an immediate notification wakes an idle thread.
|
|
242
|
+
|
|
243
|
+
Returns `{ accepted: true, record: NotificationRecord, decision: NotificationDeliveryDecision, runId?: string, signal?: CreatedAgentSignal, persisted?: Promise<void> }`. `record` is the stored inbox record. `decision` is the delivery-policy result. `signal` and `runId` are present when ingress emits a signal immediately, including the immediate summary emitted for active high-priority notifications. `persisted` is present when the emitted signal is persisted without waking an idle thread.
|
|
244
|
+
|
|
245
|
+
Default delivery is priority-aware. `urgent` notifications deliver immediately. `high` notifications deliver immediately when the thread is idle; when the thread is active, Mastra emits a summary immediately and keeps `deliverAt` for later full delivery when the thread is idle. `medium` notifications deliver immediately when idle and batch into summaries when active. `low` notifications batch into summaries in both active and idle threads; idle low-priority summaries reach subscribers without waking the model loop. For the full flow, visit [Signals](https://mastra.ai/docs/agents/signals).
|
|
246
|
+
|
|
199
247
|
### `subscribeToThread(options)`
|
|
200
248
|
|
|
201
249
|
Subscribes to raw stream chunks for a memory thread. Use this before calling `sendMessage()`, `queueMessage()`, or `sendSignal()` when you need to render stream output, observe signal echoes, or abort the active run.
|
|
@@ -234,6 +282,8 @@ Returns an `AgentThreadSubscription` object with these members:
|
|
|
234
282
|
|
|
235
283
|
**transform** (`ToolPayloadTransformPolicy`): Shared policy for transforming tool payloads before display streams or user-visible transcript messages receive them. Use per-tool \`transform\` on \`createTool()\` for tool-local rules.
|
|
236
284
|
|
|
285
|
+
**notifications** (`{ deliveryPolicy?: NotificationDeliveryPolicyConfig }`): Notification delivery configuration for \`sendNotificationSignal()\`. \`deliveryPolicy\` can define \`decide\`, \`sources\`, \`priorities\`, or \`default\` rules that return \`deliver\`, \`queue\`, \`defer\`, \`summarize\`, \`persist\`, or \`discard\` decisions.
|
|
286
|
+
|
|
237
287
|
**workflows** (`Record<string, Workflow> | ({ requestContext: RequestContext }) => Record<string, Workflow> | Promise<Record<string, Workflow>>`): Workflows that the agent can execute. Can be static or dynamically resolved.
|
|
238
288
|
|
|
239
289
|
**defaultOptions** (`AgentExecutionOptions | ({ requestContext: RequestContext }) => AgentExecutionOptions | Promise<AgentExecutionOptions>`): Default options used when calling \`stream()\` and \`generate()\`.
|
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
# DurableAgent
|
|
2
|
+
|
|
3
|
+
`DurableAgent` wraps an existing [`Agent`](https://mastra.ai/reference/agents/agent) with durable execution and resumable streams. It runs the agentic loop so that a client can disconnect and reconnect without missing events, and it streams those events over [PubSub](https://mastra.ai/docs/server/pubsub). Use it when a run must outlive a single request or survive a dropped connection.
|
|
4
|
+
|
|
5
|
+
Create one with the [`createDurableAgent`](#createdurableagentoptions) factory, or use [`createEventedAgent`](#createeventedagentoptions) for fire-and-forget execution on the built-in workflow engine. For Inngest-powered execution, use `createInngestAgent` from `@mastra/inngest`.
|
|
6
|
+
|
|
7
|
+
## Usage example
|
|
8
|
+
|
|
9
|
+
```typescript
|
|
10
|
+
import { Mastra } from '@mastra/core'
|
|
11
|
+
import { Agent } from '@mastra/core/agent'
|
|
12
|
+
import { createDurableAgent } from '@mastra/core/agent/durable'
|
|
13
|
+
|
|
14
|
+
const agent = new Agent({
|
|
15
|
+
id: 'my-agent',
|
|
16
|
+
name: 'My Agent',
|
|
17
|
+
instructions: 'You are a helpful assistant',
|
|
18
|
+
model: 'openai/gpt-5.5',
|
|
19
|
+
})
|
|
20
|
+
|
|
21
|
+
const durableAgent = createDurableAgent({ agent })
|
|
22
|
+
|
|
23
|
+
export const mastra = new Mastra({
|
|
24
|
+
agents: { myAgent: durableAgent },
|
|
25
|
+
})
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
Stream a response and read the result. The `cleanup` function unsubscribes from PubSub when you are done with the run:
|
|
29
|
+
|
|
30
|
+
```typescript
|
|
31
|
+
const { output, runId, cleanup } = await durableAgent.stream('Hello!')
|
|
32
|
+
|
|
33
|
+
const text = await output.text
|
|
34
|
+
|
|
35
|
+
cleanup()
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
## `createDurableAgent(options)`
|
|
39
|
+
|
|
40
|
+
Wraps an `Agent` with durable execution and resumable streams. This is the recommended way to create a `DurableAgent`.
|
|
41
|
+
|
|
42
|
+
```typescript
|
|
43
|
+
import { createDurableAgent } from '@mastra/core/agent/durable'
|
|
44
|
+
|
|
45
|
+
const durableAgent = createDurableAgent({ agent })
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Returns: `DurableAgent`
|
|
49
|
+
|
|
50
|
+
### Parameters
|
|
51
|
+
|
|
52
|
+
**agent** (`Agent`): The Agent to wrap with durable execution capabilities. Agent methods delegate to this agent.
|
|
53
|
+
|
|
54
|
+
**id** (`string`): ID override. (Default: `agent.id`)
|
|
55
|
+
|
|
56
|
+
**name** (`string`): Name override. (Default: `agent.name`)
|
|
57
|
+
|
|
58
|
+
**cache** (`MastraServerCache | false`): Cache for stored stream events, which enables resumable streams. If omitted, the agent inherits the cache from the Mastra instance, or uses an InMemoryServerCache. Set to \`false\` to disable caching, which makes streams non-resumable.
|
|
59
|
+
|
|
60
|
+
**pubsub** (`PubSub`): PubSub instance for streaming events. (Default: `EventEmitterPubSub`)
|
|
61
|
+
|
|
62
|
+
**maxSteps** (`number`): Maximum number of steps for the agentic loop.
|
|
63
|
+
|
|
64
|
+
## `createEventedAgent(options)`
|
|
65
|
+
|
|
66
|
+
Wraps an `Agent` with fire-and-forget durable execution on the built-in workflow engine. Like `createDurableAgent`, it returns a result you stream from, but the underlying workflow runs non-blocking (via `startAsync`) instead of running to completion before the stream is wired up. Use it when you want the run to progress independently of the caller. It does not accept `id` or `name` overrides.
|
|
67
|
+
|
|
68
|
+
```typescript
|
|
69
|
+
import { createEventedAgent } from '@mastra/core/agent/durable'
|
|
70
|
+
|
|
71
|
+
const eventedAgent = createEventedAgent({ agent })
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
Returns: `EventedAgent` (a subclass of `DurableAgent`)
|
|
75
|
+
|
|
76
|
+
### Parameters
|
|
77
|
+
|
|
78
|
+
**agent** (`Agent`): The Agent to wrap with evented durable execution capabilities.
|
|
79
|
+
|
|
80
|
+
**cache** (`MastraServerCache | false`): Cache for stored stream events, which enables resumable streams. If omitted, the agent inherits the cache from the Mastra instance, or uses an InMemoryServerCache. Set to \`false\` to disable caching.
|
|
81
|
+
|
|
82
|
+
**pubsub** (`PubSub`): PubSub instance for streaming events. (Default: `EventEmitterPubSub`)
|
|
83
|
+
|
|
84
|
+
**maxSteps** (`number`): Maximum number of steps for the agentic loop.
|
|
85
|
+
|
|
86
|
+
## Constructor parameters
|
|
87
|
+
|
|
88
|
+
The `DurableAgent` class accepts the same options as `createDurableAgent`, plus `cleanupTimeoutMs`. Prefer the factory unless you need to subclass.
|
|
89
|
+
|
|
90
|
+
**agent** (`Agent`): The Agent to wrap with durable execution capabilities.
|
|
91
|
+
|
|
92
|
+
**id** (`string`): ID override. (Default: `agent.id`)
|
|
93
|
+
|
|
94
|
+
**name** (`string`): Name override. (Default: `agent.name`)
|
|
95
|
+
|
|
96
|
+
**cache** (`MastraServerCache | false`): Cache for stored stream events. If omitted, inherits from the Mastra instance or uses an InMemoryServerCache. Set to \`false\` to disable caching.
|
|
97
|
+
|
|
98
|
+
**pubsub** (`PubSub`): PubSub instance for streaming events. (Default: `EventEmitterPubSub`)
|
|
99
|
+
|
|
100
|
+
**maxSteps** (`number`): Maximum number of steps for the agentic loop.
|
|
101
|
+
|
|
102
|
+
**cleanupTimeoutMs** (`number`): Grace period in milliseconds before registry entries are cleaned up automatically after a stream finishes or errors. Set to 0 to disable auto-cleanup and require a manual \`cleanup()\` call. Auto-cleanup does not fire on suspended events. (Default: `30000`)
|
|
103
|
+
|
|
104
|
+
## Methods
|
|
105
|
+
|
|
106
|
+
### Execution
|
|
107
|
+
|
|
108
|
+
#### `stream(messages, options?)`
|
|
109
|
+
|
|
110
|
+
Streams a response using durable execution. Returns immediately with a result whose `output` produces events as the run progresses.
|
|
111
|
+
|
|
112
|
+
```typescript
|
|
113
|
+
const { output, runId, cleanup } = await durableAgent.stream('Hello!', {
|
|
114
|
+
onChunk: chunk => console.log(chunk),
|
|
115
|
+
onFinish: result => console.log('done', result),
|
|
116
|
+
})
|
|
117
|
+
|
|
118
|
+
const text = await output.text
|
|
119
|
+
cleanup()
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
Returns: [`Promise<DurableAgentStreamResult>`](#durableagentstreamresult)
|
|
123
|
+
|
|
124
|
+
#### `resume(runId, resumeData, options?)`
|
|
125
|
+
|
|
126
|
+
Resumes a suspended run, for example after a tool approval. Pass the `runId` from the original stream and the data the run was waiting on. Throws if no registry entry exists for the run.
|
|
127
|
+
|
|
128
|
+
```typescript
|
|
129
|
+
const { output, cleanup } = await durableAgent.resume(runId, {
|
|
130
|
+
approved: true,
|
|
131
|
+
})
|
|
132
|
+
|
|
133
|
+
await output.text
|
|
134
|
+
cleanup()
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
Returns: [`Promise<DurableAgentStreamResult>`](#durableagentstreamresult)
|
|
138
|
+
|
|
139
|
+
#### `observe(runId, options?)`
|
|
140
|
+
|
|
141
|
+
Reconnects to an existing run, replaying cached events before delivering live ones. Use this after a network disconnection. Pass `offset` to start replay from a known position.
|
|
142
|
+
|
|
143
|
+
```typescript
|
|
144
|
+
const { output, cleanup } = await durableAgent.observe(runId, {
|
|
145
|
+
offset: 0,
|
|
146
|
+
onChunk: chunk => console.log(chunk),
|
|
147
|
+
})
|
|
148
|
+
|
|
149
|
+
await output.text
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
Returns: `Promise<DurableAgentStreamResult>`
|
|
153
|
+
|
|
154
|
+
> **Warning:** The `cleanup()` returned by `observe()` destroys the run's registry entries and cached events. Only call it when you are done with the run. If the run is suspended and you intend to resume later, do not call `cleanup()` — let the auto-cleanup timer handle it after the run finishes or errors. Auto-cleanup does not fire on suspended events.
|
|
155
|
+
|
|
156
|
+
## Stream options
|
|
157
|
+
|
|
158
|
+
`stream()` accepts a `DurableAgentStreamOptions` object. It supports the agent execution options below, plus lifecycle callbacks.
|
|
159
|
+
|
|
160
|
+
**runId** (`string`): Unique identifier for this run. Use it later with \`resume()\` or \`observe()\`.
|
|
161
|
+
|
|
162
|
+
**instructions** (`AgentExecutionOptions['instructions']`): Overrides the agent's default instructions for this run. Accepts a static string or the same dynamic instructions value the agent supports.
|
|
163
|
+
|
|
164
|
+
**context** (`ModelMessage[]`): Additional context messages to provide to the agent.
|
|
165
|
+
|
|
166
|
+
**memory** (`object`): Memory configuration for conversation persistence and retrieval.
|
|
167
|
+
|
|
168
|
+
**requestContext** (`RequestContext`): Request context carrying dynamic configuration and state for this run.
|
|
169
|
+
|
|
170
|
+
**maxSteps** (`number`): Maximum number of steps to run for this stream.
|
|
171
|
+
|
|
172
|
+
**toolsets** (`object`): Additional tool sets available for this run.
|
|
173
|
+
|
|
174
|
+
**clientTools** (`object`): Client-side tools available during execution.
|
|
175
|
+
|
|
176
|
+
**toolChoice** (`'auto' | 'none' | 'required' | { type: 'tool'; toolName: string }`): Tool selection strategy.
|
|
177
|
+
|
|
178
|
+
**activeTools** (`string[]`): Restricts execution to the named subset of the agent's tools.
|
|
179
|
+
|
|
180
|
+
**modelSettings** (`object`): Model-specific settings such as temperature.
|
|
181
|
+
|
|
182
|
+
**requireToolApproval** (`boolean`): Require approval for all tool calls, which suspends the run until resumed.
|
|
183
|
+
|
|
184
|
+
**autoResumeSuspendedTools** (`boolean`): Automatically resume tools that suspended, instead of waiting for an external \`resume()\` call.
|
|
185
|
+
|
|
186
|
+
**toolCallConcurrency** (`number`): Maximum number of tool calls to execute concurrently.
|
|
187
|
+
|
|
188
|
+
**includeRawChunks** (`boolean`): Include raw provider chunks in the stream output.
|
|
189
|
+
|
|
190
|
+
**maxProcessorRetries** (`number`): Maximum number of processor retries per generation.
|
|
191
|
+
|
|
192
|
+
**structuredOutput** (`object`): Structured output configuration.
|
|
193
|
+
|
|
194
|
+
**versions** (`object`): Version overrides for sub-agent delegation.
|
|
195
|
+
|
|
196
|
+
**onChunk** (`(chunk: ChunkType) => void | Promise<void>`): Called for each streamed chunk.
|
|
197
|
+
|
|
198
|
+
**onStepFinish** (`(result: AgentStepFinishEventData) => void | Promise<void>`): Called when a step in the agentic loop finishes.
|
|
199
|
+
|
|
200
|
+
**onFinish** (`(result: AgentFinishEventData) => void | Promise<void>`): Called when the run finishes.
|
|
201
|
+
|
|
202
|
+
**onError** (`(error: Error) => void | Promise<void>`): Called when the run errors.
|
|
203
|
+
|
|
204
|
+
**onSuspended** (`(data: AgentSuspendedEventData) => void | Promise<void>`): Called when the run suspends, for example for tool approval.
|
|
205
|
+
|
|
206
|
+
`resume()` and `observe()` accept the same lifecycle callbacks (`onChunk`, `onStepFinish`, `onFinish`, `onError`, `onSuspended`). `observe()` also accepts an `offset` to control where replay starts.
|
|
207
|
+
|
|
208
|
+
## DurableAgentStreamResult
|
|
209
|
+
|
|
210
|
+
The object returned by `stream()`, `resume()`, and `observe()`.
|
|
211
|
+
|
|
212
|
+
```typescript
|
|
213
|
+
interface DurableAgentStreamResult<OUTPUT = undefined> {
|
|
214
|
+
output: MastraModelOutput<OUTPUT>
|
|
215
|
+
readonly fullStream: ReadableStream<any>
|
|
216
|
+
runId: string
|
|
217
|
+
threadId?: string
|
|
218
|
+
resourceId?: string
|
|
219
|
+
cleanup: () => void
|
|
220
|
+
}
|
|
221
|
+
```
|
|
222
|
+
|
|
223
|
+
**output** (`MastraModelOutput`): The streaming output. Await \`output.text\` for the full text, or consume \`output.fullStream\`.
|
|
224
|
+
|
|
225
|
+
**fullStream** (`ReadableStream`): The full event stream, delegating to \`output.fullStream\`.
|
|
226
|
+
|
|
227
|
+
**runId** (`string`): The unique run ID. Pass it to \`resume()\` or \`observe()\` to reconnect.
|
|
228
|
+
|
|
229
|
+
**threadId** (`string`): Thread ID when using memory.
|
|
230
|
+
|
|
231
|
+
**resourceId** (`string`): Resource ID when using memory.
|
|
232
|
+
|
|
233
|
+
**cleanup** (`() => void`): Unsubscribes from PubSub and clears registry entries for the run. Call it when done with the run.
|
|
234
|
+
|
|
235
|
+
## Related
|
|
236
|
+
|
|
237
|
+
- [Agent class](https://mastra.ai/reference/agents/agent)
|
|
238
|
+
- [PubSub](https://mastra.ai/docs/server/pubsub)
|
|
239
|
+
- [`.getMemory()`](https://mastra.ai/reference/agents/getMemory)
|