@mastra/mcp-docs-server 1.3.6-alpha.7 → 1.3.6

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.
Files changed (69) hide show
  1. package/.docs/docs/agents/processors.md +6 -5
  2. package/.docs/docs/browser.md +0 -2
  3. package/.docs/docs/deployment/mastra-server.md +2 -2
  4. package/.docs/docs/guides/authentication-identity.md +1 -1
  5. package/.docs/docs/harness/agent-controller.md +29 -0
  6. package/.docs/docs/harness/durable-agents.md +45 -9
  7. package/.docs/docs/harness/signals.md +12 -0
  8. package/.docs/docs/memory/message-history.md +15 -8
  9. package/.docs/docs/memory/observational-memory.md +33 -4
  10. package/.docs/docs/sandbox/overview.md +1 -0
  11. package/.docs/docs/server/pubsub.md +2 -0
  12. package/.docs/docs/subagents.md +1 -0
  13. package/.docs/docs/workflows/overview.md +2 -0
  14. package/.docs/integrations/sandboxes/blaxel.md +3 -1
  15. package/.docs/integrations/sandboxes/e2b.md +32 -1
  16. package/.docs/integrations/sandboxes/railway.md +13 -0
  17. package/.docs/integrations/sandboxes/sprites.md +219 -0
  18. package/.docs/integrations.md +1 -0
  19. package/.docs/models/environment-variables.md +2 -1
  20. package/.docs/models/gateways/merge-gateway.md +3 -1
  21. package/.docs/models/gateways/openrouter.md +1 -12
  22. package/.docs/models/gateways/vercel.md +2 -1
  23. package/.docs/models/index.md +3 -2
  24. package/.docs/models/providers/302ai.md +3 -1
  25. package/.docs/models/providers/ambient.md +17 -15
  26. package/.docs/models/providers/coralbricks.md +2 -2
  27. package/.docs/models/providers/cortecs.md +1 -1
  28. package/.docs/models/providers/deepinfra.md +2 -2
  29. package/.docs/models/providers/digitalocean.md +2 -1
  30. package/.docs/models/providers/edenai.md +305 -299
  31. package/.docs/models/providers/empiriolabs.md +4 -8
  32. package/.docs/models/providers/huggingface.md +7 -4
  33. package/.docs/models/providers/hyper.md +4 -6
  34. package/.docs/models/providers/kilo.md +33 -44
  35. package/.docs/models/providers/llmgateway-providers.md +6 -6
  36. package/.docs/models/providers/llmgateway.md +3 -7
  37. package/.docs/models/providers/lowrouter.md +84 -0
  38. package/.docs/models/providers/moark.md +17 -9
  39. package/.docs/models/providers/nano-gpt.md +12 -12
  40. package/.docs/models/providers/nearai.md +22 -3
  41. package/.docs/models/providers/neuralwatt.md +3 -1
  42. package/.docs/models/providers/novita-ai.md +43 -66
  43. package/.docs/models/providers/ofox.md +2 -1
  44. package/.docs/models/providers/tinfoil.md +1 -2
  45. package/.docs/models/providers.md +2 -1
  46. package/.docs/reference/agent-controller/agent-controller-class.md +15 -1
  47. package/.docs/reference/agent-controller/session.md +17 -6
  48. package/.docs/reference/agents/durable-agent.md +40 -4
  49. package/.docs/reference/agents/inngest-agent.md +27 -1
  50. package/.docs/reference/client-js/agent-controller.md +1 -1
  51. package/.docs/reference/client-js/agents.md +2 -2
  52. package/.docs/reference/client-js/datasets.md +19 -0
  53. package/.docs/reference/coding-agent/create-coding-agent.md +2 -2
  54. package/.docs/reference/core/mastra-class.md +12 -4
  55. package/.docs/reference/index.md +2 -0
  56. package/.docs/reference/memory/observational-memory.md +8 -4
  57. package/.docs/reference/processors/file-upload-processor.md +236 -0
  58. package/.docs/reference/processors/processor-interface.md +2 -0
  59. package/.docs/reference/processors/stream-error-retry-processor.md +1 -1
  60. package/.docs/reference/processors/unsupported-file-handler.md +69 -0
  61. package/.docs/reference/pubsub/lease-provider.md +2 -0
  62. package/.docs/reference/pubsub/valkey-streams.md +1 -1
  63. package/.docs/reference/server/routes.md +1 -0
  64. package/.docs/reference/storage/retention.md +21 -18
  65. package/.docs/reference/tools/isolated-vm-transport.md +0 -2
  66. package/.docs/reference/tools/mcp-client.md +5 -0
  67. package/.docs/reference/tools/quickjs-transport.md +0 -2
  68. package/.docs/reference/workspace/platform-sandbox.md +17 -2
  69. package/package.json +6 -6
@@ -116,13 +116,14 @@ const agent = new Agent({
116
116
 
117
117
  ### Error processors are enabled by default
118
118
 
119
- Every agent adds whichever of these three your `errorProcessors` list doesn't already contain:
119
+ Every agent adds whichever of these four your `errorProcessors` list doesn't already contain:
120
120
 
121
121
  1. `ProviderHistoryCompat`: repairs provider-specific history incompatibilities in the outbound prompt
122
122
  2. `PrefillErrorHandler`: recovers from assistant-response prefill rejections
123
- 3. `StreamErrorRetryProcessor`: retries transient API and stream failures
123
+ 3. [`UnsupportedFileHandler`](https://mastra.ai/reference/processors/unsupported-file-handler): takes a file the model rejects out of the prompt, uploads it to the agent's sandbox when there is one, and calls the model again
124
+ 4. `StreamErrorRetryProcessor`: retries transient API and stream failures
124
125
 
125
- A default is only added when nothing in your list carries its `id`, so your own instance always wins and is never duplicated. An added default is placed at the position its `id` gives it among the defaults, so naming only a later one doesn't invert the pair. Supplying only your own `StreamErrorRetryProcessor` still resolves with `ProviderHistoryCompat` and `PrefillErrorHandler` ahead of it.
126
+ A default is only added when nothing in your list carries its `id`, so your own instance always wins and is never duplicated. An added default is placed at the position its `id` gives it among the defaults, so naming only a later one doesn't invert the pair. Supplying only your own `StreamErrorRetryProcessor` still resolves with `ProviderHistoryCompat`, `PrefillErrorHandler`, and `UnsupportedFileHandler` ahead of it.
126
127
 
127
128
  Error processors stop at the first one that returns `{ retry: true }`, so that relative order decides which repair runs. The default order puts the repairs ahead of the retrying processor. Placed earlier, an instance with broad matchers (the bad-request matcher matches any `400`, for example) would claim a request the repairs could have fixed and resend it unchanged. The default instance retries only transient failures: connection resets, retryable OpenAI stream errors, and errors the provider marks as retryable. Your own instance can be configured with broader matchers. The order keeps repairs ahead of it too.
128
129
 
@@ -144,11 +145,11 @@ const agent = new Agent({
144
145
  })
145
146
  ```
146
147
 
147
- The `StreamErrorRetryProcessor` above is the only stream-retry processor on the agent, and it resolves in its usual position: last, behind the `ProviderHistoryCompat` and `PrefillErrorHandler` defaults your list never names. Pass all three ids to run a completely custom set.
148
+ The `StreamErrorRetryProcessor` above is the only stream-retry processor on the agent, and it resolves in its usual position: last, behind the `ProviderHistoryCompat`, `PrefillErrorHandler`, and `UnsupportedFileHandler` defaults your list never names. Pass all four ids to run a completely custom set.
148
149
 
149
150
  A processor's `maxRetries` can't raise the agent's limit. Without `maxProcessorRetries`, error-processor retries stop after `3` (see [Error processor retry limits](#error-processor-retry-limits)), so set it when a processor needs more.
150
151
 
151
- An empty `errorProcessors` list merges like any other, so it still gets the three defaults. To turn the defaults off, set `errorProcessorDefaults: false`. The agent then runs only the processors you configure, or none when you configure none:
152
+ An empty `errorProcessors` list merges like any other, so it still gets the four defaults. To turn the defaults off, set `errorProcessorDefaults: false`. The agent then runs only the processors you configure, or none when you configure none:
152
153
 
153
154
  ```typescript
154
155
  new Agent({
@@ -178,8 +178,6 @@ const browser = new AgentBrowser({
178
178
 
179
179
  ## Record browser sessions
180
180
 
181
- > **Beta:** Breaking changes may occur without a major version bump until the API is stable.
182
-
183
181
  AgentBrowser and StagehandBrowser can opt into recording for reviewing, sharing, or debugging browser runs. Configure `outputDir` to add the recording tools:
184
182
 
185
183
  ```typescript
@@ -143,7 +143,7 @@ To add your own endpoints, see [Custom API Routes](https://mastra.ai/docs/server
143
143
 
144
144
  ## Graceful shutdown and rolling deploys
145
145
 
146
- By default, the generated server handles `SIGINT` and `SIGTERM`. It stops accepting connections, waits up to [`server.drainTimeout`](https://mastra.ai/reference/configuration) for active requests and streams, then runs `mastra.shutdown()`. Shutdown gives in-flight workflow runs (including durable agent runs) the same drain window to finish before workers and pub/sub subscriptions are torn down. The drain timeout defaults to 5 seconds. A second signal terminates the process immediately. See [`server.handleShutdownSignals`](https://mastra.ai/reference/configuration) if you need to manage signals yourself.
146
+ By default, the generated server handles `SIGINT` and `SIGTERM`. It stops accepting connections, waits up to [`server.drainTimeout`](https://mastra.ai/reference/configuration) for active requests and streams, then runs `mastra.shutdown()`. Shutdown gives in-flight workflow runs (including durable agent runs) the same drain window to finish before workers and pub/sub subscriptions are torn down. A durable agent run still executing after the window stops and releases its claim on the run, so the next boot can recover it right away. The drain timeout defaults to 5 seconds. A second signal terminates the process immediately. See [`server.handleShutdownSignals`](https://mastra.ai/reference/configuration) if you need to manage signals yourself.
147
147
 
148
148
  Increase `drainTimeout` when your hosting platform's termination grace period can accommodate longer turns. The HTTP drain and the workflow drain run one after the other, so keep enough time for both plus shutdown cleanup.
149
149
 
@@ -163,7 +163,7 @@ export const mastra = new Mastra({
163
163
  })
164
164
  ```
165
165
 
166
- A plain `agent.stream()` call can't resume after its server process exits. If a stream ends without its expected terminal event, treat the turn as interrupted and let the client retry or reconcile it. Use [durable agents](https://mastra.ai/docs/harness/durable-agents) when turns must survive process replacement. [Crash recovery](https://mastra.ai/docs/harness/durable-agents) requires shared persistent run storage and idempotent tools. Replaying missed events after a restart also requires a shared persistent cache such as Redis because the default event cache is in-memory. Multi-replica recovery doesn't yet use a distributed lease.
166
+ A plain `agent.stream()` call can't resume after its server process exits. If a stream ends without its expected terminal event, treat the turn as interrupted and let the client retry or reconcile it. Use [durable agents](https://mastra.ai/docs/harness/durable-agents) when turns must survive process replacement. [Crash recovery](https://mastra.ai/docs/harness/durable-agents) requires shared persistent run storage and idempotent tools. Replaying missed events after a restart also requires a shared persistent cache such as Redis because the default event cache is in-memory. Recovering from multiple replicas requires a storage adapter that supports run fencing or a PubSub backend whose lease every replica shares. See [multi-instance deployments](https://mastra.ai/docs/harness/durable-agents).
167
167
 
168
168
  ## Troubleshooting
169
169
 
@@ -215,7 +215,7 @@ This example uses the default bridge. Mastra first preserves any `req.auth` valu
215
215
 
216
216
  Return only the data the model needs. Remove credentials and sensitive upstream fields before returning a tool result.
217
217
 
218
- `RequestContext.serializeForSpan()` redacts `MASTRA_AUTH_TOKEN_KEY` when context is attached to tracing spans. Application logs and custom telemetry must apply the same principle to other credentials and sensitive identity fields.
218
+ Reserved Mastra keys (those starting with `mastra__` or `__mastra_`, including `MASTRA_AUTH_TOKEN_KEY`) are omitted when request context is attached to tracing spans or saved on score records. Application logs and custom telemetry must apply the same principle to other credentials and sensitive identity fields.
219
219
 
220
220
  ## Add authorization after authentication
221
221
 
@@ -201,6 +201,35 @@ await session.model.switch('anthropic/claude-sonnet-4-6')
201
201
  console.log(session.model.get())
202
202
  ```
203
203
 
204
+ ### Select Observational Memory models
205
+
206
+ Observer and reflector model choices are independent. Each role can use an explicit model or an automatic selection that the host resolves from the active main model and session state.
207
+
208
+ Configure automatic selection with a synchronous resolver that returns a concrete model ID:
209
+
210
+ ```typescript
211
+ const controller = new AgentController({
212
+ // ...
213
+ omConfig: {
214
+ observerModel: 'auto',
215
+ reflectorModel: 'auto',
216
+ defaultObserverModelId: 'openai/gpt-5-mini',
217
+ defaultReflectorModelId: 'openai/gpt-5-mini',
218
+ resolveAutoModelId: ({ currentModelId }) => currentModelId,
219
+ },
220
+ })
221
+ ```
222
+
223
+ `session.om.observer.model()` returns `'auto'` or a concrete model ID. `session.om.observer.modelId()` returns the effective concrete model. A host can therefore change the main model without rewriting automatic role settings.
224
+
225
+ Reset one role to automatic selection without changing the other:
226
+
227
+ ```typescript
228
+ await session.om.observer.switchModel({ modelId: 'auto' })
229
+ ```
230
+
231
+ If the resolver returns `undefined` or throws, the role uses its concrete `defaultObserverModelId` or `defaultReflectorModelId` fallback. See the [`Session` Observational Memory API](https://mastra.ai/reference/agent-controller/session) for explicit selection.
232
+
204
233
  ## Manage threads and state
205
234
 
206
235
  List stored conversations with [`session.thread.list()`](https://mastra.ai/reference/agent-controller/session):
@@ -276,9 +276,9 @@ await durableAgent.resume(runId, { approved: true })
276
276
 
277
277
  Durable agents can checkpoint each run's state to storage while it executes. If the server process crashes mid-run, the run remains in `running` status in storage with no automatic retry, and on the next server start you can re-drive these orphaned runs so they pick up where they left off. For orderly shutdowns such as rolling deploys, the generated server can also drain in-flight turns before exiting. See [graceful shutdown and rolling deploys](https://mastra.ai/docs/deployment/mastra-server).
278
278
 
279
- Under the default persistence policy, these `running` checkpoints are only written when crash recovery is enabled. With `recovery.durableAgents: 'off'` (the default), durable agents persist snapshots only for `pending`, `paused`, and `suspended` runs (the artifacts human-in-the-loop resume depends on) and skip the per-step `running` writes entirely. A custom `shouldPersistSnapshot` predicate can keep `running` checkpoints even with recovery off. See [snapshot persistence](#snapshot-persistence) for the full policy and how to override it.
279
+ Under the default persistence policy, these `running` checkpoints are written when crash recovery is enabled. With `recovery.durableAgents: 'off'` (the default), durable agents persist snapshots for `pending`, `paused`, and `suspended` runs (the artifacts human-in-the-loop resume depends on) and skip the per-step `running` writes until `mastra.shutdown()` starts. A custom `shouldPersistSnapshot` predicate replaces the default policy: one that includes `running` writes those checkpoints at every step, and one that excludes `running` writes none, including during shutdown. See [snapshot persistence](#snapshot-persistence) for the full policy and how to override it.
280
280
 
281
- Durable agent runs are excluded from the generic boot-time restart of active workflow runs. The only automatic recovery path for durable agent runs is `recovery.durableAgents: 'auto'`, which holds a recovery lease and registers thread runtimes before re-driving each run.
281
+ Durable agent runs are excluded from the generic boot-time restart of active workflow runs. The only automatic recovery path for durable agent runs is `recovery.durableAgents: 'auto'`, which claims each orphaned run and registers its thread runtimes before re-driving it. See [run ownership](#run-ownership).
282
282
 
283
283
  > **Warning:** Automatic and manual recovery re-run the agentic loop from the last persisted snapshot, which can reissue LLM calls (with real cost) and re-execute tool calls. A sub-agent delegation is one generated `agent-<name>` tool call, and recovery doesn't checkpoint the LLM or tool calls inside that delegation independently. If recovery replays the delegation step, the entire sub-agent run starts again and can repeat inner LLM calls and already-completed tool side effects. Make tools, including tools used by sub-agents, idempotent, or deduplicate their external side effects.
284
284
 
@@ -287,7 +287,10 @@ Durable agent runs are excluded from the generic boot-time restart of active wor
287
287
  The `shouldPersistSnapshot` option on `createDurableAgent()` (also accepted in the agent-level `durable` config) controls which workflow snapshots a durable agent writes. The default policy:
288
288
 
289
289
  - Always persists `pending`, `paused`, and `suspended` snapshots. These are what `resume()` and tool approval read, so human-in-the-loop flows work without configuration.
290
- - Persists `running` checkpoints only when `recovery.durableAgents` is `'auto'`. These per-step writes exist solely to make in-flight runs recoverable after a crash, so they're skipped when nothing consumes them.
290
+ - Persists `running` checkpoints at every step when `recovery.durableAgents` is `'auto'`. These per-step writes exist solely to make in-flight runs recoverable after a crash, so with recovery off they're skipped until shutdown.
291
+ - Persists a `running` checkpoint at each step boundary a run reaches after `mastra.shutdown()` starts, even with recovery off. A run that reaches a step boundary before the drain window ends can then be resumed later with `recover()` or `recoverActiveRuns()`. A run blocked in a single LLM or tool call for the whole drain gets no shutdown checkpoint.
292
+
293
+ When the agent is configured with a fixed memory instance (`memory: new Memory(...)`), a `running` checkpoint doesn't repeat messages memory already stores. Messages recalled from memory and messages the run saved itself (for example with `savePerStep: true`) are stored as small references to their memory rows instead of their full contents, as long as they still match the stored row (a message changed after saving stays inline). This applies to every copy of the conversation a checkpoint holds, including the run input and step results. A long run's checkpoints grow much more slowly as a result. Agents that resolve memory with a function keep the full transcript in each checkpoint, because the memory a resumed run resolves may differ.
291
294
 
292
295
  To keep crash-recovery checkpoints without enabling automatic recovery (for example, when you call `recoverActiveRuns()` yourself behind a leader election), pass a predicate that includes `running`:
293
296
 
@@ -305,7 +308,7 @@ Evented agents always persist the full snapshot set: the evented engine coordina
305
308
 
306
309
  ### Automatic recovery
307
310
 
308
- Set `recovery.durableAgents` to `'auto'` in the Mastra config. The deployer calls `recoverAllDurableAgents()` on boot, right after restarting active workflow runs:
311
+ Set `recovery.durableAgents` to `'auto'` in the Mastra config. The deployer calls `recoverAllDurableAgents()` on boot, alongside the workflow run restarts (the two run concurrently):
309
312
 
310
313
  ```typescript
311
314
  export const mastra = new Mastra({
@@ -317,27 +320,60 @@ export const mastra = new Mastra({
317
320
 
318
321
  On startup, this discovers every registered durable agent with runs stuck in `running` status and re-drives them from the last persisted snapshot.
319
322
 
323
+ Recovery doesn't take over a run that another execution still drives. It skips the run and checks it again once that execution's claim could have lapsed. A run whose process crashed shortly before the restart is still recovered, without another call.
324
+
320
325
  ### Manual recovery
321
326
 
322
- If you need finer control, such as gating recovery behind a leader election or running it on a schedule, call the methods directly:
327
+ If you need finer control, such as running recovery on a schedule, call the methods directly:
323
328
 
324
329
  ```typescript
325
330
  // Recover all durable agents
326
331
  const result = await mastra.recoverAllDurableAgents()
327
- console.log(`Recovered ${result.recovered} runs (${result.succeeded} ok, ${result.failed} failed)`)
332
+ console.log(
333
+ `Recovered ${result.recovered} runs (${result.succeeded} ok, ${result.failed} failed, ${result.skipped} still live)`,
334
+ )
328
335
 
329
336
  // Recover a specific agent
330
- const agentResult = await durableAgent.recoverActiveRuns()
337
+ const { recovered } = await durableAgent.recoverActiveRuns()
338
+ for (const run of recovered) {
339
+ if (run.status === 'skipped') console.log(`${run.runId} is still live: ${run.reason}`)
340
+ }
331
341
 
332
342
  // Recover a single known run
333
343
  await durableAgent.recoverActiveRuns({ runId: 'run-abc-123' })
334
344
  ```
335
345
 
336
- Manual recovery reads the same `running` checkpoints as automatic recovery. If `recovery.durableAgents` is `'off'` and you haven't set a custom `shouldPersistSnapshot` that includes `running`, in-flight runs are never checkpointed, so `listActiveRuns()` and `recoverActiveRuns()` find nothing after a crash. See [snapshot persistence](#snapshot-persistence).
346
+ `recoverAllDurableAgents()` returns counts and re-checks skipped runs itself. `recoverActiveRuns()` returns each run's outcome as `success`, `failed`, or `skipped`, and doesn't re-check skipped runs. A run skipped because another process drives it carries `retryAt`, the time after which its claim lapses unless renewed.
347
+
348
+ Manual recovery reads the same `running` checkpoints as automatic recovery. For a `DurableAgent` using the default snapshot policy with `recovery.durableAgents` set to `'off'`, in-flight runs are only checkpointed at step boundaries reached after `mastra.shutdown()` starts. A run that crashes before then, or doesn't reach a step boundary during the drain, has no checkpoint, so `listActiveRuns()` and `recoverActiveRuns()` don't find it. See [snapshot persistence](#snapshot-persistence).
349
+
350
+ To take over a run that's still live, such as one held by a hung execution, call `recover()` with `force: true`:
351
+
352
+ ```typescript
353
+ const { output } = await durableAgent.recover('run-abc-123', { force: true })
354
+ ```
355
+
356
+ The execution that held the run loses it and stops, and streams for the run drop the events it still publishes. Without `force`, `recover()` throws `DURABLE_AGENT_RUN_ACTIVE` for a live run. Even with `force`, `recover()` refuses a run that the same process is executing.
357
+
358
+ ### Run ownership
359
+
360
+ Every `stream()`, `generate()`, `resume()`, and `recover()` call claims the run before it executes and renews the claim every 10 seconds. A claim lapses 30 seconds after its last renewal, so a run whose process crashed becomes recoverable within 30 seconds. Until then, recovery treats the run as live, and a `stream()` or `resume()` call for that run waits up to 5 seconds for the claim, then throws `DURABLE_AGENT_EXECUTION_CONFLICT`. `mastra.shutdown()` stops the runs still executing after its drain window without further writes and releases their claims. The next boot then recovers them without waiting for the claims to lapse.
361
+
362
+ Enforcement of the claim depends on the workflows store. When the store supports run fencing, the claim is a record in that store, and each write is checked against the claim in the same operation. Once another execution claims the run, writes from the execution that lost it are rejected. That execution's message, thread, and working memory writes are rejected only if the memory store supports run fencing too, so they still land when the agent's `Memory` uses a storage adapter without it. These storage adapters support run fencing:
363
+
364
+ - `InMemoryStore` from `@mastra/core/storage`
365
+ - `@mastra/pg`
366
+ - `@mastra/libsql` and `@mastra/turso`
367
+
368
+ Stores that support run fencing keep one claim record per run, plus one memory fence record per run with memory. Stores with retention support prune them with the `workflows.runOwnership` and `memory.runFences` [retention keys](https://mastra.ai/reference/storage/retention). A run's first generation comes from the store's clock, so a run that reuses a `runId` after its records were pruned still outranks the fences and stream events of its earlier executions.
369
+
370
+ With any other workflows store, the claim is a lease on the [PubSub](https://mastra.ai/docs/server/pubsub) backend. The lease keeps two executions from claiming the run at once, but writes from an execution that lost the run aren't rejected. A run taken over while its previous execution was still live can end with that execution's output. When an execution loses its lease and no other execution has taken the run, the run stays held for up to 15 more seconds. Until then, `recover()` without `force` throws `DURABLE_AGENT_RUN_ACTIVE` with `retryAt` set to when the hold is sure to have ended. Mastra logs a warning when it recovers runs against a workflows or memory store without run fencing.
371
+
372
+ A lease only coordinates the processes that share it. `EventEmitterPubSub`, the default, covers one process. `UnixSocketPubSub` covers the processes on one host. `RedisStreamsPubSub` and `ValkeyStreamsPubSub` cover every instance connected to the same server. `GoogleCloudPubSub` doesn't provide leases, so with a store that lacks run fencing every claim succeeds, and recovery can take over a run that's still live.
337
373
 
338
374
  ### Multi-instance deployments
339
375
 
340
- Mastra doesn't provide a distributed lease or lock yet. In multi-replica deployments, every replica that starts with `recovery.durableAgents: 'auto'` will race to recover the same runs. For now, either gate recovery behind your own leader election or run it from a single replica.
376
+ Every replica can start with `recovery.durableAgents: 'auto'`. Replicas that boot together race to recover the same orphaned runs, but only one claim succeeds per run and the other replicas skip it. This requires a claim that every replica shares: a workflows store that supports run fencing, or a PubSub backend whose lease every replica shares. Without either, gate recovery behind your own leader election or run it from a single replica.
341
377
 
342
378
  ## Related
343
379
 
@@ -48,6 +48,18 @@ for await (const chunk of subscription.stream) {
48
48
 
49
49
  When the thread has a running agent stream, `sendMessage()` becomes new input inside that agent loop. When the thread is idle, Mastra starts a stream with the message as the first input.
50
50
 
51
+ ### Input during reasoning
52
+
53
+ In the default loop and experimental durable and evented agents, accepted pending messages and signals interrupt a model request that has produced only reasoning or metadata. This includes the wait for its first token. Mastra cancels that request, discards its response from model history and memory, and includes queued input in the next request within the same run. Earlier completed responses stay in history.
54
+
55
+ Once text, tool calls, or other response content starts, signals wait for the next loop boundary. Running tools aren't cancelled or repeated. If the run reaches `maxSteps`, queued input may be saved without a response. `queueMessage()` still waits for the active run to finish. Signals that processors write directly to the message history don't interrupt their own request.
56
+
57
+ Interrupted requests don't count toward `maxSteps` or advance `stepNumber`. The next request uses the same logical step, so `maxSteps: 1` still allows a replacement response. Mastra doesn't set a separate interruption limit. Repeated signals can keep restarting reasoning until a request completes, the run is cancelled, or its total timeout expires.
58
+
59
+ Already-streamed reasoning may remain visible until the client reloads history. When input arrives while per-step input processors (`processInputStep`) run, the processors finish and Mastra cancels the model request they prepared. Custom output processors also keep running after a cancellation, and the next request waits for their in-flight work to settle. Mastra discards framework-owned response buffers, but doesn't undo processor state, data that processors write while the cancelled request settles, or external side effects. Usage totals exclude interrupted requests, including any usage the provider reports for them. Providers may still bill for those requests.
60
+
61
+ Reasoning interruption doesn't apply to the Inngest engine, or to durable and evented steps that run in a different process from the one that accepted the input.
62
+
51
63
  ## Message input
52
64
 
53
65
  ### Send a message now
@@ -10,14 +10,6 @@ You can also retrieve message history to display past conversations in your UI.
10
10
 
11
11
  > **Note:** Each message belongs to a thread (the conversation) and a resource (the user or entity it's associated with). See [Threads and resources](#threads-and-resources) for more detail.
12
12
 
13
- > **Warning:** When you use memory with a client application, send **only the new message** from the client instead of the full conversation history.
14
- >
15
- > Sending the full history is redundant because Mastra loads messages from storage. Mastra filters client-echoed history before loading stored messages and uses the stored copy as the base when message IDs match, preserving stored timestamps and provider metadata while retaining new tool results.
16
- >
17
- > If you assemble the request input yourself and need it processed exactly as sent, set `retainFullInput: true` on `memory.options` for that call, or in the memory constructor options to apply it agent-wide. This disables the filtering described above. History still loads underneath. Every input message that isn't already stored is saved to the thread, including few-shot examples.
18
- >
19
- > For an AI SDK example, see [Using Mastra Memory](https://mastra.ai/integrations/agentic-ui/ai-sdk-ui).
20
-
21
13
  ## Threads and resources
22
14
 
23
15
  Mastra organizes conversations using two identifiers:
@@ -126,6 +118,21 @@ You can use this history in two ways:
126
118
 
127
119
  > **Note:** `lastMessages` counts every stored message, including tool calls, tool results, and [signals](https://mastra.ai/docs/harness/signals) of any kind, so a single turn can add several messages to the count. The window also slides forward on every request: once a thread grows past the limit, the oldest message leaves context on each turn, which changes the start of the prompt and invalidates the provider prompt cache. For long-running conversations, use [Observational Memory](https://mastra.ai/docs/memory/observational-memory), which keeps the prompt prefix stable.
128
120
 
121
+ ### Sending messages from a client
122
+
123
+ When you use memory with a client application, send **only the new message** instead of the full conversation history. Mastra loads previous messages from storage.
124
+
125
+ For an AI SDK example, see [Using Mastra Memory](https://mastra.ai/integrations/agentic-ui/ai-sdk-ui).
126
+
127
+ <details>
128
+ **Passing a full input history**
129
+
130
+ Mastra filters client-echoed history before loading stored messages. When message IDs match, it uses the stored copy as the base, preserving stored timestamps and provider metadata while retaining new tool results.
131
+
132
+ If you assemble the request input yourself and need it processed exactly as sent, set `retainFullInput: true` on `memory.options` for that call, or in the memory constructor options to apply it agent-wide. This disables input filtering, but stored history still loads. Every input message that isn't already stored is saved to the thread, including few-shot examples.
133
+
134
+ </details>
135
+
129
136
  ### Limit history by tokens
130
137
 
131
138
  Message count is a poor proxy for context size: a tool result can be a few tokens or thousands. Use `messageHistory` to keep recent history within a token budget instead:
@@ -76,7 +76,7 @@ console.log(secondResponse.text)
76
76
 
77
77
  The `resource` identifies the user or entity, while the `thread` identifies the conversation. Reuse both values to continue the same conversation. Observational Memory processes the stored history as it grows and replaces older messages with observations when its activation conditions are met.
78
78
 
79
- The agent now has humanlike long-term memory that persists across conversations. Setting `observationalMemory: true` uses `google/gemini-2.5-flash` by default. To use a different model, pass it in the config object:
79
+ The agent now has humanlike long-term memory that persists across conversations. Setting `observationalMemory: true` uses automatic model selection. To use a specific model, pass it in the config object:
80
80
 
81
81
  ```typescript
82
82
  const memory = new Memory({
@@ -98,7 +98,17 @@ See [configuration options](https://mastra.ai/reference/memory/observational-mem
98
98
  >
99
99
  > For an AI SDK example, see [Using Mastra Memory](https://mastra.ai/integrations/agentic-ui/ai-sdk-ui).
100
100
 
101
- > **Note:** OM currently only supports `@mastra/pg`, `@mastra/libsql`, `@mastra/mysql`, `@mastra/mongodb`, `@mastra/convex`, and `@mastra/oracledb` storage adapters. It uses background agents for managing memory. When no model is set, the default model is `google/gemini-2.5-flash`.
101
+ > **Note:** OM currently only supports `@mastra/pg`, `@mastra/libsql`, `@mastra/mysql`, `@mastra/mongodb`, `@mastra/convex`, and `@mastra/oracledb` storage adapters. It uses background agents for managing memory. When no model is set, the default is `model: 'auto'`.
102
+
103
+ ### Automatic models in Mastra Code and Factory
104
+
105
+ Mastra Code and Factory surface the same automatic selection as a per-role **Auto** option in their settings.
106
+
107
+ An automatic Observer or Reflector follows the active main model provider. Mastra Code uses that provider's built-in low-cost Observational Memory model when one is configured. For custom providers and providers without a built-in choice, it uses the active main model. The effective model is resolved when the role runs, so changing the main model doesn't rewrite the saved automatic selection.
108
+
109
+ Select an explicit model to pin one role independently. Reset that role to **Auto** to resume following the main model provider. Existing saved concrete model IDs remain explicit until you reset them.
110
+
111
+ Factory stores automatic intent separately from the effective model shown in settings. A missing provider credential can mark that effective model unavailable, but it doesn't replace the saved selection or prevent Factory from starting.
102
112
 
103
113
  ## Temporal gap markers
104
114
 
@@ -570,11 +580,30 @@ The progress bars update live while the agent is observing or reflecting, showin
570
580
 
571
581
  ## Models
572
582
 
573
- The Observer and Reflector run in the background. Any model that works with Mastra's [model routing](https://mastra.ai/models) (`provider/model`) can be used. When no model is set, the default model is `google/gemini-2.5-flash`.
583
+ The Observer and Reflector run in the background. Any model that works with Mastra's [model routing](https://mastra.ai/models) (`provider/model`) can be used. When no model is set, the default is `model: 'auto'`.
584
+
585
+ Automatic selection uses `google/gemini-2.5-flash` when `GOOGLE_GENERATIVE_AI_API_KEY` is configured. Otherwise, it selects a low-cost model for the active main model's provider, then falls back to the active main model. Observer and Reflector resolve independently before each invocation.
586
+
587
+ Automatic selection reads the main model's `provider/model` ID. Models created from a plain model string carry that ID, and a dynamic model function can label a custom model by returning `{ model, id }`. When the ID is unknown, such as a model with a custom URL, API key, headers, or gateway, automatic selection reuses the main model itself because a sibling model isn't known to share that route. Pass a concrete model ID to the role to override either behavior.
588
+
589
+ Use `autoModels` to change the model picked for a provider, and `resolveModel` to create the picked model with your own credentials or routing:
590
+
591
+ ```typescript
592
+ const memory = new Memory({
593
+ options: {
594
+ observationalMemory: {
595
+ autoModels: { openai: 'openai/gpt-5-nano' },
596
+ resolveModel: (modelId, { requestContext }) => createRoutedModel(modelId, requestContext),
597
+ },
598
+ },
599
+ })
600
+ ```
601
+
602
+ `resolveAutoModelId(mainModelId, { autoModels })` from `@mastra/memory` returns the model automatic selection would pick, which is useful for showing the effective model in a settings UI.
574
603
 
575
604
  Mastra recommends using a model that has a large context window (128K+ tokens) and is fast enough to run in the background without slowing down your actions.
576
605
 
577
- If you're unsure which model to use, start with the default `google/gemini-2.5-flash`. We've also successfully tested `openai/gpt-5-mini`, `anthropic/claude-haiku-4-5`, `deepseek/deepseek-reasoner`, `deepseek/deepseek-v4-pro`, `deepseek/deepseek-v4-flash`, `xai/grok-4-1-fast`, `qwen3`, and `glm-4.7`.
606
+ To pin a model instead, set a concrete model ID. We've also successfully tested `openai/gpt-5-mini`, `anthropic/claude-haiku-4-5`, `deepseek/deepseek-reasoner`, `deepseek/deepseek-v4-pro`, `deepseek/deepseek-v4-flash`, `xai/grok-4-1-fast`, `qwen3`, and `glm-4.7`.
578
607
 
579
608
  ```typescript
580
609
  const memory = new Memory({
@@ -142,6 +142,7 @@ Use a remote or container sandbox when commands need a stronger boundary from th
142
142
  - [Mastra](https://mastra.ai/reference/workspace/platform-sandbox)
143
143
  - [Modal](https://mastra.ai/integrations/sandboxes/modal)
144
144
  - [Railway](https://mastra.ai/integrations/sandboxes/railway)
145
+ - [Fly.io Sprites](https://mastra.ai/integrations/sandboxes/sprites)
145
146
  - [Vercel](https://mastra.ai/integrations/sandboxes/vercel)
146
147
 
147
148
  If Mastra doesn't support your sandbox provider, implement the [sandbox provider interface](https://mastra.ai/reference/workspace/sandbox) to add it.
@@ -74,6 +74,8 @@ Use a distributed backend when you run more than one instance or host, and every
74
74
 
75
75
  For example, sending a signal to an agent run requires the signal event to cross the process boundary to the instance that owns the run. With the in-process default, that instance never receives the event.
76
76
 
77
+ [Durable agent](https://mastra.ai/docs/harness/durable-agents) crash recovery also depends on the backend when the storage adapter doesn't support run fencing. Recovery then uses the backend's leases to tell whether another instance still drives a run. `RedisStreamsPubSub` provides leases across hosts. `GoogleCloudPubSub` doesn't.
78
+
77
79
  Both backends below deliver across processes and hosts and persist events for redelivery.
78
80
 
79
81
  The following example uses [Redis Streams](https://redis.io/docs/latest/develop/data-types/streams/):
@@ -73,6 +73,7 @@ Called before the parent agent delegates to a subagent. Return an object to cont
73
73
  - `proceed: false`: Reject the delegation with a `rejectionReason`
74
74
  - `modifiedPrompt`: Rewrite the prompt sent to the subagent
75
75
  - `modifiedMaxSteps`: Limit the subagent's iteration count
76
+ - `threadMetadata`: Attach metadata (for example a `tenantId`) to the subagent's thread when it's created, so you can filter threads with `memory.listThreads({ filter: { metadata } })`
76
77
 
77
78
  ```typescript
78
79
  const stream = await parentAgent.stream('Research AI trends', {
@@ -490,6 +490,8 @@ Use `restartAllActiveWorkflowRuns()` to restart all active workflow runs of a wo
490
490
  workflow.restartAllActiveWorkflowRuns()
491
491
  ```
492
492
 
493
+ Runs restart concurrently, up to `recovery.workflowConcurrency` at a time (default `5`). Set it to `1` in the Mastra config if your runs share side effects that must not run in parallel.
494
+
493
495
  To exclude a workflow from automatic boot-time restarts triggered by `Mastra.restartAllActiveWorkflowRuns()`, set `autoRestartActiveRuns: false` in the workflow's `options`. This is useful for workflows with side effects that must not be re-driven by a blanket restart. Durable agent workflows set this automatically because their recovery is owned by the opt-in `recovery.durableAgents: 'auto'` path.
494
496
 
495
497
  ### Restarting an active workflow run with `restart()`
@@ -120,11 +120,13 @@ const handle = await sandbox.processes.spawn('node server.js', {
120
120
  })
121
121
 
122
122
  // Interact with the process
123
+ await handle.sendStdin('hello\n')
124
+ await handle.closeStdin()
123
125
  console.log(handle.stdout)
124
126
  await handle.kill()
125
127
  ```
126
128
 
127
- > **Note:** Blaxel sandboxes don't support stdin. Calling `handle.sendStdin()` throws an error.
129
+ Spawned processes have a writable stdin by default. Pass `stdinMode: 'ignore'` to start a process with stdin closed so commands that read stdin get EOF immediately.
128
130
 
129
131
  See [`SandboxProcessManager` reference](https://mastra.ai/reference/workspace/process-manager) for the full API.
130
132
 
@@ -72,7 +72,9 @@ const agent = new Agent({
72
72
 
73
73
  **id** (`string`): Unique identifier for this sandbox instance (Default: `Auto-generated`)
74
74
 
75
- **sandboxId** (`string`): Persisted E2B provider sandbox ID to reattach to deterministically. When set, start() connects to this exact sandbox (resuming it if paused) instead of discovering by logical id metadata. Only a typed "sandbox gone" error (not found, killed, or not running) falls through to the usual logical-id lookup and create ladder; auth, quota, rate-limit, timeout, and network errors propagate without creating a new sandbox. A sandbox tagged with a different logical id is refused. Read the resolved provider ID from the sandboxId property after start.
75
+ **sandboxId** (`string`): Persisted E2B provider sandbox ID to reattach to deterministically. When set, start() connects to this exact sandbox (resuming it if paused) instead of discovering by logical id metadata. Under the default reattach: 'best-effort', only a typed "sandbox gone" error (not found, killed, or not running) falls through to the usual logical-id lookup and create ladder; auth, quota, rate-limit, timeout, and network errors propagate without creating a new sandbox. A sandbox tagged with a different logical id is refused. Read the resolved provider ID from the sandboxId property after start.
76
+
77
+ **reattach** (`'best-effort' | 'required'`): What start() does when sandboxId is set but that sandbox is gone. 'best-effort' falls through to the logical-id lookup, which may reconnect to another sandbox with the same id before creating a new one. 'required' throws a SandboxError with code SANDBOX\_REATTACH\_FAILED instead of looking up or creating a sandbox. See Requiring reattachment. (Default: `'best-effort'`)
76
78
 
77
79
  **domain** (`string`): Domain for self-hosted E2B. Falls back to E2B\_DOMAIN env var.
78
80
 
@@ -98,6 +100,20 @@ const agent = new Agent({
98
100
 
99
101
  **processes** (`E2BProcessManager`): Background process manager. See SandboxProcessManager reference.
100
102
 
103
+ ## Requiring reattachment
104
+
105
+ When you pass a persisted `sandboxId` and that sandbox is gone, the default `reattach: 'best-effort'` falls through to the logical-id lookup, which may reconnect to another sandbox with the same `id` or create a new one. When a different sandbox would silently lose state your app depends on, set `reattach: 'required'`:
106
+
107
+ ```typescript
108
+ const sandbox = new E2BSandbox({
109
+ id: 'session-123',
110
+ sandboxId: persistedSandboxId,
111
+ reattach: 'required',
112
+ })
113
+ ```
114
+
115
+ With `reattach: 'required'`, a gone sandbox rejects `start()` with a `SandboxError` whose `code` is `SANDBOX_REATTACH_FAILED`, and no lookup or create runs. The error's `details` include `provider`, `sandboxId`, and `logicalId` (the sandbox's logical `id`). Other errors propagate unchanged, as they do under `'best-effort'`. To start fresh, clear your persisted `sandboxId` and construct the sandbox without it. Clones inherit the `reattach` setting.
116
+
101
117
  ## Background processes
102
118
 
103
119
  `E2BSandbox` includes a built-in process manager for spawning and managing background processes. Processes run in the E2B cloud sandbox using the E2B SDK's `commands.run()` with `background: true`.
@@ -361,6 +377,21 @@ Failure handling is designed so a broken template never wedges a session:
361
377
  - A failed build falls back to the default mountable template; the session's runtime cold clone into `$HOME` keeps working.
362
378
  - E2B keeps a failed build's ref visible to `Template.exists`, so a broken ref could otherwise be reused forever. When creating a sandbox from a named ref fails, the cached resolution is dropped and creation retries down the fallback ladder.
363
379
 
380
+ If a sandbox without the template's toolchain is worse than a failed start, set `fallbackTemplate: false` on the resolved spec. A failed build, or a ref that can't create a sandbox, then rejects `start()` with the original error instead of falling back:
381
+
382
+ ```typescript
383
+ const repoTemplate = createRepoTemplate({
384
+ getRepositoryAccess: async () => ({ cloneUrl: 'https://github.com/acme/app.git' }),
385
+ setupCommand: 'pnpm install',
386
+ })!
387
+
388
+ const sandbox = new E2BSandbox({
389
+ template: {
390
+ resolveSpec: async () => ({ ...(await repoTemplate.resolveSpec()), fallbackTemplate: false }),
391
+ },
392
+ })
393
+ ```
394
+
364
395
  Private repositories build warm templates when `getRepositoryAccess` returns an `authorization` alongside the clone URL — a fresh, short-lived credential (such as a GitHub App installation token) minted per template resolution. The credential authenticates the head lookup and the build's clone through an in-shell `http.extraheader` — it enters the template definition's environment (visible to build steps but not persisted into runtime sandbox environments) and never touches the image filesystem, so no captured layer can contain it. It's set as `GH_TOKEN`, the same variable a session installs before running setup, so a command that shells out to `gh` or authenticated https behaves the same in the build as it does in a session.
365
396
 
366
397
  Only pass short-lived credentials — the value stays in the template definition until the next rebuild, so its expiry is what bounds the exposure. Note that the cloned repository contents become part of a team-visible template image. When the access call returns no credential the clone is tokenless: public repositories build fine, and a private repository's build degrades to the fallback, where the session's own runtime setup (with runtime-injected auth) does the clone.
@@ -201,6 +201,17 @@ await sandbox._start()
201
201
  const result = await sandbox.executeCommand('cat', ['/tmp/state.txt'])
202
202
  ```
203
203
 
204
+ By default (`reattach: 'best-effort'`), if the sandbox with that ID no longer exists or isn't running, `start()` provisions a replacement sandbox and reports `{ outcome: 'created' }`. When a replacement would silently lose state your app depends on, set `reattach: 'required'`:
205
+
206
+ ```typescript
207
+ const sandbox = new RailwaySandbox({
208
+ sandboxId: 'existing-railway-sandbox-id',
209
+ reattach: 'required',
210
+ })
211
+ ```
212
+
213
+ With `reattach: 'required'`, a missing or stopped sandbox rejects `start()` with a `SandboxError` whose `code` is `SANDBOX_REATTACH_FAILED`, and no new sandbox is created. The error's `details` include `provider`, `sandboxId`, and `logicalId` (the sandbox's logical `id`). Other errors, such as network or authentication failures, propagate unchanged. To start fresh, clear your persisted `sandboxId` and construct the sandbox without it. Clones inherit the `reattach` setting.
214
+
204
215
  ## Constructor parameters
205
216
 
206
217
  **id** (`string`): Unique identifier for this sandbox instance. (Default: `Auto-generated`)
@@ -211,6 +222,8 @@ const result = await sandbox.executeCommand('cat', ['/tmp/state.txt'])
211
222
 
212
223
  **sandboxId** (`string`): Reattach to an existing Railway sandbox by its Railway ID instead of creating a new one. When set, start() calls Sandbox.connect().
213
224
 
225
+ **reattach** (`'best-effort' | 'required'`): What start() does when sandboxId is set but that sandbox no longer exists or isn't running. 'best-effort' provisions a replacement sandbox. 'required' throws a SandboxError with code SANDBOX\_REATTACH\_FAILED instead of provisioning. (Default: `'best-effort'`)
226
+
214
227
  **checkpointName** (`string`): Named Railway checkpoint used to seed new sandboxes and preserve the filesystem before idle teardown. Use a unique stable name for each independent filesystem.
215
228
 
216
229
  **seedCheckpointName** (`string`): Boot-only fallback checkpoint used when checkpointName has no stored state. Later snapshots continue writing to checkpointName.