0
Fork 0
mirror of https://github.com/mastra-ai/mastra.git synced 2026-11-17 08:44:46 +00:00
Commit graph

1,851 commits

Author SHA1 Message Date
NikAiyer
d929736435
fix(core): use one stream bus for durable agents (#30229)
Durable agents now use the wrapped Agent's stream bus instead of
constructing a second one. An Agent-level pubsub carries both run frames
and thread events, including after registration and forks; evented
execution still uses Mastra's shared transport. Standalone durable
agents remain observable, and plain-run records and abort checks stay
separate from durable execution.

Previously, observing across replicas required repeating the pubsub on
the durable wrapper. This now works with the Agent configuration alone:

```ts
const agent = createDurableAgent({
  agent: new Agent({ id: 'assistant', name: 'Assistant', instructions, model, pubsub }),
});
```

Inngest explicitly exposes its detached-streaming capability without
migrating its bus. The server retains the `isDurableAgentLike` fallback
in `hasResumableStreams` for compatibility with older Inngest wrappers:
their proxy can inherit `false` from a plain Agent or lack the method
entirely. Server and Inngest versions are not coupled, so removing the
fallback would silently turn HTTP disconnects into run cancellation on
supported mixed-version installs. This is a deliberate, user-approved
exception to the ticket's shortcut-removal bullet; no peer-dependency
bump is needed while the fallback remains. Regression coverage exercises
capability `true`, `false`, and missing; the latter two fail without the
fallback.

Server branch audit (`packages/server/src/server/handlers/agents.ts`):
`validateDurableToolCallAccess` (line 298) remains because approvals
need durable workflow snapshots; `authorizeRunAccess` (2676) remains
because durable ownership uses workflow rows/local and replay owners
rather than plain run records (COR-1542). The two abort-route branches
(2724 and 2742) retain durable cancellation support and its
missing/finished-run acknowledgement semantics, not separate transports.

The observe-route branch (3141) remains for generation-fenced
`__subscribeToRunStream` and the Inngest adapter's `pubsub` fallback;
consolidating observation is COR-1541, and migrating Inngest's bus is
COR-1539. The recover-route guard (3746) remains because only durable
execution has recoverable workflow snapshots. None of these remaining
branches requires a second stream bus on core DurableAgent.

The Mastra-fallback regression also runs through a fork created after
registration, both with and without resolving the bus before
registration. Another replica must receive replay plus live tail through
finish, and the terminal frame must be published on Mastra's transport.
The latest targeted rerun passed 33 tests, including cache-policy
warnings and plain-publisher isolation across both durable storage
variants; core typecheck, targeted lint, formatting and diff checks
passed.

Verified with 1,643 core durable/stream tests, 78 AIMock parity tests,
292 server handler tests (including the mixed-version capability cases),
119 Inngest tests, and six real Redis cross-server cases covering live
observation, thread events and HTTP Stop. Typechecks, lint and
formatting pass. The Agent-pubsub regression failed before the fix; a
built-package red/green demo also confirms the transport change. An
earlier approval-resume timing failure passed in isolation and on the
final full rerun.

Fixes COR-1540




## Transport precedence and upgrade scope

Default-engine durable run transport precedence is now: explicit
`createDurableAgent` pubsub → wrapped Agent pubsub → Mastra pubsub.
Evented runs retain Mastra's shared transport. Mastra-only
configurations are unchanged.

If the wrapped Agent already specifies a different transport from Mastra
and the wrapper has no override, this fix changes the effective
run-frame and remote Stop transport. To preserve routing across an
upgrade, explicitly pass the previous transport to `createDurableAgent`
or align the Agent and Mastra transports. The wrapper configures the
shared stream bus, so its override also affects resumable streams from
direct calls on the wrapped Agent. The core changeset includes this
upgrade note.

A local investigation used separately built pre-change main
(`049b31dd2c`) and this branch with real Redis in both owner/observer
version directions. Shared effective transport passed live completion,
replay, and remote Stop. Distinct selected transports lost live
completion and remote Stop acknowledgement; shared-cache replay still
worked. This is a configuration-dependent routing cutover, not a general
rolling-deploy incompatibility. The investigation-only second-checkout
harness and expected failures are not included in this PR; existing
same-version Redis coverage remains.

Permanent coverage now executes wrapper and fork runs with three
distinct wrapper/Agent/Mastra buses, verifies run frames only reach the
wrapper bus, and verifies replayed output. Dropping the wrapper override
makes this test fail on the intended publication assertion. Latest
focused verification: 38 tests passed; core typecheck, type-aware lint,
formatting, and diff checks passed.

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

ELI5: Durable agents now send live updates through the same stream
channel as the normal agent they wrap. Before, they built a second
channel. Users can now set up cross-server viewing by configuring only
the wrapped agent.

## Summary

This PR changes durable agents to use the wrapped `Agent`'s stream bus.
They no longer build a second bus. Agent-level pubsub carries run frames
and thread events, including after registration and forks. Evented
execution continues to use Mastra's shared transport.

### Core changes (`packages/core`)

- `Agent` stores a fallback stream pubsub and a shared-run-log
capability callback.
- `__getStreamBus()` initializes a bus when wrapper stream configuration
exists or streams are enabled. It prefers wrapper configuration over
agent durable settings.
- `__getStreamBus()` uses the configured pubsub, or the agent pubsub. If
neither exists, it uses a reusable fallback `EventEmitterPubSub`.
- The shared-run-log check uses the wrapper callback when configured.
Otherwise, it calls `__usesSharedRunLog()`.
- `__ownsPlainStreamPublisher()` still selects the plain publisher. It
now gets its bus through `__getStreamBus()`.
- Plain publishing still requires enabled agent streams.
- `__configureDurableStreams(config, usesSharedRunLog)` overlays defined
wrapper values on the agent durable settings and any existing wrapper
settings. It stores the callback and resets the bus.
- Agent forks copy the durable stream configuration and share the
fallback pubsub.
- `DurableAgent` delegates stream-bus ownership and access to the
wrapped agent. Its cache, pubsub, cleanup scheduling, and replay-owner
operations use that bus.
- The `DurableAgent` constructor configures durable streams on the
wrapped agent. `__getStreamBus()` returns that bus.
- `DurableAgent` no longer copies a private bus configuration when
forked. It no longer adopts the inner pubsub. Mastra registration no
longer registers a separate bus.
- `DurableAgent` adds `__setLogger(logger: IMastraLogger)`. It forwards
logger updates to the wrapped agent.
- The `AgentStreamBus` constructor accepts an optional `defaultPubsub`.
The bus uses it when `config.pubsub` is absent, before the new
`EventEmitterPubSub` fallback.
- `AgentStreamBus.forkConfig` and `adoptInnerPubsub` are removed.
- Direct `stream` and `generate` calls on an agent with `durable: false`
stay unpublished. This holds after durable wrapping configures the
shared bus. The wrapper can still publish through that bus.
- Plain-run records and abort checks stay separate from durable
execution.

### Inngest changes (`workflows/inngest`)

- `InngestAgent` adds the public method `hasResumableStreams():
boolean`. It always returns `true`.
- The internal `Pick` type includes this method.
- Inngest exposes detached streaming. It does not migrate its bus.
- A new test checks that `createInngestAgent` reports resumable streams
when its wrapped `Agent` has `durable: false`.

### Server changes (`packages/server`)

- `hasResumableStreams` keeps the `isDurableAgentLike` fallback for
older Inngest wrappers in mixed-version installs.
- The observe-stream handler keeps the same fallback.
- The fallback applies when a wrapper reports `false` or does not report
the capability.
- Removing the fallback would cause the reported capability-`false` and
missing-method regression cases to fail.
- This PR does not require a peer-dependency bump while the fallback
remains.
- Other server branches handle durable tool-call access, run
authorization, abort, observation, and recovery. The PR states these
address separate durable-workflow behavior or deferred work. They do not
need a second stream bus on core `DurableAgent`.
- Comments in `hasResumableStreams` and the observe-stream handler were
revised. No executable behavior changed.
- The durable-wrapper stream-detachment test runs with
`hasResumableStreams` set to `true`, `false`, and absent. The stream
observer detaches in each case.

### Redis pubsub (`pubsub/redis-streams`)

- The cross-server abort test runs for the durable and evented engines
with the Mastra bus. It runs for the durable engine with the agent bus.
- Each child server receives the selected bus location.
- The successful-abort case subscribes the other server to the run's
thread. That server verifies a tool-call chunk. It then verifies
completion and a finish chunk after the abort.
- The remote abort response remains `{ aborted: true }`. The owner's run
ends aborted.
- The abort fixture adds `BUS_LOCATION=agent`. With this value, the
agent uses Redis Streams pubsub. The Mastra-level bus uses
`EventEmitterPubSub`.
- Without `BUS_LOCATION=agent`, the agent has no explicit pubsub. With
`ENGINE=evented`, the Mastra-level bus uses `CachingPubSub` over Redis
Streams. Otherwise, it uses Redis Streams directly.
- The `stream` command accepts optional `threadId` and `resourceId`. It
passes them as memory configuration when `threadId` is present.
- The fixture adds `observe` and `subscribe` commands. `observe` streams
run observations. `subscribe` streams thread subscription chunks.

### Tests

- The shared-bus tests add a standalone mode. They cover replay and
live-tail observation with and without forks. They also cover bus
resolution before registration.
- The tests verify finish-event publication.
- Replayed start and tool-call frames are asserted only for registered
replicas.
- A prior logger-warning assertion was removed.
- Thread-coordination tests abort across processes in every
`sharedFrames` case. They observe the aborted run's frames. They expect
an aborted finish reason and one model request.
- New tests check run-frame routing for plain, durable, and evented
agents. They cover configurations with both agent-level and Mastra
buses. They also check replay from an unregistered durable agent whose
wrapped agent has `durable: false`.
- The explicit durable-execution test expects the original agent and its
durable wrapper to share the same stream bus.
- A direct-execution test checks that `stream` and `generate` runs stay
unpublished when a `durable: false` agent is wrapped and registered.
Runs through the durable wrapper publish a finish event.

### Changesets

- Patch changesets cover `@mastra/core`, `@mastra/server`, and
`@mastra/inngest`.
- The `@mastra/core` changeset includes an upgrade note. Mastra-only
configurations keep their behavior. Users who need the previous
transport can keep it by configuring it explicitly.

### Verification

The PR description reports these results. This summary does not
independently verify them.

- 1,643 core durable and stream tests passed.
- 78 AIMock parity tests passed.
- 292 server handler tests passed.
- 119 Inngest tests passed.
- Six real Redis cross-server cases passed.
- A latest targeted rerun passed 33 tests. It covered cache-policy
warnings and plain-publisher isolation across both durable storage
variants.
- Typechecks, targeted lint, formatting, and diff checks passed.
- The Agent-pubsub regression test failed before the fix.
- An earlier approval-resume timing test failed. It passed in isolation
and on the final full rerun.

### Diff size

- 14 files changed.
- 341 lines added.
- 118 lines removed.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: review <review@local>
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-16 07:21:54 -08:00
Rhys Balevicius
7517474b39
fix(studio): load Gateway v2 models and skip v1 memory calls (#29445)
## Why

Studio currently shows Gateway models from a bundled registry and sends
memory requests to the Gateway v1 API whenever a Gateway key exists. A
deployed project using Gateway v2 can therefore offer unsupported models
and receive 404s from the v1-only memory endpoints.

## Design

When the deployment sets `MASTRA_GATEWAY_VERSION=v2`, fetch the
authenticated `/v1/models` catalog from the configured Gateway and offer
only models with a chat endpoint through Mastra's chat model selector.
If catalog loading fails, do not fall back to the v1 model list. Treat
the Gateway memory client as unavailable in v2 mode so memory handlers
use the agent's own memory configuration. V1 behavior remains unchanged.

The Platform runtime signal is introduced by
[platform#4329](https://github.com/mastra-ai/platform/pull/4329);
deploying that PR alone will not change Studio until these Mastra
packages are released and the project is redeployed.

## Validation

- Focused core Gateway tests: 9 passed, including live model filtering
and catalog failure behavior.
- Focused server Gateway memory test: 1 passed.
- `git diff --check` passed.
- A live deployed Studio smoke test is still needed after the updated
packages are published and deployed. Full package typechecks were
unavailable in the isolated worktree because its linked local dependency
builds are older than this checkout.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## ELI5

When Gateway v2 is on, Studio lists only the chat models from the live
Gateway catalog. It also stops calling the Gateway v1 memory API. A
resolved agent without memory now shows no memory data, not
shared-storage data.

## Changes

- In v2 mode, `MastraGateway.fetchProviders()` requests `/v1/models`
with authentication and a 10-second timeout. It keeps only models that
have a string `id` and a `chat` endpoint.
- If the catalog request fails or returns an invalid response, the call
throws. It does not fall back to the v1 model list.
- The provider list skips the bundled `mastra` registry entry in v2
mode. This prevents stale model IDs from appearing.
- Other Gateway versions keep the OpenRouter model list.
- In v2 mode, `getGatewayClient()` returns `null`. Memory handlers then
use the agent's own memory configuration.
- For a resolved v2 Gateway agent without memory:
  - Thread listing returns "Memory is not initialized".
  - Message listing returns empty `messages` and `uiMessages` arrays.
- Unresolved agents keep the storage fallback.
- v2 detection uses `isGatewayV2()`. It returns true when any of these
conditions holds:
  - `MASTRA_GATEWAY_VERSION` is `v2`.
  - The API key starts with `msk-gateway-` or `mskv2_`.
- A registered `mastra` gateway instance reports `isV2()` as true.
`MastraGateway.isV2()` is a new public method. This check covers
gateways configured with a v2 key and no matching environment variables.
- Added patch changesets for `@mastra/core` and `@mastra/server`.

## Testing and rollout

- Completed CI results are not available for this review.
- The author reports that focused core Gateway tests, a focused server
memory test, and `git diff --check` passed. These results were not
verified here.
- Full package typechecks were not run in the author's isolated
worktree.
- A deployed Studio smoke test is still needed. It requires the updated
Mastra packages to be published and the project to be redeployed.
- The Platform runtime signal depends on platform#4329. Deploying that
change alone does not affect Studio.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Taofeeq Oluder <oluderutaofeeq@gmail.com>
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-16 10:00:32 -05:00
dane-ai-mastra[bot]
a5859ee2b9
chore: version packages (alpha) (#30430)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-11-16 14:09:31 +01:00
dane-ai-mastra[bot]
15dc07c51d
chore: version packages (alpha) (#30394)
This PR was opened by the [Changesets
release](https://github.com/changesets/action) GitHub action. When
you're ready to do a release, you can merge this and publish to npm
yourself or [setup this action to publish
automatically](https://github.com/changesets/action#with-publishing). If
you're not ready to do a release yet, that's fine, whenever you add more
changesets to main, this PR will be updated.

⚠️⚠️⚠️⚠️⚠️⚠️

`main` is currently in **pre mode** so this branch has prereleases
rather than normal releases. If you want to exit prereleases, run
`changeset pre exit` on `main`.

⚠️⚠️⚠️⚠️⚠️⚠️

# Releases
## @mastra/core@1.84.0-alpha.2

### Minor Changes

- Added run metadata to background process callbacks.
([#30161](https://github.com/mastra-ai/mastra/pull/30161))

`backgroundProcesses` callbacks on `execute_command` now receive, when
available, the `agentId`, `threadId`, `resourceId`, and `runId` of the
call that started the process, so hosts can route exit notices to the
right conversation. `onExit` also receives `killedByAbort`, which is
`true` when the abort signal fired (the run's signal by default) and
killed the process.

  ```ts
  backgroundProcesses: {
    onExit: ({ pid, exitCode, threadId, killedByAbort }) => {
if (!killedByAbort) notifyThread(threadId, `Process ${pid} exited with
code ${exitCode}`);
    },
  },
  ```

`truncateOutput` and `DEFAULT_TAIL_LINES` are now exported from
`@mastra/core/workspace`, so hosts can trim process output the same way
`execute_command` does.

### Patch Changes

- Fixed retries in `dountil` and `dowhile` loops on the evented engine.
Each iteration of a loop body now starts at `retryCount` 0 and gets the
step's full `retries`, as on the default engine. Before, the count
carried over from earlier iterations, so a body that failed once in a
later iteration could run out of retries and fail the run.
([#30383](https://github.com/mastra-ai/mastra/pull/30383))

If your step code reads `retryCount` inside a loop body, it now gets the
attempt within the current iteration. The loop condition receives the
iteration number as `iterationCount`. To use it inside the body, pass it
through the step's output or workflow state.

- Fixed durable agent runs failing with
`DURABLE_AGENT_EXECUTION_UNVERIFIED` when an ownership check took longer
than the lease TTL (15 seconds by default) while the same process still
held the run. These runs used to fail and lose their saved snapshots.
They now keep running, and a step stops only when an ownership check
fails, the claim can't be renewed before it expires, or another
execution takes over the run.
([#30386](https://github.com/mastra-ai/mastra/pull/30386))

- Fixed workflow recovery restarting a run that is still executing,
which ran its steps twice. `startAsync()` now takes the run's lease
before it saves the first snapshot, so it resolves after the lease is
taken and rejects if taking it fails. Runs of workflows whose
`shouldPersistSnapshot` saves `waiting` but not `running` now hold a
lease too, so recovery no longer restarts them while they execute or
sleep. ([#30384](https://github.com/mastra-ai/mastra/pull/30384))

- `processToolResult` now sees and can rewrite a tool's `toModelOutput`
result. Previously, when a tool mapped its result with `toModelOutput`
(for example a file viewer returning images), output processors only saw
and changed the raw result, and the mapped output, images included,
still reached the next model call and stored history unchanged.
([#30401](https://github.com/mastra-ai/mastra/pull/30401))

The hook now receives `modelOutput`. To replace it, commit a
`result`-state part that carries the new value in
`providerMetadata.mastra.modelOutput`:

  ```ts
processToolResult({ messageList, toolCallId, toolName, args, result,
modelOutput }) {
    messageList.updateToolInvocation({
      type: 'tool-invocation',
toolInvocation: { state: 'result', toolCallId, toolName, args, result },
providerMetadata: { mastra: { modelOutput: shrinkImages(modelOutput) }
},
    });
  }
  ```

A processor that replaces only `result`, or edits it in place, now has
the new value mapped through `toModelOutput` again, so the model reads
the mapping of the processed result rather than of the original. With
several processors, each one receives the `modelOutput` the processor
before it committed, so a later processor can't bring back an image an
earlier one removed. This applies to both regular and durable agents. In
durable agents, a `processToolResult` that throws now also keeps the
unprocessed mapped output from the model, not only the raw result.
## @mastra/client-js@1.60.1-alpha.2

### Patch Changes

- Updated dependencies
[[`7277766`](7277766d6c),
[`951a18b`](951a18b085),
[`f4458ee`](f4458eea7f),
[`a3b4ef9`](a3b4ef9ecd),
[`547600d`](547600d004)]:
  - @mastra/core@1.84.0-alpha.2
## @mastra/react@1.15.1-alpha.2

### Patch Changes

- Updated dependencies
[[`7277766`](7277766d6c),
[`951a18b`](951a18b085),
[`f4458ee`](f4458eea7f),
[`a3b4ef9`](a3b4ef9ecd),
[`547600d`](547600d004)]:
  - @mastra/core@1.84.0-alpha.2
  - @mastra/client-js@1.60.1-alpha.2
## @mastra/deployer-cloud@1.84.0-alpha.2

### Patch Changes

- Updated dependencies
[[`7277766`](7277766d6c),
[`951a18b`](951a18b085),
[`f4458ee`](f4458eea7f),
[`a3b4ef9`](a3b4ef9ecd),
[`547600d`](547600d004)]:
  - @mastra/core@1.84.0-alpha.2
  - @mastra/deployer@1.84.0-alpha.2
## @mastra/longmemeval@1.1.43-alpha.2

### Patch Changes

- Updated dependencies
[[`7277766`](7277766d6c),
[`9eae968`](9eae9680d2),
[`951a18b`](951a18b085),
[`f4458ee`](f4458eea7f),
[`a3b4ef9`](a3b4ef9ecd),
[`547600d`](547600d004)]:
  - @mastra/core@1.84.0-alpha.2
  - @mastra/memory@1.41.2-alpha.1
## @mastra/opencode@0.1.43-alpha.2

### Patch Changes

- Updated dependencies
[[`7277766`](7277766d6c),
[`9eae968`](9eae9680d2),
[`951a18b`](951a18b085),
[`f4458ee`](f4458eea7f),
[`a3b4ef9`](a3b4ef9ecd),
[`547600d`](547600d004)]:
  - @mastra/core@1.84.0-alpha.2
  - @mastra/memory@1.41.2-alpha.1
## @mastra/factory@0.29.0-alpha.2

### Patch Changes

- Recognize Detail findings as linked work items so intake cards retain
their external source and rule identity.
([#30410](https://github.com/mastra-ai/mastra/pull/30410))

- Updated dependencies
[[`7277766`](7277766d6c),
[`951a18b`](951a18b085),
[`f4458ee`](f4458eea7f),
[`a3b4ef9`](a3b4ef9ecd),
[`547600d`](547600d004)]:
  - @mastra/core@1.84.0-alpha.2
  - @mastra/code-sdk@1.19.1-alpha.2
## create-factory@0.4.4-alpha.2

### Patch Changes

- Updated dependencies:
  - mastra@1.39.1-alpha.2
## @mastra/code-sdk@1.19.1-alpha.2

### Patch Changes

- Updated dependencies
[[`7277766`](7277766d6c),
[`9eae968`](9eae9680d2),
[`951a18b`](951a18b085),
[`f4458ee`](f4458eea7f),
[`a3b4ef9`](a3b4ef9ecd),
[`547600d`](547600d004)]:
  - @mastra/core@1.84.0-alpha.2
  - @mastra/memory@1.41.2-alpha.1
  - @mastra/client-js@1.60.1-alpha.2
## mastracode@0.50.1-alpha.2

### Patch Changes

- Updated dependencies
[[`7277766`](7277766d6c),
[`9eae968`](9eae9680d2),
[`951a18b`](951a18b085),
[`f4458ee`](f4458eea7f),
[`a3b4ef9`](a3b4ef9ecd),
[`547600d`](547600d004)]:
  - @mastra/core@1.84.0-alpha.2
  - @mastra/memory@1.41.2-alpha.1
  - @mastra/code-sdk@1.19.1-alpha.2
## @mastra/agent-builder@1.2.2-alpha.1

### Patch Changes

- Updated dependencies
[[`7277766`](7277766d6c),
[`9eae968`](9eae9680d2),
[`951a18b`](951a18b085),
[`f4458ee`](f4458eea7f),
[`a3b4ef9`](a3b4ef9ecd),
[`547600d`](547600d004)]:
  - @mastra/core@1.84.0-alpha.2
  - @mastra/memory@1.41.2-alpha.1
## mastra@1.39.1-alpha.2

### Patch Changes

- Updated dependencies
[[`7277766`](7277766d6c),
[`951a18b`](951a18b085),
[`f4458ee`](f4458eea7f),
[`a3b4ef9`](a3b4ef9ecd),
[`547600d`](547600d004)]:
  - @mastra/core@1.84.0-alpha.2
  - @mastra/deployer@1.84.0-alpha.2
## @mastra/deployer@1.84.0-alpha.2

### Patch Changes

- Updated dependencies
[[`7277766`](7277766d6c),
[`951a18b`](951a18b085),
[`f4458ee`](f4458eea7f),
[`a3b4ef9`](a3b4ef9ecd),
[`547600d`](547600d004)]:
  - @mastra/core@1.84.0-alpha.2
  - @mastra/server@1.84.0-alpha.2
## @mastra/editor@0.17.2-alpha.1

### Patch Changes

- Updated dependencies
[[`7277766`](7277766d6c),
[`9eae968`](9eae9680d2),
[`951a18b`](951a18b085),
[`f4458ee`](f4458eea7f),
[`a3b4ef9`](a3b4ef9ecd),
[`547600d`](547600d004)]:
  - @mastra/core@1.84.0-alpha.2
  - @mastra/memory@1.41.2-alpha.1
## @mastra/mcp-docs-server@1.3.14-alpha.2

### Patch Changes

- Updated dependencies
[[`7277766`](7277766d6c),
[`951a18b`](951a18b085),
[`f4458ee`](f4458eea7f),
[`a3b4ef9`](a3b4ef9ecd),
[`547600d`](547600d004)]:
  - @mastra/core@1.84.0-alpha.2
## @mastra/memory@1.41.2-alpha.1

### Patch Changes

- Observational Memory does half as much work per step in long tool
runs. Token counting no longer serializes every plain JSON tool result a
second time just to check it for images, so each step serializes the
earlier tool results twice instead of four times. Token counts are
unchanged. ([#30400](https://github.com/mastra-ai/mastra/pull/30400))

- Updated dependencies
[[`7277766`](7277766d6c),
[`951a18b`](951a18b085),
[`f4458ee`](f4458eea7f),
[`a3b4ef9`](a3b4ef9ecd),
[`547600d`](547600d004)]:
  - @mastra/core@1.84.0-alpha.2
## @mastra/playground-ui@69.1.0-alpha.2

### Patch Changes

- Connect providers that use OAuth client credentials (`OAUTH2_CC`) or
no authentication (`NONE`) without leaving Studio. Client-credential
providers ask for a client ID and secret in the connect dialog;
providers with no authentication connect immediately instead of opening
an OAuth popup.
([#30336](https://github.com/mastra-ai/mastra/pull/30336))

Providers whose catalog lists only connection settings (for example a
subdomain) now also ask for their API key, username and password, or
client ID and secret. Previously the dialog showed only the settings,
and the connection failed.

The headless connect helpers in `@mastra/playground-ui/domains/connect`
now return a fully resolved `HeadlessAuthField` and support conditional
fields (`visibleWhen`), so other apps can import them instead of keeping
their own copy.

  ```ts
  import {
    headlessAuthFieldKey,
    headlessAuthFields,
    isHeadlessAuthFieldVisible,
    splitHeadlessAuthValues,
    startHeadlessAuth,
  } from '@mastra/playground-ui/domains/connect';

// Every field comes back fully resolved: label, target, required, and
so on are always set.
  const fields = headlessAuthFields(provider);

// Render only the fields whose `visibleWhen` condition matches the
current values.
const visible = fields.filter(field =>
isHeadlessAuthFieldVisible(fields, field, values));
const missingRequired = visible.some(field => field.required &&
!values[headlessAuthFieldKey(field)]);

  // On submit, values for hidden fields are dropped.
const { credentials, params } = splitHeadlessAuthValues(fields, values);
  await startHeadlessAuth({
    sessionToken,
    integrationId: provider.id,
    authType: provider.authType,
    credentials,
    params,
  }).result;
  ```

- Updated dependencies
[[`7277766`](7277766d6c),
[`9eae968`](9eae9680d2),
[`951a18b`](951a18b085),
[`f4458ee`](f4458eea7f),
[`a3b4ef9`](a3b4ef9ecd),
[`547600d`](547600d004)]:
  - @mastra/core@1.84.0-alpha.2
  - @mastra/memory@1.41.2-alpha.1
  - @mastra/client-js@1.60.1-alpha.2
  - @mastra/ai-sdk@1.12.0
  - @mastra/react@1.15.1-alpha.2
## @mastra/server@1.84.0-alpha.2

### Patch Changes

- Updated dependencies
[[`7277766`](7277766d6c),
[`951a18b`](951a18b085),
[`f4458ee`](f4458eea7f),
[`a3b4ef9`](a3b4ef9ecd),
[`547600d`](547600d004)]:
  - @mastra/core@1.84.0-alpha.2
## @mastra/elysia@0.1.24-alpha.2

### Patch Changes

- Updated dependencies
[[`7277766`](7277766d6c),
[`951a18b`](951a18b085),
[`f4458ee`](f4458eea7f),
[`a3b4ef9`](a3b4ef9ecd),
[`547600d`](547600d004)]:
  - @mastra/core@1.84.0-alpha.2
  - @mastra/server@1.84.0-alpha.2
## @mastra/express@1.5.28-alpha.2

### Patch Changes

- Updated dependencies
[[`7277766`](7277766d6c),
[`951a18b`](951a18b085),
[`f4458ee`](f4458eea7f),
[`a3b4ef9`](a3b4ef9ecd),
[`547600d`](547600d004)]:
  - @mastra/core@1.84.0-alpha.2
  - @mastra/server@1.84.0-alpha.2
## @mastra/fastify@1.5.28-alpha.2

### Patch Changes

- Updated dependencies
[[`7277766`](7277766d6c),
[`951a18b`](951a18b085),
[`f4458ee`](f4458eea7f),
[`a3b4ef9`](a3b4ef9ecd),
[`547600d`](547600d004)]:
  - @mastra/core@1.84.0-alpha.2
  - @mastra/server@1.84.0-alpha.2
## @mastra/hono@1.7.26-alpha.2

### Patch Changes

- Updated dependencies
[[`7277766`](7277766d6c),
[`951a18b`](951a18b085),
[`f4458ee`](f4458eea7f),
[`a3b4ef9`](a3b4ef9ecd),
[`547600d`](547600d004)]:
  - @mastra/core@1.84.0-alpha.2
  - @mastra/server@1.84.0-alpha.2
## @mastra/koa@1.7.28-alpha.2

### Patch Changes

- Updated dependencies
[[`7277766`](7277766d6c),
[`951a18b`](951a18b085),
[`f4458ee`](f4458eea7f),
[`a3b4ef9`](a3b4ef9ecd),
[`547600d`](547600d004)]:
  - @mastra/core@1.84.0-alpha.2
  - @mastra/server@1.84.0-alpha.2
## @mastra/nestjs@0.3.1-alpha.2

### Patch Changes

- Updated dependencies
[[`7277766`](7277766d6c),
[`951a18b`](951a18b085),
[`f4458ee`](f4458eea7f),
[`a3b4ef9`](a3b4ef9ecd),
[`547600d`](547600d004)]:
  - @mastra/core@1.84.0-alpha.2
  - @mastra/server@1.84.0-alpha.2
## @mastra/next@0.2.42-alpha.2

### Patch Changes

- Updated dependencies
[[`7277766`](7277766d6c),
[`951a18b`](951a18b085),
[`f4458ee`](f4458eea7f),
[`a3b4ef9`](a3b4ef9ecd),
[`547600d`](547600d004)]:
  - @mastra/core@1.84.0-alpha.2
  - @mastra/hono@1.7.26-alpha.2
  - @mastra/server@1.84.0-alpha.2
## @mastra/tanstack-start@0.2.42-alpha.2

### Patch Changes

- Updated dependencies
[[`7277766`](7277766d6c),
[`951a18b`](951a18b085),
[`f4458ee`](f4458eea7f),
[`a3b4ef9`](a3b4ef9ecd),
[`547600d`](547600d004)]:
  - @mastra/core@1.84.0-alpha.2
  - @mastra/hono@1.7.26-alpha.2
  - @mastra/server@1.84.0-alpha.2
## @mastra/temporal@0.6.1-alpha.2

### Patch Changes

- Updated dependencies
[[`7277766`](7277766d6c),
[`951a18b`](951a18b085),
[`f4458ee`](f4458eea7f),
[`a3b4ef9`](a3b4ef9ecd),
[`547600d`](547600d004)]:
  - @mastra/core@1.84.0-alpha.2
  - @mastra/deployer@1.84.0-alpha.2
## create-mastra@1.39.1-alpha.2


## @internal/playground@1.39.1-alpha.2

### Patch Changes

- Updated dependencies
[[`7277766`](7277766d6c),
[`2f4a9ed`](2f4a9ed771),
[`951a18b`](951a18b085),
[`f4458ee`](f4458eea7f),
[`a3b4ef9`](a3b4ef9ecd),
[`547600d`](547600d004)]:
  - @mastra/core@1.84.0-alpha.2
  - @mastra/playground-ui@69.1.0-alpha.2
  - @mastra/client-js@1.60.1-alpha.2
  - @mastra/react@1.15.1-alpha.2

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-11-14 10:23:58 -08:00
dane-ai-mastra[bot]
1c52fdd034
chore: version packages (alpha) (#30261)
This PR was opened by the [Changesets
release](https://github.com/changesets/action) GitHub action. When
you're ready to do a release, you can merge this and publish to npm
yourself or [setup this action to publish
automatically](https://github.com/changesets/action#with-publishing). If
you're not ready to do a release yet, that's fine, whenever you add more
changesets to main, this PR will be updated.

⚠️⚠️⚠️⚠️⚠️⚠️

`main` is currently in **pre mode** so this branch has prereleases
rather than normal releases. If you want to exit prereleases, run
`changeset pre exit` on `main`.

⚠️⚠️⚠️⚠️⚠️⚠️

# Releases

> The changelog information of each package has been omitted from this
message, as the content exceeds the size limit.

## @mastra/factory@0.29.0-alpha.1


## @mastra/core@1.84.0-alpha.1


## @mastra/playground-ui@69.1.0-alpha.1


## @mastra/client-js@1.60.1-alpha.1


## @mastra/react@1.15.1-alpha.1


## @mastra/deployer-cloud@1.84.0-alpha.1


## @mastra/longmemeval@1.1.43-alpha.1


## @mastra/opencode@0.1.43-alpha.1


## create-factory@0.4.4-alpha.1


## @mastra/code-sdk@1.19.1-alpha.1


## mastracode@0.50.1-alpha.1


## @mastra/arize@1.3.31-alpha.0


## @mastra/arthur@0.4.31-alpha.0


## @mastra/braintrust@1.3.28-alpha.0


## @mastra/datadog@1.4.23-alpha.0


## @mastra/deepeval@0.1.25-alpha.0


## @mastra/laminar@1.3.33-alpha.0


## @mastra/langfuse@1.6.7-alpha.0


## @mastra/langsmith@1.4.4-alpha.0


## @mastra/observability@1.24.1-alpha.0


## @mastra/otel-bridge@1.5.23-alpha.0


## @mastra/otel-exporter@1.5.3-alpha.0


## @mastra/posthog@1.4.8-alpha.0


## @mastra/sentry@1.2.33-alpha.0


## @mastra/agent-builder@1.2.2-alpha.0


## mastra@1.39.1-alpha.1


## @mastra/connect@1.4.1-alpha.0


## @mastra/deployer@1.84.0-alpha.1


## @mastra/editor@0.17.2-alpha.0


## @mastra/mcp-docs-server@1.3.14-alpha.1


## @mastra/memory@1.41.2-alpha.0


## @mastra/server@1.84.0-alpha.1


## @mastra/google-cloud-pubsub@1.1.8-alpha.0


## @mastra/redis-streams@0.8.2-alpha.0


## @mastra/valkey-streams@0.6.3-alpha.0


## @mastra/elysia@0.1.24-alpha.1


## @mastra/express@1.5.28-alpha.1


## @mastra/fastify@1.5.28-alpha.1


## @mastra/hono@1.7.26-alpha.1


## @mastra/koa@1.7.28-alpha.1


## @mastra/nestjs@0.3.1-alpha.1


## @mastra/next@0.2.42-alpha.1


## @mastra/tanstack-start@0.2.42-alpha.1


## @mastra/clickhouse@1.30.1-alpha.0


## @mastra/cloudflare@1.8.1-alpha.0


## @mastra/cloudflare-d1@1.5.1-alpha.0


## @mastra/convex@1.9.1-alpha.0


## @mastra/dsql@1.5.8-alpha.0


## @mastra/dynamodb@1.5.2-alpha.0


## @mastra/libsql@1.30.1-alpha.0


## @mastra/mongodb@1.27.1-alpha.0


## @mastra/mssql@1.11.2-alpha.0


## @mastra/mysql@0.17.1-alpha.0


## @mastra/oracledb@0.5.7-alpha.0


## @mastra/pg@1.36.1-alpha.0


## @mastra/redis@1.4.14-alpha.0


## @mastra/spanner@1.12.1-alpha.0


## @mastra/turso@0.1.22-alpha.0


## @mastra/upstash@1.6.2-alpha.0


## @mastra/valkey@0.2.10-alpha.0


## @mastra/temporal@0.6.1-alpha.1


## @mastra/daytona@0.11.6-alpha.0


## create-mastra@1.39.1-alpha.1


## @internal/playground@1.39.1-alpha.1

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-11-13 19:58:20 -08:00
Tyler Barnes
2087fdccb8
fix(server): limit built-in MCP memory tools to reads and add working-memory inspection (#30245)
## Summary

The built-in MCP server (added in #29931, built-in MCP memory tools)
gives connected MCP clients a set of memory tools. Two of them did more
than an outside client should: `save_messages` wrote raw messages
straight into a thread, and `search_memory` ran a broad semantic-recall
search. There was also no way to read an agent's working memory through
MCP.

This PR narrows the built-in MCP memory toolset to inspection:

- **Removed `save_messages` and `search_memory` from the built-in MCP
toolset.** Their HTTP endpoints are unchanged; only MCP exposure is
removed.
- **Added read-only `get_working_memory`** for a thread or a resource.
It never writes stored state and works in read-only mode.
- With a thread (the request's reserved context thread takes precedence
over a `threadId` argument), it uses the existing thread working-memory
route and its ownership checks.
- Without a thread, it uses a new `GET /memory/working-memory` route
that reads resource-scoped working memory for the caller's effective
resource. When fine-grained authorization (FGA) is configured, the route
requires an authenticated user and checks `memory:read` on that
resource; a grant on a single thread does not authorize the whole
resource.
- Regenerated client route types and CLI route metadata for the new
route.

## Test plan

- New regression tests with real `Memory` + `InMemoryStore`, `Agent` and
`Mastra`, through the MCP catalogue and route handlers: tool list,
thread and resource reads, FGA allow/deny, missing user, spoofed
resource, thread grant vs resource grant, Studio/server FGA provider
selection, reserved context thread precedence, and no storage mutation.
- These tests fail on the code before the fix (8 failed / 25 passed) and
pass after.
- Focused MCP/memory/FGA-provider suites: 140/140.
- Full server suite: 128 files, 3,552 passed, 3 skipped, 1 todo.
- `pnpm build:server`, server TypeScript, lint, formatting, and
`generate:permissions` / `check:permissions` pass.
- Live loopback MCP SDK client check of `tools/list` and `tools/call`:
removed tools are absent, caller identity is enforced, nothing is
written.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## ELI5

This change makes the built-in MCP memory tools read-only. It removes
the tools that save messages or search memory. It adds one tool that
reads working memory for a thread or a resource.

## Summary

This change limits the built-in MCP memory toolset to inspection. It
removes the `save_messages` and `search_memory` tools from MCP. Their
HTTP endpoints remain unchanged. It adds a read-only
`get_working_memory` MCP tool.

### Behavior

- **Thread reads:** The tool uses the reserved context thread ID when
one exists. Otherwise, it uses the `threadId` argument. Thread reads use
the existing thread working-memory route. The existing ownership checks
apply.
- **Resource reads:** When no thread ID is available, the tool calls the
new route `GET /memory/working-memory`. The route reads working memory
for the effective resource ID. When the tool call omits the resource ID,
the tool uses the value from the request context.
- **Fine-grained authorization (FGA):** When an FGA provider is
configured, the resource route requires an authenticated user and
`memory:read` permission on the effective resource. The FGA check passes
request context. A grant on one thread does not authorize resource-wide
access.
- **Memory unavailable:** The resource route returns null working memory
when memory is unavailable.
- **Thread-scoped requests on the resource route:** The resource route
rejects thread-scoped working memory.

### Changed files

- `packages/server/src/server/handlers/memory.ts`: Adds MCP metadata to
`GET_WORKING_MEMORY_ROUTE`. Adds `GET_RESOURCE_WORKING_MEMORY_ROUTE`.
Removes MCP tool metadata from `SAVE_MESSAGES_ROUTE` and
`SEARCH_MEMORY_ROUTE`.
- `packages/server/src/server/mcp/toolsets/memory.ts`: Adds
working-memory retrieval for threads and resources. Removes the search
and message-saving operations.
- `packages/server/src/server/server-adapter/routes/memory.ts`: Adds the
new route to the exported `MEMORY_ROUTES`.
- `packages/server/src/server/server-adapter/routes/fga-manifest.ts`:
Registers `/memory/working-memory` as a resource route. The resource ID
comes from the request context, or from the `resourceId` parameter.
- `packages/server/src/server/server-adapter/index.test.ts`: Adds FGA
tests for the resource working-memory endpoint.
- `packages/server/src/server/mcp/toolsets.test.ts`: Adds tests for FGA
provider selection, fail-closed behavior, resource and thread
permissions, reserved-context precedence, and read-only inspection.
Updates the expected tool list.
-
`server-adapters/server-adapters-test-suite/src/builtin-mcp-parity-test-suite.ts`:
Removes `save_messages` and `search_memory` from the expected tool list.
-
`server-adapters/server-adapters-test-suite/src/builtin-mcp-toolsets-test-suite.ts`:
Adds `get_working_memory` to the parity and read-only cases. Asserts
that `save_messages` is not offered to a non-owner and that the HTTP
write returns 403.
- `server-adapters/server-adapters-test-suite/src/route-test-utils.ts`:
Sets a default `resourceId` for `GET /memory/working-memory`.
- `.changeset/red-pets-throw.md`: Declares patch releases for
`@mastra/client-js`, `@mastra/server`, and `mastra`.

The PR also regenerates client route types and CLI route metadata.

The diff changes 12 files, with 558 lines added and 57 removed.

### Public API

- New route: `GET_RESOURCE_WORKING_MEMORY_ROUTE` at `GET
/memory/working-memory`.
- Changed export: `MEMORY_ROUTES` includes the new route.
- MCP tool surface: `save_messages` and `search_memory` are removed from
MCP. `get_working_memory` is added. The HTTP endpoints for the removed
tools are unchanged.

### Verification

The author reports these results. This summary did not run them:

- 140 of 140 focused MCP, memory, and FGA-provider tests pass.
- 128 server test files pass, with 3,552 tests passed, 3 skipped, and 1
todo.
- Server build, TypeScript, lint, formatting, and permission-generation
checks pass.
- A live loopback MCP SDK check of `tools/list` and `tools/call` passes.
- The author reports that the new regression tests failed before the
change (8 failed, 25 passed) and pass after it.

CI status on the current head: not available.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: remy-builder[bot] <324360501+remy-builder[bot]@users.noreply.github.com>
2026-11-13 15:06:31 -07:00
dane-ai-mastra[bot]
34dbbd363e
chore: version packages (alpha) (#30241)
This PR was opened by the [Changesets
release](https://github.com/changesets/action) GitHub action. When
you're ready to do a release, you can merge this and publish to npm
yourself or [setup this action to publish
automatically](https://github.com/changesets/action#with-publishing). If
you're not ready to do a release yet, that's fine, whenever you add more
changesets to main, this PR will be updated.

⚠️⚠️⚠️⚠️⚠️⚠️

`main` is currently in **pre mode** so this branch has prereleases
rather than normal releases. If you want to exit prereleases, run
`changeset pre exit` on `main`.

⚠️⚠️⚠️⚠️⚠️⚠️

# Releases
## @mastra/factory@0.29.0-alpha.0

### Minor Changes

- Intake rules can now set a description on the cards they create, so
cards from integrations show the item's details instead of an empty
description. ([#30253](https://github.com/mastra-ai/mastra/pull/30253))

  ```ts
  return {
    type: 'upsertLinkedWorkItem',
    board: context.intake.board,
    source: 'github-dependabot-alert',
    sourceKey: alert.id,
    title: alert.title,
    description: alert.description,
    url: alert.url,
    stage: context.intake.initialPhase,
    // ...
  };
  ```

- Added Vanta vulnerabilities as a Factory intake source through
MastraConnect. Once you connect Vanta and enable it in intake settings,
each active vulnerability becomes a card labeled `security` with its
severity, package, and remediation date in the description.
([#30255](https://github.com/mastra-ai/mastra/pull/30255))

- Intake integrations are now off until you turn them on. A newly
connected integration no longer starts pulling items onto your boards
until you enable it in the intake settings.
([#30251](https://github.com/mastra-ai/mastra/pull/30251))

- Added two reads that serve a Factory board without sending every card.
`GET /web/factory/projects/:id/boards/:boardKey/phases` returns, for
each phase of the board, how many cards it holds and the first of them
in the order asked, after the search and filters given. `GET
/web/factory/projects/:id/work-items/filter-options` returns the labels
and people the board can be filtered by. `item=<card id>` also answers
for one card and its place in each phase, however deep it lies, without
listing the phase down to it. Each card is named with a `version` of its
body, which `?workItemId=` also sends, so a reader keeps the bodies it
holds and reads only the ones that changed.
([#30177](https://github.com/mastra-ai/mastra/pull/30177))

  ```ts
const res = await
fetch(`/web/factory/projects/${projectId}/boards/work/phases?label=bug&limit=10&cards=true`);
const { phases, matchingTotal, boardTotal, workItems } = await
res.json();
// phases: [{ phase: "intake", total: 42, cards: [{ id, version }, …] },
…]
  ```

- Added Dependabot alerts as a Factory intake source. Turn on **Sync
alerts** under GitHub in intake settings and pick repositories, or `PUT
/web/intake/config` with `{ "dependabot": { "enabled": true,
"sourceIds": ["owner/repo"] } }`. Open alerts in those repositories
become cards labeled `security` with the advisory details as the
description, and they close automatically when the alert is fixed or
dismissed. ([#30254](https://github.com/mastra-ai/mastra/pull/30254))

- Changing an intake route now warns you when cards already on your
boards match a different board, and offers to move those untouched cards
to the start of their new board.
([#30252](https://github.com/mastra-ai/mastra/pull/30252))

### Patch Changes

- Fixed who owns the sessions a Factory card runs in, and who can
approve what they wait on.
([#30146](https://github.com/mastra-ai/mastra/pull/30146))

  **Who owns a card's phase session**

- In a Factory that runs card work on the organization's model keys (the
`factory` and `hybrid` credential settings), every new phase session now
belongs to the Factory itself and uses the organization's keys and the
Factory's default model. That holds whoever moved the card: a person, an
agent, a webhook or a rule. Before, it ran as whoever connected the
repository, or as the person who approved the move.
- The person who moved or approved the card stays on record as the one
who did it. When they move a card from their own session, that session
follows the card, so it hears when the phase waits on someone and can
answer from there.
- If the organization has neither a model key nor a provider of its own,
the run stops with a clear "add an organization key or provider" message
and is not tried again on its own. Add one, then press Retry on the
card.
- In a Factory on personal credentials there are no organization keys,
so a phase runs as the person who moved or approved the card (or whose
session's agent moved it), and otherwise as the person who created the
Factory.

  Sessions that already exist keep their owner.

  **Approving a waiting tool call**

- The person who asked for the work, and anyone whose session follows
the card, can approve or decline any tool call the phase session is
waiting on, a plan or any other tool that asks first. They can do it
from their own session in the sidebar, with `factory_answer_approval`,
or over HTTP:

    ```http
    POST /web/user-sessions/:sessionId/parked-approval
    { "decision": "approve" }
    ```

Add `toolCallId` when the session waits on more than one approval.
Questions that need a typed answer are still answered in the session.

- A session following the card is told when the phase session waits on a
yes or no, for a plan or any other tool, with the call to answer it. In
the chat that notice now has Approve and Decline buttons and a link to
open the waiting session; a notice about a question that needs a typed
answer has the link only.
- Nobody is asked to approve what a phase approves itself: when a
phase's `exitTool` has `autoApprove` and the card matches
`autoApproveWhen`, the run carries on without a notice. This now works
for any exit tool that pauses for a yes or no, not only `submit_plan`.
- When two people answer the same call at once, one answer is used and
the other is told the call was already answered.
- The run then carries on as the phase session's owner. Before, it
carried on as whoever answered, and could fail with "the request has no
authenticated user".
- Following moves with a session: after a hand-over, the session's new
owner can answer and the old one cannot.

  **Sidebar**

A card's phase sessions now show under the session that asked for the
work when child sessions are revealed, marked "run by Factory" when the
Factory owns them, and that session shows "waiting on you", with Approve
and Decline in its menu, while one of them waits on the viewer.

- Mastra Code's Knowledge scopes now use canonical addresses, matching
`@mastra/core`'s one-segment scope values. Factory sessions hold their
org and project ids encoded (`org:acme%3Aeu` for org `acme:eu`), and the
`/knowledge` inspector and Factory Knowledge routes read the same
addresses the code agent writes, instead of encoding host scopes a
second time. ([#30019](https://github.com/mastra-ai/mastra/pull/30019))

- Sandboxes in a Factory with more than ten repositories can now reach
all of them with `git` and `gh`. The Factory mints each sandbox token
for at most ten repositories, so the sandbox now gets one token per
group of ten (`GH_TOKEN`, `GH_TOKEN_2`, …). Each checkout's git
credential helper uses the token that covers it, `github_refresh_token`
refreshes every group, and the environment note tells the agent which
variable to use for `gh` in each repository, for example
`GH_TOKEN=$GH_TOKEN_2 gh pr list -R owner/repo`. Before, a Factory over
ten repositories fell back to a token for the session repository only.
([#30121](https://github.com/mastra-ai/mastra/pull/30121))

- Fixed GitHub pull request cards losing their labels, so intake routes
that match on labels (for example `security`) now route pull requests
too. ([#30250](https://github.com/mastra-ai/mastra/pull/30250))

- Updated dependencies
[[`175b4b5`](175b4b5194),
[`5266060`](5266060ccd),
[`175b4b5`](175b4b5194),
[`9abbec6`](9abbec671c)]:
  - @mastra/core@1.84.0-alpha.0
  - @mastra/code-sdk@1.19.1-alpha.0
## @mastra/core@1.84.0-alpha.0

### Minor Changes

- **Breaking (Knowledge alpha):** a `$param` in a Knowledge scope
pattern now matches exactly one segment, so scope values can no longer
contain a raw `:`. Before, the last param took the rest of the address,
so `org:acme:viewer` counted as an `org:$orgId` scope and its holder got
that pattern's `self` rights there.
([#30019](https://github.com/mastra-ai/mastra/pull/30019))

- Agent `scopes` are canonical addresses. An id containing `:`, `/`, `#`
or `%` must be encoded with the new `encodeKnowledgeScopeId`. The raw
form (e.g. `org🅰️b` against `org:$orgId`) fails with "does not match a
declared scope type", and `%` is always read as an escape, so each scope
has one spelling.
- Memory ids are bound encoded: resource `slack:U123` becomes
`resource:slack%3AU123`.
- Patterns of one type with different segment counts no longer overlap,
so `org:$orgId` and `org:$orgId:viewer` can be declared side by side.
- `decodeKnowledgeScopeId` reads an id back from one segment of an
address.

  ```ts
  import { encodeKnowledgeScopeId } from '@mastra/core/knowledge';

const scope = `org:${encodeKnowledgeScopeId('auth0|a:b')}`; //
'org:auth0|a%3Ab', pass this in Agent scopes
  ```

  No data is rewritten:

- **Ids with a colon in the last segment get new addresses.** Before,
the last segment kept a raw `:` (`resource:slack:U123`); now it is
encoded (`resource:slack%3AU123`), so a run reaches a new, empty scope,
and pages, pins and notes stored under the old address stay there
unreached. Nothing moves them.
- **Every other id keeps its address if you pass it through
`encodeKnowledgeScopeId`.** `/`, `#` and `%` were already encoded the
same way, so `org:${encodeKnowledgeScopeId('a/b')}` reaches rows stored
from the raw `org:a/b`. Passing the old raw string unchanged does not:
`org:a/b` is refused, and a raw scope that happened to contain an escape
(`org:a%3Ab`, once stored as `org:a%253Ab`) now means the id `a:b`.
- **Stale rows get nothing from their new match.** A stored scope row
whose address now matches a different declaration than the one it was
created under (e.g. `org:acme:viewer` created under `org:$orgId`, once
`org:$orgId:viewer` is declared) gets none of the new declaration's
access. It is never a `belongsTo` parent, and using it as a scope of the
new declaration fails with an error. Prefix grants of the declaration it
was created under still let their holders read it, as before, without a
role on it.

### Patch Changes

- Fixed web search on models served through the Mastra gateway. An agent
using `webSearchTool` with a model such as `mastra/openai/gpt-6.1-sol`
failed every turn with `unknown tool type "openai:web_search"`, and on
Anthropic and Google models the tool was dropped without an error. These
models now use the gateway's web search.
([#30239](https://github.com/mastra-ai/mastra/pull/30239))

Other provider-native tools on gateway models now fail with a clear
error. Previously the gateway rejected them with a 400 or ignored them,
leaving the model without the tool.

- Fixed a run waiting on a tool approval losing its saved state when the
thread lease expired. This happened when the lease backend (such as
Redis) was down for too long. Before, the run's snapshot was deleted, so
the approval could not be resumed. Now the run resumes normally once the
backend is back. If another run took the thread first, a resume in the
same process is refused and the run keeps waiting.
([#27734](https://github.com/mastra-ai/mastra/pull/27734))
## @mastra/client-js@1.60.1-alpha.0

### Patch Changes

- Updated dependencies
[[`175b4b5`](175b4b5194),
[`5266060`](5266060ccd),
[`9abbec6`](9abbec671c)]:
  - @mastra/core@1.84.0-alpha.0
## @mastra/react@1.15.1-alpha.0

### Patch Changes

- Updated dependencies
[[`175b4b5`](175b4b5194),
[`5266060`](5266060ccd),
[`9abbec6`](9abbec671c)]:
  - @mastra/core@1.84.0-alpha.0
  - @mastra/client-js@1.60.1-alpha.0
## @mastra/deployer-cloud@1.84.0-alpha.0

### Patch Changes

- Updated dependencies
[[`175b4b5`](175b4b5194),
[`5266060`](5266060ccd),
[`9abbec6`](9abbec671c)]:
  - @mastra/core@1.84.0-alpha.0
  - @mastra/deployer@1.84.0-alpha.0
## @mastra/deployer-cloudflare@1.2.43-alpha.0

### Patch Changes

- Updated dependencies
[[`175b4b5`](175b4b5194),
[`5266060`](5266060ccd),
[`9abbec6`](9abbec671c)]:
  - @mastra/core@1.84.0-alpha.0
  - @mastra/deployer@1.84.0-alpha.0
## @mastra/deployer-netlify@1.2.43-alpha.0

### Patch Changes

- Updated dependencies
[[`175b4b5`](175b4b5194),
[`5266060`](5266060ccd),
[`9abbec6`](9abbec671c)]:
  - @mastra/core@1.84.0-alpha.0
  - @mastra/deployer@1.84.0-alpha.0
## @mastra/deployer-sandbox@0.3.28-alpha.0

### Patch Changes

- Updated dependencies
[[`175b4b5`](175b4b5194),
[`5266060`](5266060ccd),
[`9abbec6`](9abbec671c)]:
  - @mastra/core@1.84.0-alpha.0
  - @mastra/deployer@1.84.0-alpha.0
## @mastra/deployer-vercel@1.2.43-alpha.0

### Patch Changes

- Updated dependencies
[[`175b4b5`](175b4b5194),
[`5266060`](5266060ccd),
[`9abbec6`](9abbec671c)]:
  - @mastra/core@1.84.0-alpha.0
  - @mastra/deployer@1.84.0-alpha.0
## @mastra/longmemeval@1.1.43-alpha.0

### Patch Changes

- Updated dependencies
[[`175b4b5`](175b4b5194),
[`5266060`](5266060ccd),
[`9abbec6`](9abbec671c)]:
  - @mastra/core@1.84.0-alpha.0
## @mastra/opencode@0.1.43-alpha.0

### Patch Changes

- Updated dependencies
[[`175b4b5`](175b4b5194),
[`5266060`](5266060ccd),
[`9abbec6`](9abbec671c)]:
  - @mastra/core@1.84.0-alpha.0
## create-factory@0.4.4-alpha.0

### Patch Changes

- `create-factory` no longer asks where your Factory project should run.
New projects are created in the US region by default. To create the
project in the EU instead, pass `--region eu`:
([#30249](https://github.com/mastra-ai/mastra/pull/30249))

  ```bash
  npx create-factory@latest my-mastra-factory --region eu
  ```

- Updated dependencies
[[`4a3920c`](4a3920c7bf),
[`f75eb1a`](f75eb1a197),
[`338ec03`](338ec03925),
[`28e243f`](28e243f638)]:
  - mastra@1.39.1-alpha.0
## @mastra/code-sdk@1.19.1-alpha.0

### Patch Changes

- Mastra Code's Knowledge scopes now use canonical addresses, matching
`@mastra/core`'s one-segment scope values. Factory sessions hold their
org and project ids encoded (`org:acme%3Aeu` for org `acme:eu`), and the
`/knowledge` inspector and Factory Knowledge routes read the same
addresses the code agent writes, instead of encoding host scopes a
second time. ([#30019](https://github.com/mastra-ai/mastra/pull/30019))

- Updated dependencies
[[`be818ec`](be818ecb53),
[`175b4b5`](175b4b5194),
[`5266060`](5266060ccd),
[`9abbec6`](9abbec671c)]:
  - @mastra/github-signals@0.5.3-alpha.0
  - @mastra/core@1.84.0-alpha.0
  - @mastra/client-js@1.60.1-alpha.0
## mastracode@0.50.1-alpha.0

### Patch Changes

- Updated dependencies
[[`be818ec`](be818ecb53),
[`175b4b5`](175b4b5194),
[`5266060`](5266060ccd),
[`175b4b5`](175b4b5194),
[`9abbec6`](9abbec671c)]:
  - @mastra/github-signals@0.5.3-alpha.0
  - @mastra/core@1.84.0-alpha.0
  - @mastra/code-sdk@1.19.1-alpha.0
## mastra@1.39.1-alpha.0

### Patch Changes

- Added `factory intake-route reroute-preview` and `factory intake-route
reroute` to `mastra api`, for listing and moving untouched cards whose
intake route now points at a different board.
([#30252](https://github.com/mastra-ai/mastra/pull/30252))

  ```sh
  mastra api factory intake-route reroute-preview <factoryProjectId>
  mastra api factory intake-route reroute <factoryProjectId>
  ```

- Improved the Factory board on large projects. The board now loads the
first cards of each phase, then more as you scroll. It no longer
downloads every card of the project.
([#30191](https://github.com/mastra-ai/mastra/pull/30191))

Search, filters and sorting now run on the server. Search matches cards
that contain every word typed, in any order. It also finds a card by its
number or source id.

- Fixed the checkmark on a finished Factory onboarding step sitting 12px
right of the step numbers below it.
([#30248](https://github.com/mastra-ai/mastra/pull/30248))

- Added `mastra api factory board phases` and `mastra api factory
work-item filter-options`, which read the first cards under each phase
of a Factory board and the labels and people it can be filtered by.
([#30177](https://github.com/mastra-ai/mastra/pull/30177))

  ```bash
mastra api factory board phases <project-id> work
'{"label":["bug"],"limit":10}'
  mastra api factory work-item filter-options <project-id>
  ```

- Updated dependencies
[[`175b4b5`](175b4b5194),
[`5266060`](5266060ccd),
[`9abbec6`](9abbec671c)]:
  - @mastra/core@1.84.0-alpha.0
  - @mastra/deployer@1.84.0-alpha.0
## @mastra/deployer@1.84.0-alpha.0

### Patch Changes

- Updated dependencies
[[`175b4b5`](175b4b5194),
[`5266060`](5266060ccd),
[`9abbec6`](9abbec671c)]:
  - @mastra/core@1.84.0-alpha.0
  - @mastra/server@1.84.0-alpha.0
## @mastra/mcp-docs-server@1.3.14-alpha.0

### Patch Changes

- Updated dependencies
[[`175b4b5`](175b4b5194),
[`5266060`](5266060ccd),
[`9abbec6`](9abbec671c)]:
  - @mastra/core@1.84.0-alpha.0
## @mastra/playground-ui@69.0.1-alpha.0

### Patch Changes

- Updated dependencies
[[`175b4b5`](175b4b5194),
[`5266060`](5266060ccd),
[`9abbec6`](9abbec671c)]:
  - @mastra/core@1.84.0-alpha.0
  - @mastra/client-js@1.60.1-alpha.0
  - @mastra/react@1.15.1-alpha.0
## @mastra/server@1.84.0-alpha.0

### Patch Changes

- Updated dependencies
[[`175b4b5`](175b4b5194),
[`5266060`](5266060ccd),
[`9abbec6`](9abbec671c)]:
  - @mastra/core@1.84.0-alpha.0
## @mastra/elysia@0.1.24-alpha.0

### Patch Changes

- Updated dependencies
[[`175b4b5`](175b4b5194),
[`5266060`](5266060ccd),
[`9abbec6`](9abbec671c)]:
  - @mastra/core@1.84.0-alpha.0
  - @mastra/server@1.84.0-alpha.0
## @mastra/express@1.5.28-alpha.0

### Patch Changes

- Updated dependencies
[[`175b4b5`](175b4b5194),
[`5266060`](5266060ccd),
[`9abbec6`](9abbec671c)]:
  - @mastra/core@1.84.0-alpha.0
  - @mastra/server@1.84.0-alpha.0
## @mastra/fastify@1.5.28-alpha.0

### Patch Changes

- Updated dependencies
[[`175b4b5`](175b4b5194),
[`5266060`](5266060ccd),
[`9abbec6`](9abbec671c)]:
  - @mastra/core@1.84.0-alpha.0
  - @mastra/server@1.84.0-alpha.0
## @mastra/hono@1.7.26-alpha.0

### Patch Changes

- Updated dependencies
[[`175b4b5`](175b4b5194),
[`5266060`](5266060ccd),
[`9abbec6`](9abbec671c)]:
  - @mastra/core@1.84.0-alpha.0
  - @mastra/server@1.84.0-alpha.0
## @mastra/koa@1.7.28-alpha.0

### Patch Changes

- Updated dependencies
[[`175b4b5`](175b4b5194),
[`5266060`](5266060ccd),
[`9abbec6`](9abbec671c)]:
  - @mastra/core@1.84.0-alpha.0
  - @mastra/server@1.84.0-alpha.0
## @mastra/nestjs@0.3.1-alpha.0

### Patch Changes

- Updated dependencies
[[`175b4b5`](175b4b5194),
[`5266060`](5266060ccd),
[`9abbec6`](9abbec671c)]:
  - @mastra/core@1.84.0-alpha.0
  - @mastra/server@1.84.0-alpha.0
## @mastra/next@0.2.42-alpha.0

### Patch Changes

- Updated dependencies
[[`175b4b5`](175b4b5194),
[`5266060`](5266060ccd),
[`9abbec6`](9abbec671c)]:
  - @mastra/core@1.84.0-alpha.0
  - @mastra/hono@1.7.26-alpha.0
  - @mastra/server@1.84.0-alpha.0
## @mastra/tanstack-start@0.2.42-alpha.0

### Patch Changes

- Updated dependencies
[[`175b4b5`](175b4b5194),
[`5266060`](5266060ccd),
[`9abbec6`](9abbec671c)]:
  - @mastra/core@1.84.0-alpha.0
  - @mastra/hono@1.7.26-alpha.0
  - @mastra/server@1.84.0-alpha.0
## @mastra/github-signals@0.5.3-alpha.0

### Patch Changes

- Fixed delivery of authorized review comments and inline findings even
when bot summaries change or check status is unknown. Limit comment
bursts to ten findings and a counted overflow notice per poll.
([#30246](https://github.com/mastra-ai/mastra/pull/30246))

- Updated dependencies
[[`175b4b5`](175b4b5194),
[`5266060`](5266060ccd),
[`9abbec6`](9abbec671c)]:
  - @mastra/core@1.84.0-alpha.0
## @mastra/temporal@0.6.1-alpha.0

### Patch Changes

- Updated dependencies
[[`175b4b5`](175b4b5194),
[`5266060`](5266060ccd),
[`9abbec6`](9abbec671c)]:
  - @mastra/core@1.84.0-alpha.0
  - @mastra/deployer@1.84.0-alpha.0
## create-mastra@1.39.1-alpha.0


## @internal/playground@1.39.1-alpha.0

### Patch Changes

- Updated dependencies
[[`175b4b5`](175b4b5194),
[`5266060`](5266060ccd),
[`9abbec6`](9abbec671c)]:
  - @mastra/core@1.84.0-alpha.0
  - @mastra/client-js@1.60.1-alpha.0
  - @mastra/react@1.15.1-alpha.0
  - @mastra/playground-ui@69.0.1-alpha.0

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-11-12 16:45:14 -08:00
dane-ai-mastra[bot]
d60ba71be0 chore: version - exit prerelease mode 2026-11-12 21:12:29 +00:00
dane-ai-mastra[bot]
5c87442ed7
chore: version packages (alpha) (#30203)
This PR was opened by the [Changesets
release](https://github.com/changesets/action) GitHub action. When
you're ready to do a release, you can merge this and publish to npm
yourself or [setup this action to publish
automatically](https://github.com/changesets/action#with-publishing). If
you're not ready to do a release yet, that's fine, whenever you add more
changesets to main, this PR will be updated.

⚠️⚠️⚠️⚠️⚠️⚠️

`main` is currently in **pre mode** so this branch has prereleases
rather than normal releases. If you want to exit prereleases, run
`changeset pre exit` on `main`.

⚠️⚠️⚠️⚠️⚠️⚠️

# Releases

> The changelog information of each package has been omitted from this
message, as the content exceeds the size limit.

## @mastra/auth-auth0@1.3.0-alpha.0


## @mastra/auth-clerk@1.4.0-alpha.0


## @mastra/auth-okta@0.3.0-alpha.0


## @mastra/auth-supabase@1.2.0-alpha.0


## @mastra/client-js@1.60.0-alpha.13


## @mastra/auth@1.2.0-alpha.0


## @mastra/core@1.83.0-alpha.13


## @mastra/playground-ui@69.0.0-alpha.15


## @mastra/rag@2.8.0-alpha.3


## @mastra/server@1.83.0-alpha.13


## @mastra/server-adapters-test-suite@0.3.0-alpha.5


## @mastra/auth-better-auth@1.1.11-alpha.2


## @mastra/auth-cloud@1.2.9-alpha.0


## @mastra/auth-neon@0.3.6-alpha.1


## @mastra/auth-workos@1.6.9-alpha.0


## @mastra/discord@1.3.4-alpha.0


## @mastra/react@1.15.0-alpha.13


## @mastra/deployer-cloud@1.83.0-alpha.13


## @mastra/deployer-cloudflare@1.2.42-alpha.3


## @mastra/deployer-netlify@1.2.42-alpha.1


## @mastra/deployer-sandbox@0.3.27-alpha.1


## @mastra/deployer-vercel@1.2.42-alpha.1


## @mastra/longmemeval@1.1.42-alpha.13


## @mastra/opencode@0.1.42-alpha.13


## @mastra/factory@0.28.0-alpha.15


## create-factory@0.4.3-alpha.15


## @mastra/code-sdk@1.19.0-alpha.15


## mastracode@0.50.0-alpha.14


## @mastra/agent-builder@1.2.1-alpha.5


## mastra@1.39.0-alpha.15


## @mastra/connect@1.4.0-alpha.6


## @mastra/deployer@1.83.0-alpha.13


## @mastra/editor@0.17.1-alpha.7


## @mastra/mcp@2.9.0-alpha.5


## @mastra/mcp-docs-server@1.3.13-alpha.17


## @mastra/memory@1.41.1-alpha.5


## @mastra/schema-compat@1.4.0-alpha.2


## @mastra/elysia@0.1.23-alpha.13


## @mastra/express@1.5.27-alpha.13


## @mastra/fastify@1.5.27-alpha.13


## @mastra/hono@1.7.25-alpha.13


## @mastra/koa@1.7.27-alpha.13


## @mastra/nestjs@0.3.0-alpha.13


## @mastra/next@0.2.41-alpha.13


## @mastra/tanstack-start@0.2.41-alpha.13


## @mastra/voice-google-gemini-live@0.14.19-alpha.2


## @mastra/voice-openai-realtime@0.14.9-alpha.3


## @mastra/voice-xai-realtime@0.2.18-alpha.2


## @mastra/inngest@1.11.2-alpha.9


## @mastra/temporal@0.6.0-alpha.13


## create-mastra@1.39.0-alpha.15


## @internal/playground@1.39.0-alpha.15

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-11-12 12:07:03 -08:00
Daniel Lew
18168d518c
feat(playground): show the built-in MCP server in Studio (#29932)
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-12 13:40:02 -05:00
Daniel Lew
4ba2bdef89
feat(server): memory, observability and agent builder MCP toolsets (#29931)
## Description

Adds four toolsets to the built-in MCP server at `/api/mcp`:

- `memory`: threads, messages, memory search, and Observational Memory.
`get_observations` can wait for pending Observational Memory work, for
example right after `call_agent`.
- `observability`: trace and span queries, logs, and trace trajectories.
- `observability_analytics`: `analyze_metrics`, `analyze_scores`, and
`analyze_feedback`, plus metric name and label lookups.
- `stored_agents`: list allowed models, and create, read, and update
stored agents.

With these, an MCP client such as Claude Code can create an agent, talk
to it, read what it remembered, and explain a slow trace.

### Behavior

- **On by default, shown only when supported.** Each toolset appears
only when the app has the matching capability (a memory-enabled agent,
an observability store that supports the queries, an editor for stored
agents). Apps that don't set `server.mcp.toolsets` get these tools on
upgrade, including write tools. Set `toolsets` to keep the previous set,
or `readOnly: true` to drop writes. The changeset says this.
- **Same checks as HTTP.** Every tool dispatches through its HTTP route,
so authentication, RBAC, FGA, thread ownership, and agent visibility
apply unchanged. No MCP caller gets more access than the same caller
over HTTP.
- **Observability isn't scoped per user.** Anyone with
`observability:read` sees all traces, as over HTTP. The docs show how to
leave those toolsets out.
- **Builder model policy.** When the agent builder restricts models,
`create_stored_agent` and `update_stored_agent` check the model the
agent runs (`provider` and `name`, in every conditional variant; other
keys on `model` are rejected), models named in `defaultOptions` such as
`structuredOutput.model`, enabled fallback models (`modelList`), memory
models, input and output processor models, and the defaults they fall
back to. Anything the policy can't check is rejected. The HTTP
stored-agent routes don't apply this check. Agents created or updated
over MCP are published immediately (`update_stored_agent` defaults
`autoPublish` to `true`).
- **Results fit MCP client limits.** `get_trace` returns light span
records with every span id, and `get_span` returns one span in full.
Long lists are cut to fit, with a note on how to get the rest, and a
single oversized item has its long values shortened (ids are never cut).
- **Errors.** Bad `analyze_*` and `list_metric_names` arguments return
400. A failed observability store lookup is retried on the next request
instead of hiding the observability tools until restart.

Stacked on #29930.

## Test plan

- `@mastra/server`: unit tests for the toolsets, capability detection,
result sizing, and schemas.
- Shared adapter suite (`builtin-mcp-toolsets-test-suite`) on Hono,
Express, Fastify, Koa, Elysia, and NestJS: memory ownership compared
with HTTP on the same request, read-only mode, analytics dispatch, and
argument errors. Hono also runs observability tests against in-memory,
LibSQL, and DuckDB stores.
- `@mastra/editor` integration tests for the builder model policy across
`model` (static and conditional), `defaultOptions`, fallback models,
memory, and processors. They need no provider API keys.
- Run end to end with two users over MCP and HTTP, and with Claude Code.

---------

Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-12 10:25:19 -08:00
Daniel Lew
27705673f2
feat(server): OAuth discovery and audience checks for the built-in MCP endpoint (#29930)
## Description

Lets MCP clients such as Claude Code sign in to the built-in `/api/mcp`
endpoint with OAuth instead of a pasted token. The endpoint tells
clients where to sign in (RFC 9728 protected-resource metadata) and can
reject tokens issued for a different API (audience check).

```ts
new Mastra({
  server: {
    auth: new MastraJwtAuth({
      jwksUri: 'https://auth.example.com/.well-known/jwks.json',
      issuer: 'https://auth.example.com/',
    }),
    mcp: { oauth: { resource: 'https://my-app.example.com/api/mcp' } },
  },
});
```

### Behavior changes

**OAuth discovery for `/api/mcp`** (`@mastra/server`, every server
adapter including NestJS)
- When `server.auth` is set and the built-in MCP server is on, a `401`
from `/api/mcp` carries `WWW-Authenticate: Bearer
resource_metadata="…"`. `error="invalid_token"` is added only when a
token was sent (RFC 6750 §3).
- Metadata is served publicly at
`/.well-known/oauth-protected-resource/api/mcp` and
`/.well-known/oauth-protected-resource`, with `Cache-Control: no-store`.
- The document lists `resource`, `authorization_servers`, optional
`scopes_supported`, and `bearer_methods_supported: ['header']`. Without
`oauth.resource`, `resource` is derived from the request origin.
- The challenge, metadata routes and audience check apply only to
`/api/mcp`. Other routes are unaffected.

**Audience check** (`server.mcp.oauth.resource`)
- When set, the token audience must include this exact value, or the
request gets 401.
- An invalid value (non-URL, or a non-loopback `http://` URL) turns
discovery off and logs an error, but the audience check still runs
against it. Requests fail closed until the value is fixed.
- A provider that can't check audience (no `verifyAudience`, for example
`SimpleAuth` API keys) is accepted by default. The server logs a startup
warning on adapters built on `MastraServer`, not on NestJS.
- `requireAudience: true` (opt-in, only valid together with `resource`)
rejects those requests on `/api/mcp` with 401 `invalid_token`. Inside
`CompositeAuth`, only requests accepted by such providers are rejected.
Without `resource`, nothing changes.

**Config and provider hooks** (`@mastra/core`)
- New `server.mcp.oauth` config: `resource`, `requireAudience`,
`authorizationServers`, `scopesSupported`.
- Two new optional auth-provider methods:
  - `getOAuthMetadata()` advertises the provider's authorization server.
  - `verifyAudience()` checks the token audience.
- `CompositeAuth` combines the authorization servers of its providers.
It checks the audience with the provider that accepted the token, and
rejects when that provider can't be determined. The new
`getAuthenticatedProvider(user)` returns that provider.

**Providers**
| Provider | Advertises its authorization server | Checks audience
against `oauth.resource` |
|---|---|---|
| `MastraJwtAuth` | Yes, its `issuer` | Yes |
| Auth0 | Yes, the tenant | Yes |
| Clerk | Yes, the Frontend API | No |
| Okta | Yes, the issuer | No: Okta already enforces its own `audience`
(`OKTA_AUDIENCE`) |
| Supabase | Yes, `<url>/auth/v1` (requires Supabase's OAuth 2.1 server)
| No |

`MastraJwtAuth` gains `jwksUri` and `issuer` options
(`JWT_AUTH_JWKS_URI`, `JWT_AUTH_ISSUER`), so it can verify tokens signed
by an identity provider. JWKS keys are restricted to their key type, so
HMAC tokens forged with the public key are rejected.

**JWT subject as user id** (`@mastra/auth`, Auth0, Clerk)
- When a token has no `id` claim, the user's `id` is now set to `sub`.
Existing `id` claims are kept.
- Standard OIDC access tokens only carry `sub`. Before this change, RBAC
never loaded roles for these users, so every protected route returned
`403 Missing required permission`.
- Unless `mapUserToResourceId` is set, this also scopes data for these
users:
- **Owned records** (stored agents, skills, workspaces and other owned
records): each user sees their own records plus public ones. Admin
permissions keep the full list.
- **Tool-provider connections:** per-author connections move from the
shared `default` owner to the user's `sub`. Existing connections need
reconnecting, or set `mapUserToResourceId: () => 'default'` to keep the
old shared behavior.
  - **Feedback:** recorded with `sub` as the user id.
- The changeset describes all of these effects.

**Test suite** (`@mastra/server-adapters-test-suite`)
- New `createBuiltinMCPOAuthTestSuite`.
- The package now has `@mastra/auth` and `jose` as peer dependencies.

Stacked on #29929.

## Test plan

- `packages/server`: `src/server/mcp/oauth.test.ts` and
`oauth-without-mcp.test.ts`. They cover metadata, the challenge format,
resource validation, failing closed on an invalid `resource`, and
discovery working without `@mastra/mcp` installed.
- `packages/auth` `jwt.test.ts`:
  - JWKS and issuer validation
  - string and array `aud`
- an algorithm-confusion token that is HS256-signed with the real RSA
public key PEM and must be rejected
  - `sub` used as `id`
- `packages/core` `composite-auth.test.ts`: per-provider audience
delegation, rejection when the authenticating provider is unknown, and
`getAuthenticatedProvider`.
- `auth/auth0`, `auth/clerk`, `auth/okta`, `auth/supabase` unit tests.
- `createBuiltinMCPOAuthTestSuite` on Hono, Express, Fastify, Koa and
Elysia, plus the NestJS equivalent. It checks:
  - the challenge, and fetching the advertised metadata URL
  - audience accept and reject, including for an invalid `resource`
  - `requireAudience`:
    - `SimpleAuth` + `resource`: 200 by default, 401 in strict mode
    - a JWT with a matching audience: 200 in strict mode
    - a mixed `CompositeAuth`: only the API key is rejected
  - RBAC with a token that carries only `sub`
- that a `sub`-only user can't list another user's private stored agent
- `tsc --noEmit` and `oxlint` on the touched packages, plus docs `pnpm
check` and Vale.
- Manual run end to end with Claude Code against a local identity
provider: discovery, client registration, PKCE login, and two users with
different roles.

---------

Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-12 10:10:31 -08:00
Daniel Lew
392c7b69d5
feat(server): built-in MCP endpoint for agents, workflows and tools (#29929)
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-12 12:56:28 -05:00
Daniel Lew
d05afc4a90
refactor(server): shared route authorization and in-process dispatchRoute across adapters (#29928)
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-12 12:30:28 -05:00
Daniel Lew
834b0d2828
fix(server): enforce stored-agent visibility on every route that resolves an agent (#29927)
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-12 12:30:07 -05:00
arctic-char
c0d3bfdc43
feat: pass the authenticated user to DynamicArgument callbacks (#28612)
Dynamic agent config callbacks now get the authenticated end user as an
optional `user` argument, so you can personalize an agent without
digging auth keys out of `requestContext` yourself. It works in any
`DynamicArgument` callback: instructions, model, tools, memory,
workspace, processors, scorers, and so on.

```ts
import { Agent } from '@mastra/core/agent';

const supportAgent = new Agent({
  id: 'support-agent',
  instructions: ({ user }) =>
    user ? `You are helping ${user.name ?? user.id}.` : 'You are a helpful assistant.',
  model: ({ user }) => (user?.role === 'admin' ? 'openai/gpt-5' : 'openai/gpt-5-mini'),
  tools: ({ user }) => (user ? { accountTool, ...(user.role === 'admin' ? { adminTool } : {}) } : {}),
  memory: ({ user }) => (user ? userMemory : undefined),
});
```

`user` always has the same `MastraUser` shape, no matter which auth
provider you use, and it's `undefined` for unauthenticated requests:

```ts
import type { MastraUser } from '@mastra/core/types';

// { id: string; name?: string; email?: string; avatarUrl?: string; role?: string }
```

The server auth middleware builds it through a new overridable
`toMastraUser()` on `MastraAuthProvider`. The default handles common
shapes (`id`/`sub`/`userId`, `name`, `email`, `avatarUrl`/`picture`,
`role`), and JWT, Cloud, Supabase, Neon and Better Auth ship overrides
for their user objects. Custom providers can map their own shape:

```ts
import { MastraAuthProvider } from '@mastra/core/server';
import type { MastraUser } from '@mastra/core/types';

class MyAuth extends MastraAuthProvider<MyUser> {
  async authenticateToken(token: string) { /* ... */ }
  async authorizeUser(user: MyUser) { return true; }

  toMastraUser(user: MyUser): MastraUser {
    return { id: user.accountId, name: user.profile.displayName, role: user.permissions.primaryRole };
  }
}
```

Inline auth configs can pass `toMastraUser` too. If the provider user
has no role and an RBAC provider is configured, the primary RBAC role
fills it in, so `user.role` also works with WorkOS, Okta, Google and
Neon. The raw provider user is still available when you need
provider-specific fields, and the new context key is reserved, so
clients can't spoof it through the request body:

```ts
instructions: ({ requestContext }) => {
  const rawUser = requestContext.get('mastra__user'); // provider-specific object, unchanged
  // ...
},
```

Dynamic `vectorStore` resolvers on RAG tools get `user` as well:

```ts
createVectorQueryTool({
  indexName: 'docs',
  model: embedder,
  vectorStore: ({ user }) => (user ? tenantStores.get(user.id)! : sharedStore),
});
```

Inside core, every place that invoked a `DynamicArgument` callback
inline now goes through a single `resolveDynamicArgument` helper, which
reads the user from `requestContext` at call time. This is non-breaking:
callbacks get an extra optional field, providers get a method with a
working default. Requests served through an `MCPServer` don't get `user`
yet, since MCP builds its own request context; that's documented.

Tested with unit tests for the helper, normalization and each provider
override, middleware tests (inline config, provider role, RBAC role,
CompositeAuth ordering, unauthenticated), regression tests for the
migrated call sites, and an end-to-end test where an agent behind a fake
auth provider gets personalized instructions. Core, server, rag and the
touched auth packages typecheck clean, and their suites pass.



<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## ELI5
When a signed-in user makes a request, configuration callbacks can now
use a standard set of details about that user. When a workflow resumes,
it uses the new request’s user details instead of restoring them from
the earlier run.

## Summary
- Added optional `user` data to `DynamicArgument` callbacks and RAG
vector-store resolvers. Callbacks can also use `getRequestUser()` to
read the normalized user from request context.
- Added the `MastraUser` type and `toMastraUser()` normalization hooks
for auth providers and inline auth configs. The server stores the
normalized user in a reserved request-context key and uses the primary
RBAC role when the user has no role.
- Updated core dynamic configuration paths to use the shared resolver.
Added user support to agent scopes and migrated A2A memory resolution.
- Added `withoutLiveRequestKeys()` to remove live authentication and
authorization data from saved context during workflow resume, restart,
and time travel. Saved non-authentication context, such as tenant data,
remains available.
- Added documentation and changesets. Raised relevant `@mastra/core`
peer dependency minimums to 1.81.0. MCPServer requests do not receive
the normalized `user`.

## Validation
The author reports passing typechecks and test suites across core,
server, RAG, and several auth packages. The author also reports three
failing Inngest tests and earlier failures in evented workflow and
scheduler tests, which reportedly fail the same way on comparison
sources. These results are author-reported and have not been
independently verified.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-12 10:55:12 -05:00
mastra-platform[bot]
e1a20364af
Fix OpenAPI request schemas for defaulted and transformed fields (#30187)
## Summary
- Generate request path, query, and body JSON Schemas from input types
while retaining output types for responses.
- Pass input/output mode through the Zod v4 adapter to represent
defaults and transformations accurately.
- Add regressions for OpenAPI documents, API schema manifests, and Zod
v4 conversion, plus patch changesets for both packages.

## Test plan
- `pnpm exec vitest run` in `packages/schema-compat` (1089 passed, 9
skipped)
- `pnpm exec vitest run` in `packages/server` (3406 passed, 3 skipped, 1
todo)
- `pnpm exec tsc --noEmit -p tsconfig.json` in both packages
- `pnpm exec oxlint --type-aware` on modified files; `pnpm exec prettier
--check` on modified files

Fixes #30050

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

**ELI5:** Mastra builds an API document that tells client programs what
data to send. Before this change, the document described the cleaned-up
data the server produces, not the data the client sends. This change
makes the document describe what clients send for requests, and keeps
the cleaned-up form for responses.

## Summary

This pull request changes how OpenAPI documents describe request and
response schemas for Zod schemas. It addresses issue `#30050`.

### Problem

The OpenAPI conversion used the Zod output side for all schemas. Request
data needs the input side. This caused two errors:

- Fields with `.default()` appeared as required in request bodies.
- Parameters with `.transform()` appeared as `{}` in path and query
schemas.

On Zod versions before 4.2, and through the 3.25 v4 compatibility layer,
the `@mastra/schema-compat` Zod v4 adapter also dropped the input/output
mode.

### Changes

- **`packages/server/src/server/server-adapter/openapi-utils.ts`:**
`schemaToJsonSchema` accepts an optional `io` argument (`'input' |
'output'`, default `'output'`) and passes it to
`standardSchemaToJSONSchema`. Path parameters, query parameters, and
request bodies use `'input'`. Response schemas keep the default
`'output'`.
-
**`packages/server/src/server/server-adapter/api-schema-manifest.ts`:**
`convertSchema` accepts a direction and passes it to
`schemaToJsonSchema`. The manifest builder converts response schemas as
output. It converts path, query, and body schemas as input.
- **`packages/schema-compat/src/standard-schema/adapters/zod-v4.ts`:**
`convertToJsonSchema` accepts a direction and passes it to Zod's
`toJSONSchema` options. The `input` converter uses `'input'`. The
`output` converter uses `'output'`.
- **Generated CLI schemas:**
`packages/cli/src/commands/api/feedback-score-schemas.generated.ts` and
`route-metadata.generated.ts` are regenerated to match the OpenAPI
request-schema change.
- **Changeset:** Adds patch releases for `@mastra/schema-compat` and
`@mastra/server`.

### Tests

- `openapi-utils.test.ts`: Adds a test for a `createRoute` POST route.
It checks that transformed path and query inputs use string schemas,
that the defaulted query parameter is optional, and that only
non-defaulted body and response fields are required.
- `api-schema-manifest.test.ts`: Adds a test that checks property
schemas and required fields for path, query, body, and response schemas
with defaults and transforms.
- `zod-v4.test.ts`: Changes the input/output comparison. It now checks
that properties and required fields match for a schema without defaults
or transforms. It adds a test for a defaulted, transformed field through
the routed adapter.

### Scope

- 9 files changed, 155 lines added, 62 lines removed (from `git diff
--stat` against the merge base).
- Two of the nine files are generated CLI schema files.
- No exported declarations changed except the `schemaToJsonSchema`
signature, which gained an optional parameter.

### Verification

The PR objectives report these local checks by the author:
`schema-compat` and `server` Vitest runs, `tsc --noEmit` in both
packages, and `oxlint` and `prettier --check` on modified files. These
results come from the PR description. CI results on the current head are
not available.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-12 06:33:48 -08:00
dane-ai-mastra[bot]
05a6931471
chore: version packages (alpha) (#30172)
This PR was opened by the [Changesets
release](https://github.com/changesets/action) GitHub action. When
you're ready to do a release, you can merge this and publish to npm
yourself or [setup this action to publish
automatically](https://github.com/changesets/action#with-publishing). If
you're not ready to do a release yet, that's fine, whenever you add more
changesets to main, this PR will be updated.

⚠️⚠️⚠️⚠️⚠️⚠️

`main` is currently in **pre mode** so this branch has prereleases
rather than normal releases. If you want to exit prereleases, run
`changeset pre exit` on `main`.

⚠️⚠️⚠️⚠️⚠️⚠️

# Releases
## @mastra/client-js@1.60.0-alpha.12

### Minor Changes

- Allow `querySpans()` to sort by `model` or `provider`.
([#30096](https://github.com/mastra-ai/mastra/pull/30096))

  ```ts
  orderBy: [{ field: 'model', direction: 'asc' }];
  ```

### Patch Changes

- The generated route types for scores now include the `SCORER` and
`PROCESSOR` entity types, matching the entity types experiments can
emit. ([#30145](https://github.com/mastra-ai/mastra/pull/30145))

- Add span-local error counts.
([#30088](https://github.com/mastra-ai/mastra/pull/30088))

- Updated dependencies
[[`56f654f`](56f654fc0d),
[`f071044`](f0710446e0),
[`72abae6`](72abae68eb),
[`987566e`](987566e882)]:
  - @mastra/core@1.83.0-alpha.12
## @mastra/factory@0.28.0-alpha.14

### Minor Changes

- A card's sandbox now stops as soon as the card is done with that
context, instead of idling until the provider times it out.
([#29981](https://github.com/mastra-ai/mastra/pull/29981))

- When a card moves out of the last phase of a context into a phase that
runs in another one, Factory stops that context's sandbox. Triage →
Planning stops the triage sandbox; Planning → Building keeps the shared
`work` sandbox running. A run still in flight on the session keeps its
sandbox until it ends.
- When a card finishes, Factory stops every sandbox it holds, from any
Factory process, by identity through the configured sandbox provider.
Before, only the process that had opened a sandbox stopped it.
- A card that comes back to a context resumes the same sandbox with its
files.

Stopping never fails the move. Sandboxes are stopped, not destroyed;
deleting a session still destroys its sandbox.

- Added two read routes that answer what the new session page shows
without sending a project's cards.
([#30097](https://github.com/mastra-ai/mastra/pull/30097))

`GET /web/factory/projects/:id/work-items/starters` counts the cards
behind each starter on the project's default board, such as the cards
whose run failed, the pull requests awaiting review and the cards not
yet triaged.

`GET /web/factory/projects/:id/work-items/activity?since=<instant>`
returns how many cards the project has, and when cards were created and
completed since that instant. `since` is required and must be an ISO
date-time such as `2026-06-01T00:00:00.000Z`. The answer carries an
`ETag`, so asking again for the same `since` with `If-None-Match`
returns a 304 with no body when nothing changed.

### Patch Changes

- Fixed environment templates that could stop rebuilding for good. When
a build start was never recorded and the sandbox provider can't list its
builds (Mastra Platform), every later Build now, schedule and push run
used to skip with `unresolved` forever. Factory now treats that start as
failed 30 minutes after its lease lapsed and the next trigger builds.
([#30148](https://github.com/mastra-ai/mastra/pull/30148))

Saving a change to a template input (setup commands, the working
directory, settings, environment repositories, source-control
connections or Build variables) now rebuilds the template once the
project has one, so new sandboxes stop rerunning setup on every boot.
Saves that change nothing don't build, and a change saved during any
build, scheduled ones included, is built when that build ends.

- Factory sessions and MCP clients can now read the Factory's audit
trail with `factory_list_audit_events`: who did what to which work item,
run, branch or setting, and when. Filter by actor (`me`, a user id, or
an agent, optionally with the agent runs a person started), namespace or
exact actions, work item and time range, and page back with a cursor.
The tool only returns this Factory's events and never returns request
context (IP address, user agent), actor emails or event metadata beyond
who started an agent run. It leaves out events from or about other
people's private sessions.
([#30165](https://github.com/mastra-ai/mastra/pull/30165))

- Added a "Join the issue's card instead" switch to intake routes in the
Factory UI. A route for pull requests that close an issue can now put
the pull request on that issue's card instead of giving it a card of its
own; until now only the route Factory seeds could do this. The switch
shows on new and saved routes whose conditions include "Source kind is
Pull request" and "Pull request closes an issue is Yes".
([#30197](https://github.com/mastra-ai/mastra/pull/30197))

- Updated dependencies
[[`56f654f`](56f654fc0d),
[`f071044`](f0710446e0),
[`72abae6`](72abae68eb),
[`987566e`](987566e882)]:
  - @mastra/core@1.83.0-alpha.12
  - @mastra/code-sdk@1.19.0-alpha.14
  - @mastra/mcp@2.9.0-alpha.4
## @mastra/observability@1.24.0-alpha.7

### Minor Changes

- Add span-local error counts.
([#30088](https://github.com/mastra-ai/mastra/pull/30088))

### Patch Changes

- Updated dependencies
[[`56f654f`](56f654fc0d),
[`f071044`](f0710446e0),
[`72abae6`](72abae68eb),
[`987566e`](987566e882)]:
  - @mastra/core@1.83.0-alpha.12
## @mastra/core@1.83.0-alpha.12

### Minor Changes

- Add model and provider as span query sort fields.
([#30096](https://github.com/mastra-ai/mastra/pull/30096))

  ```ts
  orderBy: [{ field: 'model', direction: 'asc' }];
  ```

- Add span-local error counts.
([#30088](https://github.com/mastra-ai/mastra/pull/30088))

### Patch Changes

- Name the agent in the missing-storage error thrown by `Memory`. When
an agent's memory never received storage because the agent was never
attached to a Mastra instance, accessing `memory.storage` now fails with
`[Agent:<name>] Memory requires a storage provider to function. ...`, so
it is clear which agent is misconfigured. The registration and
standalone-storage guidance added in #29972 is unchanged, and agents
that inherit storage from their Mastra or configure it directly on
`Memory` are unaffected.
([#30164](https://github.com/mastra-ai/mastra/pull/30164))

- Experiments with a scorer or processor target now save their scores,
and workflow step scorers in experiments now save their step scores.
Previously these scores were silently discarded.
([#30145](https://github.com/mastra-ai/mastra/pull/30145))
## @mastra/mcp-apps-components@0.1.0-alpha.7

### Minor Changes

- Dashboards authored in chat now accept the same widgets as the
dashboard editor: KPIs that combine values (ratio, difference, max,
fallback), read trace, span or score aggregates (for example p95 span
duration) and use duration, percent or score formats; line charts of
scores; six more chart colors (blue, orange, pink, yellow, red, purple);
and optional KPI icon and detail, series color and table empty message.
([#30192](https://github.com/mastra-ai/mastra/pull/30192))

### Patch Changes

- Updated dependencies
[[`56f654f`](56f654fc0d),
[`f071044`](f0710446e0),
[`72abae6`](72abae68eb),
[`987566e`](987566e882)]:
  - @mastra/core@1.83.0-alpha.12
## @mastra/playground-ui@69.0.0-alpha.14

### Minor Changes

- Widened what dashboard widgets can show:
([#30192](https://github.com/mastra-ai/mastra/pull/30192))

- KPIs can combine values with `ratio`, `minus`, `max` and `coalesce`,
read trace and span aggregates (for example `duration.p95`) and score
aggregates, and are formatted as `duration`, `percent` or `score`.
Combined values are compared with the previous window.
- Charts accept six more colors: `blue`, `orange`, `pink`, `yellow`,
`red` and `purple`.
- KPI `icon` and `detail`, series `color` and table `emptyMessage` are
optional. Series without a color pick one from a palette, and tables
without an empty message show "No data".

### Patch Changes

- Fixed hover highlights on cards and other surfaces stopping short of
the edge. The highlight now covers the whole surface and follows its
rounded corners exactly, including the sidebar credits card and
clickable cards. Hover highlights on these surfaces now switch instantly
instead of fading.
([#30047](https://github.com/mastra-ai/mastra/pull/30047))

- Updated dependencies
[[`56f654f`](56f654fc0d),
[`f071044`](f0710446e0),
[`987566e`](987566e882),
[`72abae6`](72abae68eb),
[`987566e`](987566e882),
[`f071044`](f0710446e0)]:
  - @mastra/core@1.83.0-alpha.12
  - @mastra/client-js@1.60.0-alpha.12
  - @mastra/react@1.15.0-alpha.12
## @mastra/server@1.83.0-alpha.12

### Minor Changes

- Support model and provider sorting in span queries.
([#30096](https://github.com/mastra-ai/mastra/pull/30096))

### Patch Changes

- Updated dependencies
[[`56f654f`](56f654fc0d),
[`f071044`](f0710446e0),
[`72abae6`](72abae68eb),
[`987566e`](987566e882)]:
  - @mastra/core@1.83.0-alpha.12
## @mastra/clickhouse@1.30.0-alpha.4

### Minor Changes

- Sort span queries by model or provider in ascending or descending
order. ([#30096](https://github.com/mastra-ai/mastra/pull/30096))

### Patch Changes

- Updated dependencies
[[`56f654f`](56f654fc0d),
[`f071044`](f0710446e0),
[`72abae6`](72abae68eb),
[`987566e`](987566e882)]:
  - @mastra/core@1.83.0-alpha.12
## @mastra/duckdb@1.19.0-alpha.5

### Minor Changes

- Sort span queries by model or provider in ascending or descending
order. ([#30096](https://github.com/mastra-ai/mastra/pull/30096))

### Patch Changes

- Updated dependencies
[[`56f654f`](56f654fc0d),
[`f071044`](f0710446e0),
[`72abae6`](72abae68eb),
[`987566e`](987566e882)]:
  - @mastra/core@1.83.0-alpha.12
## @mastra/pg@1.36.0-alpha.6

### Minor Changes

- Sort span queries by model or provider in ascending or descending
order. ([#30096](https://github.com/mastra-ai/mastra/pull/30096))

### Patch Changes

- Updated dependencies
[[`56f654f`](56f654fc0d),
[`f071044`](f0710446e0),
[`72abae6`](72abae68eb),
[`987566e`](987566e882)]:
  - @mastra/core@1.83.0-alpha.12
## @mastra/react@1.15.0-alpha.12

### Patch Changes

- Updated dependencies
[[`56f654f`](56f654fc0d),
[`f071044`](f0710446e0),
[`987566e`](987566e882),
[`72abae6`](72abae68eb),
[`987566e`](987566e882),
[`f071044`](f0710446e0)]:
  - @mastra/core@1.83.0-alpha.12
  - @mastra/client-js@1.60.0-alpha.12
## @mastra/deployer-cloud@1.83.0-alpha.12

### Patch Changes

- Updated dependencies
[[`56f654f`](56f654fc0d),
[`f071044`](f0710446e0),
[`72abae6`](72abae68eb),
[`987566e`](987566e882)]:
  - @mastra/core@1.83.0-alpha.12
  - @mastra/deployer@1.83.0-alpha.12
## @mastra/longmemeval@1.1.42-alpha.12

### Patch Changes

- Updated dependencies
[[`56f654f`](56f654fc0d),
[`f071044`](f0710446e0),
[`72abae6`](72abae68eb),
[`987566e`](987566e882)]:
  - @mastra/core@1.83.0-alpha.12
  - @mastra/libsql@1.30.0-alpha.3
## @mastra/opencode@0.1.42-alpha.12

### Patch Changes

- Updated dependencies
[[`56f654f`](56f654fc0d),
[`f071044`](f0710446e0),
[`72abae6`](72abae68eb),
[`987566e`](987566e882)]:
  - @mastra/core@1.83.0-alpha.12
  - @mastra/libsql@1.30.0-alpha.3
## create-factory@0.4.3-alpha.14

### Patch Changes

- Updated dependencies
[[`1fbc69a`](1fbc69aa9a),
[`4e378c3`](4e378c3e26),
[`1fbc69a`](1fbc69aa9a)]:
  - mastra@1.39.0-alpha.14
## @mastra/code-sdk@1.19.0-alpha.14

### Patch Changes

- Updated dependencies
[[`56f654f`](56f654fc0d),
[`72abae6`](72abae68eb),
[`f071044`](f0710446e0),
[`f071044`](f0710446e0),
[`987566e`](987566e882),
[`72abae6`](72abae68eb),
[`987566e`](987566e882),
[`f071044`](f0710446e0),
[`f071044`](f0710446e0)]:
  - @mastra/core@1.83.0-alpha.12
  - @mastra/observability@1.24.0-alpha.7
  - @mastra/duckdb@1.19.0-alpha.5
  - @mastra/client-js@1.60.0-alpha.12
  - @mastra/pg@1.36.0-alpha.6
  - @mastra/mcp@2.9.0-alpha.4
  - @mastra/libsql@1.30.0-alpha.3
## mastracode@0.50.0-alpha.13

### Patch Changes

- Fix `/settings` crashing when mouse preferences are missing from saved
settings by defaulting to Off.
([#30184](https://github.com/mastra-ai/mastra/pull/30184))

- Updated dependencies
[[`56f654f`](56f654fc0d),
[`72abae6`](72abae68eb),
[`f071044`](f0710446e0),
[`f071044`](f0710446e0),
[`72abae6`](72abae68eb),
[`987566e`](987566e882),
[`f071044`](f0710446e0)]:
  - @mastra/core@1.83.0-alpha.12
  - @mastra/observability@1.24.0-alpha.7
  - @mastra/duckdb@1.19.0-alpha.5
  - @mastra/pg@1.36.0-alpha.6
  - @mastra/code-sdk@1.19.0-alpha.14
  - @mastra/mcp@2.9.0-alpha.4
  - @mastra/libsql@1.30.0-alpha.3
## @mastra/arize@1.3.30-alpha.7

### Patch Changes

- Updated dependencies
[[`56f654f`](56f654fc0d),
[`f071044`](f0710446e0),
[`72abae6`](72abae68eb),
[`987566e`](987566e882)]:
  - @mastra/core@1.83.0-alpha.12
  - @mastra/otel-exporter@1.5.2-alpha.7
## @mastra/arthur@0.4.30-alpha.7

### Patch Changes

- Updated dependencies
[[`56f654f`](56f654fc0d),
[`f071044`](f0710446e0),
[`72abae6`](72abae68eb),
[`987566e`](987566e882)]:
  - @mastra/core@1.83.0-alpha.12
  - @mastra/otel-exporter@1.5.2-alpha.7
## @mastra/braintrust@1.3.27-alpha.7

### Patch Changes

- Updated dependencies
[[`56f654f`](56f654fc0d),
[`72abae6`](72abae68eb),
[`f071044`](f0710446e0),
[`72abae6`](72abae68eb),
[`987566e`](987566e882)]:
  - @mastra/core@1.83.0-alpha.12
  - @mastra/observability@1.24.0-alpha.7
## @mastra/datadog@1.4.22-alpha.7

### Patch Changes

- Updated dependencies
[[`56f654f`](56f654fc0d),
[`72abae6`](72abae68eb),
[`f071044`](f0710446e0),
[`72abae6`](72abae68eb),
[`987566e`](987566e882)]:
  - @mastra/core@1.83.0-alpha.12
  - @mastra/observability@1.24.0-alpha.7
## @mastra/deepeval@0.1.24-alpha.7

### Patch Changes

- Updated dependencies
[[`56f654f`](56f654fc0d),
[`72abae6`](72abae68eb),
[`f071044`](f0710446e0),
[`72abae6`](72abae68eb),
[`987566e`](987566e882)]:
  - @mastra/core@1.83.0-alpha.12
  - @mastra/observability@1.24.0-alpha.7
## @mastra/laminar@1.3.32-alpha.7

### Patch Changes

- Updated dependencies
[[`56f654f`](56f654fc0d),
[`72abae6`](72abae68eb),
[`f071044`](f0710446e0),
[`72abae6`](72abae68eb),
[`987566e`](987566e882)]:
  - @mastra/core@1.83.0-alpha.12
  - @mastra/observability@1.24.0-alpha.7
## @mastra/langfuse@1.6.6-alpha.7

### Patch Changes

- Updated dependencies
[[`56f654f`](56f654fc0d),
[`72abae6`](72abae68eb),
[`f071044`](f0710446e0),
[`72abae6`](72abae68eb),
[`987566e`](987566e882)]:
  - @mastra/core@1.83.0-alpha.12
  - @mastra/observability@1.24.0-alpha.7
  - @mastra/otel-exporter@1.5.2-alpha.7
## @mastra/langsmith@1.4.3-alpha.7

### Patch Changes

- Updated dependencies
[[`56f654f`](56f654fc0d),
[`72abae6`](72abae68eb),
[`f071044`](f0710446e0),
[`72abae6`](72abae68eb),
[`987566e`](987566e882)]:
  - @mastra/core@1.83.0-alpha.12
  - @mastra/observability@1.24.0-alpha.7
## @mastra/otel-bridge@1.5.22-alpha.7

### Patch Changes

- Updated dependencies
[[`56f654f`](56f654fc0d),
[`72abae6`](72abae68eb),
[`f071044`](f0710446e0),
[`72abae6`](72abae68eb),
[`987566e`](987566e882)]:
  - @mastra/core@1.83.0-alpha.12
  - @mastra/observability@1.24.0-alpha.7
  - @mastra/otel-exporter@1.5.2-alpha.7
## @mastra/otel-exporter@1.5.2-alpha.7

### Patch Changes

- Updated dependencies
[[`56f654f`](56f654fc0d),
[`72abae6`](72abae68eb),
[`f071044`](f0710446e0),
[`72abae6`](72abae68eb),
[`987566e`](987566e882)]:
  - @mastra/core@1.83.0-alpha.12
  - @mastra/observability@1.24.0-alpha.7
## @mastra/posthog@1.4.7-alpha.7

### Patch Changes

- Updated dependencies
[[`56f654f`](56f654fc0d),
[`72abae6`](72abae68eb),
[`f071044`](f0710446e0),
[`72abae6`](72abae68eb),
[`987566e`](987566e882)]:
  - @mastra/core@1.83.0-alpha.12
  - @mastra/observability@1.24.0-alpha.7
## @mastra/sentry@1.2.32-alpha.7

### Patch Changes

- Updated dependencies
[[`56f654f`](56f654fc0d),
[`72abae6`](72abae68eb),
[`f071044`](f0710446e0),
[`72abae6`](72abae68eb),
[`987566e`](987566e882)]:
  - @mastra/core@1.83.0-alpha.12
  - @mastra/observability@1.24.0-alpha.7
  - @mastra/otel-exporter@1.5.2-alpha.7
## mastra@1.39.0-alpha.14

### Patch Changes

- Added `mastra api factory work-item starters` and `mastra api factory
work-item activity`. The first counts the cards behind each new-session
starter on a project's default board. The second lists when a project's
cards were created and completed since an instant:
([#30097](https://github.com/mastra-ai/mastra/pull/30097))

  ```bash
  mastra api factory work-item starters <project-id>
mastra api factory work-item activity <project-id>
'{"since":"2026-06-01T00:00:00.000Z"}'
  ```

- Added a "Join the issue's card instead" switch to intake routes in the
Factory UI. A route for pull requests that close an issue can now put
the pull request on that issue's card instead of giving it a card of its
own; until now only the route Factory seeds could do this. The switch
shows on new and saved routes whose conditions include "Source kind is
Pull request" and "Pull request closes an issue is Yes".
([#30197](https://github.com/mastra-ai/mastra/pull/30197))

- Improved the Factory new session page on large boards. Its starters
and its activity band now load the counts and dates they show instead of
downloading every card of the project. They show the same content as
before. ([#30097](https://github.com/mastra-ai/mastra/pull/30097))

- Updated dependencies
[[`56f654f`](56f654fc0d),
[`f071044`](f0710446e0),
[`72abae6`](72abae68eb),
[`987566e`](987566e882)]:
  - @mastra/core@1.83.0-alpha.12
  - @mastra/deployer@1.83.0-alpha.12
## @mastra/deployer@1.83.0-alpha.12

### Patch Changes

- Updated dependencies
[[`56f654f`](56f654fc0d),
[`f071044`](f0710446e0),
[`f071044`](f0710446e0),
[`72abae6`](72abae68eb),
[`987566e`](987566e882)]:
  - @mastra/core@1.83.0-alpha.12
  - @mastra/server@1.83.0-alpha.12
## @mastra/mcp-docs-server@1.3.13-alpha.16

### Patch Changes

- Updated dependencies
[[`56f654f`](56f654fc0d),
[`f071044`](f0710446e0),
[`72abae6`](72abae68eb),
[`987566e`](987566e882)]:
  - @mastra/core@1.83.0-alpha.12
## @mastra/elysia@0.1.23-alpha.12

### Patch Changes

- Updated dependencies
[[`56f654f`](56f654fc0d),
[`f071044`](f0710446e0),
[`f071044`](f0710446e0),
[`72abae6`](72abae68eb),
[`987566e`](987566e882)]:
  - @mastra/core@1.83.0-alpha.12
  - @mastra/server@1.83.0-alpha.12
## @mastra/express@1.5.27-alpha.12

### Patch Changes

- Updated dependencies
[[`56f654f`](56f654fc0d),
[`f071044`](f0710446e0),
[`f071044`](f0710446e0),
[`72abae6`](72abae68eb),
[`987566e`](987566e882)]:
  - @mastra/core@1.83.0-alpha.12
  - @mastra/server@1.83.0-alpha.12
## @mastra/fastify@1.5.27-alpha.12

### Patch Changes

- Updated dependencies
[[`56f654f`](56f654fc0d),
[`f071044`](f0710446e0),
[`f071044`](f0710446e0),
[`72abae6`](72abae68eb),
[`987566e`](987566e882)]:
  - @mastra/core@1.83.0-alpha.12
  - @mastra/server@1.83.0-alpha.12
## @mastra/hono@1.7.25-alpha.12

### Patch Changes

- Updated dependencies
[[`56f654f`](56f654fc0d),
[`f071044`](f0710446e0),
[`f071044`](f0710446e0),
[`72abae6`](72abae68eb),
[`987566e`](987566e882)]:
  - @mastra/core@1.83.0-alpha.12
  - @mastra/server@1.83.0-alpha.12
## @mastra/koa@1.7.27-alpha.12

### Patch Changes

- Updated dependencies
[[`56f654f`](56f654fc0d),
[`f071044`](f0710446e0),
[`f071044`](f0710446e0),
[`72abae6`](72abae68eb),
[`987566e`](987566e882)]:
  - @mastra/core@1.83.0-alpha.12
  - @mastra/server@1.83.0-alpha.12
## @mastra/nestjs@0.3.0-alpha.12

### Patch Changes

- Updated dependencies
[[`56f654f`](56f654fc0d),
[`f071044`](f0710446e0),
[`f071044`](f0710446e0),
[`72abae6`](72abae68eb),
[`987566e`](987566e882)]:
  - @mastra/core@1.83.0-alpha.12
  - @mastra/server@1.83.0-alpha.12
## @mastra/next@0.2.41-alpha.12

### Patch Changes

- Updated dependencies
[[`56f654f`](56f654fc0d),
[`f071044`](f0710446e0),
[`f071044`](f0710446e0),
[`72abae6`](72abae68eb),
[`987566e`](987566e882)]:
  - @mastra/core@1.83.0-alpha.12
  - @mastra/server@1.83.0-alpha.12
  - @mastra/hono@1.7.25-alpha.12
## @mastra/tanstack-start@0.2.41-alpha.12

### Patch Changes

- Updated dependencies
[[`56f654f`](56f654fc0d),
[`f071044`](f0710446e0),
[`f071044`](f0710446e0),
[`72abae6`](72abae68eb),
[`987566e`](987566e882)]:
  - @mastra/core@1.83.0-alpha.12
  - @mastra/server@1.83.0-alpha.12
  - @mastra/hono@1.7.25-alpha.12
## @mastra/voice-openai-realtime@0.14.9-alpha.2

### Patch Changes

- Use gpt-realtime-2.1-mini by default for OpenAI Realtime voice
connections instead of the retired
gpt-4o-mini-realtime-preview-2024-12-17 model.
([#30183](https://github.com/mastra-ai/mastra/pull/30183))
## @mastra/inngest@1.11.2-alpha.8

### Patch Changes

- Support span-local error counts in Inngest workflows.
([#30088](https://github.com/mastra-ai/mastra/pull/30088))

- Updated dependencies
[[`56f654f`](56f654fc0d),
[`f071044`](f0710446e0),
[`72abae6`](72abae68eb),
[`987566e`](987566e882)]:
  - @mastra/core@1.83.0-alpha.12
## @mastra/temporal@0.6.0-alpha.12

### Patch Changes

- Updated dependencies
[[`56f654f`](56f654fc0d),
[`f071044`](f0710446e0),
[`72abae6`](72abae68eb),
[`987566e`](987566e882)]:
  - @mastra/core@1.83.0-alpha.12
  - @mastra/deployer@1.83.0-alpha.12
## create-mastra@1.39.0-alpha.14


## @internal/playground@1.39.0-alpha.14

### Patch Changes

- Updated dependencies
[[`56f654f`](56f654fc0d),
[`f071044`](f0710446e0),
[`987566e`](987566e882),
[`72abae6`](72abae68eb),
[`f9088d8`](f9088d8510),
[`987566e`](987566e882),
[`f071044`](f0710446e0),
[`43d1e9c`](43d1e9c16d)]:
  - @mastra/core@1.83.0-alpha.12
  - @mastra/client-js@1.60.0-alpha.12
  - @mastra/playground-ui@69.0.0-alpha.14
  - @mastra/react@1.15.0-alpha.12

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-11-12 14:42:02 +01:00
Eric Pinzur
f0710446e0
feat(observability): sort spans by model and provider (#30096)
Adds ascending/descending `model` and `provider` ordering to
`querySpans()` across Core, server, Client JS, PostgreSQL, DuckDB and
ClickHouse. No schema changes or backfill.

```ts
orderBy: [{ field: 'model', direction: 'asc' }]
```

Sorting uses the dedicated columns before pagination, with
case-sensitive UTF-8 ordering, missing values last, and identity
tie-breakers. String cursors preserve their values and remain bound to
the query and trusted scope. Legacy attribute-based display values
remain available without changing cursor boundaries. Trace/thread sort
fields stay unchanged. The server advertises
`spanQueryModelProviderSort` and rejects unsupported stores.

This PR is API-only. Studio sorting controls and live-refresh changes
are tracked in
[OBS-906](https://linear.app/kepler-crm/issue/OBS-906/add-model-and-provider-sorting-to-spans-explorer).
Enabling those controls needs raw model/provider sorting values
available to the existing head-row merge, including when polls are
ordered by end time; using display values can disagree with database
ordering. The PR has no remaining Playground UI changes or release
entry.

Validation: Core/server tests, real storage conformance across
PostgreSQL, DuckDB and ClickHouse, mixed-core checks, and
Core/server/adapter typechecks passed for the API implementation. After
removing the UI changes, both existing span component/hook suites pass
(52 tests). Changed-file lint and docs checks including CI Vale pass.

A bounded local ClickHouse 26.6.8.7 comparison used 180,000 synthetic
rows, 10,000 matches per tenant, distinct tenants across cases, both
directions and continuation pages, and disabled query/condition caches.
Median CPU was 21.9 ms for start time, 19.4 ms for model, and 21.4 ms
for provider; median query memory was about 4.6 MiB for each (maximum
6.8/8.4/7.2 MiB). These are selection-query measurements on synthetic
OSS data, not a production benchmark.

Part of OBS-896. Platform API support and package pins follow this OSS
merge and snapshot publication. UI enablement is tracked separately in
OBS-906.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

**ELI5:** Trace spans can now be sorted by their model name and provider
name, in both directions. The database does the sorting, so users can
page through the results in the right order.

## Overview

This change adds `model` and `provider` as sort fields for span queries.
It applies to the Core API, the server handlers, and the PostgreSQL,
DuckDB, and ClickHouse stores. The diff has 31 changed files, with 320
lines added and 43 removed.

## Core changes

- `SPAN_QUERY_ORDER_FIELDS` now includes `model` and `provider`.
- `SpanQueryPlanOptions` adds `allowSpanModelProviderOrdering?:
boolean`. Ordering by these fields requires this option.
- Trace and thread queries do not support these fields.
- Cursor validation accepts string or null values for `model` and
`provider`. Timestamp normalization applies only to `startedAt` and
`endedAt`.
- `SpanQuerySelectedRow` adds an optional `cursorSortValue`. Response
construction removes this field from returned spans. It uses the value
for the next-page cursor, and falls back to the row's ordering field
when the value is absent.
- The base storage feature union adds `span-query-model-provider-sort`.

## Server changes

- `assertObservabilitySpanModelProviderSortSupported` returns HTTP 501
with `SPAN_QUERY_UNSUPPORTED` when a store does not declare
`span-query-model-provider-sort`. The check runs before `querySpans` is
called.
- `ObservabilityStorageCapabilities` and its empty default add
`spanQueryModelProviderSort`, which defaults to `false`.
- The capability is reported as supported only when span queries are
supported, the core order fields include both `model` and `provider`,
and the store declares the feature.
- The system capabilities schema adds `spanQueryModelProviderSort:
z.boolean().default(false)`.
- The route handler permits model and provider ordering and performs the
capability check.

## Store changes

- **PostgreSQL:** Sorts by `model` and `provider` use `COLLATE "C"`. The
cursor bounds cast sort values to `text COLLATE "C"` when `stringSort`
is enabled. The feature is advertised only when the core order fields
include both fields.
- **DuckDB:** Sorts by `model` and `provider` use `"C"` collation.
Cursor values cast as strings with the same collation. The feature is
advertised only when the core order fields include both fields.
- **ClickHouse:** `afterCursor` treats `model` and `provider` as
strings. Null rows are included after the cursor for numeric and string
sorts. The feature is advertised only when the core order fields include
both fields.
- Returned `model` and `provider` values may still come from span
attributes. The code comments state that these fallback values are not
used for filtering or sorting.

## Tests and conformance

- Core tests cover ordering gating, rejection in trace and thread
queries, string and null cursor values, and rejection of cursors when
the order, filters, authorization, or scope change.
- Server tests cover the 501 rejection for `durationMs`, `model`, and
`provider` on older stores. They also cover capability parsing and the
capability flag in the system endpoint.
- Shared conformance tests in `stores/_test-utils` cover ascending and
descending pagination at page sizes 1, 2, and 3. They cover empty
strings, missing values, case and Unicode ordering, ties, and filter
exclusion. They also check that missing values sort last and that legacy
attribute values are not treated as dedicated fields.
- Store feature-list tests for ClickHouse, DuckDB, and PostgreSQL expect
the new feature flag.

## Changesets and documentation

- Changesets add minor release notes for `@mastra/core`,
`@mastra/server`, `@mastra/client-js`, `@mastra/duckdb`,
`@mastra/clickhouse`, and `@mastra/pg`.
- The advanced query reference adds the `spanQueryModelProviderSort`
capability row. It documents `model` and `provider` ordering. It states
that the comparison is case-sensitive and that missing values sort last
in both directions.

## Scope and limits

- This diff does not include Studio UI changes. The commit history says
UI enablement is deferred to a separate issue because it needs raw model
and provider values for head-row merging.
- This diff does not include client-js source changes. Its client-js
changeset documents the new sort fields.
- The diff does not include schema changes or backfill.
- The PR description reports these results, which this review did not
run or verify:
- Core and server tests, and real shared-storage conformance and
mixed-core checks, pass.
- Core, server, and adapter typechecks pass. Staged-file lint and docs
checks, including CI Vale, pass.
  - 58 Studio and MSW tests pass.
- The full Playground UI typecheck reports four unrelated chart and form
errors, and the library declaration build fails.
- A local ClickHouse 26.6.8.7 comparison with 180,000 synthetic rows
measured median CPU of 21.9 ms for start time, 19.4 ms for model, and
21.4 ms for provider. Median query memory was about 4.6 MiB for each.
These figures are not production measurements.
- Platform backend and UI wiring, and package pins, remain under
OBS-896.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-12 13:52:37 +01:00
dane-ai-mastra[bot]
a4258a989c
chore: version packages (alpha) (#30127)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-11-11 21:12:19 -08:00
dane-ai-mastra[bot]
055a8c3b82 chore: version packages 2026-11-12 04:17:40 +00:00
Abhi Aiyer
3dbe6f4314
fix(agent-controller): restore stored tool suspensions (#30132)
## Problem
When the server process that parked a run on a tool question (for
example `submit_plan`) goes away, the run stays suspended in storage.
Approving the plan later was rejected with `{ok:false,
reason:"no_pending_suspension"}` because claiming only looked in memory.
The Factory UI treated that 200 as success, so "Approve & build" did
nothing and the card kept offering buttons. Seen in prod on thread
`f82402a7` (plan waiting about 14h).

## Changes
- **core:** `Session.restoreStoredToolSuspension(toolCallId, runId?)`
registers a suspension that exists only in storage. It only does this
when exactly one stored suspended run on the active thread matches the
tool call id, and it skips approval prompts.
- **server:** the tool-suspension route restores the stored suspension
before claiming it. The claim stays synchronous.
- **factory-ui:** reply mutations now reject `ok:false` acks and show an
error toast. The respond mutation refetches the session. The transcript
only resolves a prompt once the reply was actually delivered.

## Tests
- `session-stored-suspension-after-restart.test.ts`: park on one
controller, then approve from a second controller that shares storage.
Fails before the fix. A negative case covers unknown calls and
mismatched runs.
- `useRespondSuspensionRejected.msw.test.tsx`: an `ok:false` ack fails
the mutation. Fails before the fix.
- core agent-controller 1021/1021, server agent-controller 104/104,
factory-ui chat/hooks 616/616, typecheck clean.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

**ELI5:** When an AI agent asks a question and waits for an answer, the
server can restart before the user replies. The reply used to fail
because the server only checked memory. Now the server loads the waiting
question from storage, so the reply works. The user interface also shows
an error when a reply is rejected.

## Overview

This change fixes replies to tool prompts after the process that parked
the run has stopped. Before this change, the claim step checked only
in-memory suspensions. A reply could return `{ ok: false, reason:
"no_pending_suspension" }`. Factory UI treated that response as success,
so the prompt buttons stayed visible.

The change also keeps prompt cards in sync across windows. When a tool
call completes, the matching approval or suspension card clears in every
window.

## Changes

**Core (`packages/core/src/agent-controller/session.ts`)**
- Adds `Session.restoreStoredToolSuspension(toolCallId?: string, runId?:
string): Promise<void>`.
- Returns without a storage lookup when the tool-call ID is missing, the
suspension is already resolvable, or no thread is active.
- Searches suspended runs in storage for the active thread and resource.
It checks each configured agent, reads 100 runs per page, and reads at
most 10 pages per agent.
- Optionally filters by `runId`. Matches only non-approval tool calls
that have the requested ID and a tool name.
- Stops scanning an agent on the no-storage error. Propagates other
lookup errors.
- Registers the suspension and caches its owning agent only when exactly
one match exists and no concurrent restore occurred.

**Server (`packages/server/src/server/handlers/agent-controller.ts`)**
- If `session.restoreStoredToolSuspension` is available, the
tool-suspension route awaits it with `toolCallId` and `runId`. It then
claims the suspension. If the method is not available, the route claims
directly.
- Rejected claims return `{ ok: false, reason }`. Accepted claims are
acknowledged, and the suspension response runs in the background.

**Factory UI**
- `useAgentControllerRunMutations.ts`:
- Validates tool approval and suspension acknowledgments with
`requireAccepted`. A rejected acknowledgment throws the new
`RejectedReplyError`.
- Adds `isEndedPrompt(error: unknown): boolean`. It returns true for
rejections with reason `no_pending_suspension`.
  - Both mutations report errors in a toast.
- Suspension-reply errors invalidate the session query. Successful
mutations also invalidate it.
- `Transcript.tsx`: Resolves a prompt after a successful mutation. On
rejection, resolves the prompt only when `isEndedPrompt` returns true.
Otherwise, leaves it unresolved.
- `services/transcript.ts`:
- On a `tool_end` event, updates the tool result. Removes only the
approval or suspension prompt with the matching `toolCallId`.
- Omits persisted prompts for tool calls in terminal states (`result`,
`output-error`, or `output-denied`).
- During server-window reconciliation, removes prompts for terminal tool
calls. Updates matching assistant tool invocations from persisted
terminal parts.

**Changeset (`.changeset/stale-plan-approval.md`)**
- Declares patch releases for `@mastra/core` and `@mastra/server`.

**Channels test
(`packages/core/src/channels/__tests__/agent-controller-channels.test.ts`)**
- The allow/deny policy test sets `deployTool` permission in
`onSessionStart`. It no longer sets the permission on a manually created
session. It reads the session after inbound processing.

**Tests**
-
`packages/core/src/agent-controller/__tests__/session-stored-suspension-after-restart.test.ts`
(new, +169): Covers approval from a second controller that shares
storage. Covers an unknown tool call, a call tied to a different run,
and the 10-page limit.
-
`mastracode/factory-ui/src/hooks/__tests__/useRespondSuspensionRejected.msw.test.tsx`
(new, +45): Mocks a `no_pending_suspension` rejection. Asserts an error
whose message indicates the prompt is no longer waiting. Asserts that
`isEndedPrompt` classifies only that rejection reason as an ended
prompt.
-
`mastracode/factory-ui/src/ui/domains/chat/services/__tests__/transcript.test.ts`
(+57): Covers persisted prompt visibility. A prompt stays visible while
its tool call has no result. It is hidden when a later message or
refetched window includes the result. A `tool_end` event clears only the
prompt with the matching `toolCallId`.
- `mastracode/web/e2e/web/approval-other-window.scenario.test.ts` (new,
+130): End-to-end scenarios for prompts in two windows. After a response
settles, approval, plan-suspension, and `ask_user` cards clear from the
non-answering window. Approval cards clear from the answering window.
Unanswered cards stay in both windows.
- `mastracode/web/e2e/web/fixtures/approval-other-window.json` (new,
+104): Fixture for the end-to-end scenarios. Defines six `gpt-5.4-mini`
interactions: write-file approve and decline, plan approve and revise,
and an `ask_user` prompt.

## Scope

- 12 files changed, 663 lines added, 30 lines removed.
- Added declarations:
- `Session.restoreStoredToolSuspension` (method,
`packages/core/src/agent-controller/session.ts`)
- `RejectedReplyError` (class) and `isEndedPrompt` (function) in
`mastracode/factory-ui/src/hooks/useAgentControllerRunMutations.ts`

## Test results

The author reports these results. This review did not run them:
- Core agent-controller: 1021/1021 passed.
- Server agent-controller: 104/104 passed.
- Factory UI chat and hooks: 616/616 passed.
- Typecheck: clean.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
2026-11-11 18:05:50 -08:00
Anurag Ojha
7c40bc84b6
fix(react): load the Studio review queue page by page (#29291)
Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-11 17:06:48 -08:00
dane-ai-mastra[bot]
9e82af0237
chore: version packages (alpha) (#30074)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-11-11 14:21:14 -08:00
Abhi Aiyer
4884ee08a0
fix(agent-controller): answer parked tool approvals when the permission rules allow or deny them (#30114)
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-11 14:18:01 -08:00
Abhi Aiyer
1689ce38e1
perf(agent-controller): read only the newest page when listing threads with a limit (#30090)
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
2026-11-11 13:53:07 -08:00
Eric Pinzur
aa49b049d0
feat(observability): order completed spans by duration (#30085)
Adds `durationMs` ascending/descending ordering to `querySpans()`,
combined with existing duration filters and stable cursor pagination.
Duration is the completed span’s elapsed time; zero is valid. Trace
ordering and trace runtime semantics are unchanged.

The server advertises `spanQueryDurationSort` and rejects unsupported
stores before execution. A span-specific field list and default-off
planner option protect old servers paired with newer Core. Updated
adapters advertise support only when Core understands it. PostgreSQL and
DuckDB reuse their numeric ordering paths; ClickHouse handles numeric
cursor parameters and normalizes duration values returned as Int64
strings. Includes generated API types, documentation and package
changesets. No schema migration.

Implements the OSS portion of
[OBS-899](https://linear.app/kepler-crm/issue/OBS-899).
[OBS-904](https://linear.app/kepler-crm/issue/OBS-904) tracks Platform
integration after merge and a snapshot from main. UI is outside this
backend change.

Validation: 134 Core, 112 server, 125 Client JS, 100 PostgreSQL, 94
DuckDB and 103 ClickHouse tests passed (one existing ClickHouse skip).
Shared conformance exercises both directions, filters, zero durations
and ties across page sizes. The new Core tests fail before the
implementation; reverting the ClickHouse cursor fix makes both new
pagination cases fail by skipping rows. Old-Core adapters omit the new
feature; old stores receive a structured 501. Core/server/store
typechecks, Core/server/SDK builds, changed-file lint/format and
required docs checks passed. Vale reports six warnings in unchanged
text. Local Node 23.11.0 is outside the supported 22/24 versions; CI
must verify supported runtimes.

A bounded local ClickHouse 26.6.8.7 experiment used 20,000 synthetic
completed spans, the same duration filter and 50-row first/second pages
in both directions. Duration ordering peaked at 3.43–3.67 MiB versus
3.42–3.66 MiB for timestamp ordering; both read 20,000 rows/1,488,890
bytes. Duration query CPU was 7–25 ms. These are single-run local
measurements, not production capacity evidence; no ingestion or storage
layout changed.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## ELI5

This PR lets users sort completed spans by how long they took. It keeps
pagination stable and enables the feature only when Core and the storage
adapter support it.

## Changes

- Added ascending and descending `durationMs` ordering to
`querySpans()`.
- Added duration-aware cursor validation and stable pagination.
- Added `spanQueryDurationSort` capability reporting.
- Added HTTP 501 handling for unsupported stores.
- Added compatibility gates for older Core versions.
- Updated PostgreSQL, DuckDB, and ClickHouse adapters.
- Converted ClickHouse duration values to numbers.
- Added Core, server, adapter, and conformance tests.
- Updated generated API types, documentation, and package changesets.
- No schema migration was added.

## Validation

- Reported passing tests: Core 134, server 112, Client JS 125,
PostgreSQL 100, DuckDB 94, and ClickHouse 103.
- One existing ClickHouse test remains skipped.
- Reported typechecks, builds, lint, formatting, and documentation
checks passed.
- Vale reported six warnings in unchanged text.
- CI verification on supported Node.js versions is not available.
- Diff size: 28 files changed, with 220 additions and 8 deletions.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-11 19:54:11 +01:00
Eric Pinzur
b2e0e40b57
feat(cli): align score and feedback API commands (#30089)
Closes [OBS-794](https://linear.app/kepler-crm/issue/OBS-794).

Adds `feedback create`, `list`, `get`, `replace`, and `review-status`,
plus `aggregate`, `breakdown`, `timeseries`, and `percentiles` for both
scores and feedback. Creates generate missing IDs and timestamps once
and preserve them across bounded HTTP retries and credential fallback.
Replacements require the original identity and timestamp; review-status
updates preserve missing-record errors. Context-mode omission and
feedback author fields are passed through without inferring values.

List output preserves pagination and delta cursors, and write output
retains the server's success and identity data. Score/feedback schemas
are generated from the server routes and bundled for `--schema` without
requiring a target schema endpoint. Most of the diff is that generated
file. Includes help examples, CLI reference docs, and a minor `mastra`
changeset.

Validation: 221 CLI API tests, including 57 real-HTTP cases; 20 repeated
timeout/credential-fallback runs; CLI typecheck; type-aware
lint/precommit checks; docs check with Vale and the CI Vale
configuration. Validated all 14 write/analytics help examples against
the current server body schemas. Missing-anchor retries, transient
failures, credential fallback, older success-only responses, unsupported
endpoints, and API-prefix/auth headers are covered.

The full `turbo build --filter mastra` stopped in the unchanged
`@mastra/playground-ui` declaration step (`tsc found type errors`, with
no underlying diagnostic emitted) before building the CLI. Local checks
used Node 23.11.0, which is outside the repository's requested engine
range. Live Platform writes and package publication/deployment were not
tested.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

## ELI5

This PR adds commands to create, review, list, and analyze scores and
feedback. It also makes retries safer by preserving the same IDs,
timestamps, and request data.

## Changes

- Added feedback `create`, `list`, `get`, `replace`, and `review-status`
commands.
- Added `aggregate`, `breakdown`, `timeseries`, and `percentiles` for
scores and feedback.
- Added validation for write inputs and feedback replacement identity.
- Added bounded retries for transient failures and credential fallback.
- Preserved pagination cursors, response identity data, and feedback
fields.
- Bundled generated score and feedback schemas for offline `--schema`
output.
- Added unsupported-endpoint errors for HTTP 405 and 501 responses.
- Updated documentation, help examples, and the `mastra` changeset.
- Added HTTP-backed tests for commands, validation, retries, responses,
and schemas.

## Validation

- The author reports 221 CLI API tests, including 57 real-HTTP cases.
- The author reports passing typecheck, lint, precommit, Vale, and
documentation checks.
- The build stopped in the unchanged `@mastra/playground-ui` declaration
step before the CLI build.
- Local checks used Node 23.11.0, outside the repository’s requested
engine range.
- Live Platform writes and package publication or deployment were not
tested.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-11 19:53:52 +01:00
mastra-platform[bot]
b0ef22e7bf
feat(schedules): Add bounded one-off schedules (#25131)
> Opened by @abhiaiyer91

Refs #24610

## Summary
Schedules can now fire once or stop after a given time, so you no longer
need to pin a cron expression to a date and clean it up yourself.

- **New `completed` status**: the scheduler and timing reconciliation
set it when no automatic fires remain. It's written in the same atomic
`nextFireAt` check-and-set used to claim a run, so a schedule still
fires only once across instances. A cron with no future occurrence left
also moves to `completed` instead of erroring. `pause`/`resume` on a
completed schedule return 409. Changing `runAt`/`endAt` reactivates it
only when the resulting timing can still fire. `list()` hides completed
schedules unless you pass `status: 'completed'`.
- **Declarative workflow schedules**: `createWorkflow({ schedule: {
runAt } })` and `{ cron, endAt }` are supported. Past times are accepted
so redeploys don't fail, and a completed schedule isn't re-armed unless
its timing changes.
- **Trigger kind**: one-off fires report `trigger.kind: 'once'`.
- `run(id)` doesn't complete a one-off schedule.

## Surfaces
- **Core**: types, validation, scheduler claim logic,
create/update/pause/resume/list, declarative sync.
- **Storage**: new nullable `run_at`/`end_at` columns for libsql, pg,
mysql, mongodb, spanner, convex and in-memory. Existing columns are
untouched: one-off schedules store `cron` as `''`.
`updateScheduleNextFire` takes an optional `newStatus`.
- **Server/client-js/CLI**: request bodies accept `runAt`/`endAt`
(one-of rule checked in the schema). Responses include the new fields
and `completed`. Route types and CLI route metadata regenerated.
- **Studio**: shows the run time for one-off schedules, shows the
`endAt` bound, adds a `completed` badge and hides pause/resume for
completed schedules.
- **Docs + changeset.**

## Not in this PR (remaining #24610 work)
- ISO 8601 string inputs for `runAt`/`endAt` (numbers and `Date` are
accepted today).
- The template `schedule_once` tool.

## Test plan
- [x] core: schedules, scheduler, cron, schedule-config and scheduler
integration tests (260 passing), clean `tsc`
- [x] Shared adapter suite gained tests for `runAt`/`endAt` round-trip
and atomic status CAS. Passing on libsql, pg, mysql and mongodb
(Docker), plus convex server tests. **Not run on Spanner (no emulator
available); typecheck only.**
- [x] server schedules handler tests (51 passing, including
one-off/bounded creation and body validation)
- [x] client-js and playground typecheck clean; playground schedules
tests passing

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## ELI5

Schedules can now run once at a chosen time or repeat until a chosen end
time. They complete when their planned runs are over, and changing their
timing can make them active again.

## Summary

- Added `runAt` for one-off agent and workflow schedules. API-created
schedules require a future `runAt`; declarative workflow schedules can
register past times as `completed`.
- Added `endAt` for cron schedules. A schedule becomes `completed` when
its next run would occur after `endAt`, or when no future run remains.
- Completed schedules cannot be paused or resumed. Timing changes can
reactivate a completed schedule when a future run remains. `list()`
hides completed schedules unless callers filter with `status:
'completed'`.
- Resuming a paused one-off schedule after its `runAt` has passed allows
it to fire on the next scheduler tick. Calling `run(id)` manually does
not complete a one-off schedule.
- Added the `once` trigger kind for scheduled one-off agent fires.
Manual runs remain `manual`.
- Declarative workflow schedules preserve completed status across
redeploys when timing is unchanged. Timing changes can re-arm them.
- Updated schedule APIs, storage adapters, Studio, and documentation.
Storage persists `runAt` and `endAt` and supports atomic status updates.

## Checks

Current-head CI, build, and test results: not available.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Abhi Aiyer <abhiaiyer91@gmail.com>
Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: NikAiyer <nick.aiyer@gmail.com>
Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: Ehindero Israel <iehindero419@stu.ui.edu.ng>
2026-11-11 19:33:50 +01:00
Eric Pinzur
2053c881ed
fix(observability): export feedback review-status updates (#30075)
HTTP feedback review-status changes persist locally but do not reach
exporters. This forwards successful updates to supporting exporters and
adds `observability.updateFeedbackReviewStatus({ feedbackId,
reviewStatus })` for independent SDK delivery. A missing or slow local
record does not block remote delivery; the HTTP route still requires an
existing local record, honors the configured resourceId, and returns its
updated value. Organization IDs remain metadata and do not scope this
PATCH route.

MastraPlatformExporter sends the existing review-status PATCH contract,
retries recognized missing-feedback and temporary lookup responses, and
tracks delivery through flush/shutdown. Replacement PUTs and review
PATCHes for the same feedback ID share one queue through retries,
including failure recovery. This orders requests from one exporter
instance; successful publication still does not guarantee that a
subsequent PATCH reads the latest queued PUT from Platform storage.
Storage exporters wait for earlier creates of that feedback to resolve
and persist before updating it, including buffered and in-flight writes.
Other exporters remain independent. Optional hooks let older exporters
skip the update safely; HTTP updates still work when observability lacks
the notification hook. This covers review status only, with no general
PATCH or UI changes.

Fixes #24054, completing its remaining review-status exporter gap after
the create/replacement work. Part of OBS-785. Platform delivery requires
the matching endpoint from merged mastra-ai/platform#4651 to be
deployed; the Platform UI rollout remains separate.

Validation: the HTTP export regressions failed before the fix and pass
afterward. Shared HTTP suites pass in Hono, Express, Fastify, NestJS and
Koa (92 tests each); exporter HTTP tests (163 in the latest run) and
neighboring observability tests (234), and server handler tests (167)
pass. The retry-ordering, buffered-create, and inherited-hook
regressions failed before their fixes. Timing-sensitive ordering tests
passed 20 repeated runs, including PUT/PATCH in both directions with
flush/shutdown and independent IDs. Relevant builds, client-js build,
typed lint, formatting and docs checks pass. Route metadata regeneration
produces no diff. Local validation used Node 23.11.0, outside the
repository's supported engine range. Docs checks and CI-equivalent Vale
lint pass with Vale 3.25.1 installed.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## ELI5

This PR sends feedback review-status changes to observability exporters,
not only local storage. It also adds an SDK method for sending these
updates directly.

## Summary

- Added `observability.updateFeedbackReviewStatus({ feedbackId,
reviewStatus })`.
- Added the `feedback_review_status` event and exporter hooks.
- Updated the HTTP route to validate local feedback and `resourceId`,
update local storage, return the updated record, and notify exporters.
- Added Platform `PATCH` delivery with retries for recognized
missing-feedback and temporary lookup responses.
- Serialized updates for the same feedback ID while keeping different
IDs independent.
- Allowed remote delivery when local feedback is missing or local
storage lacks review-status support.
- Preserved compatibility with exporters that do not implement the new
hook.
- Tracked pending updates through `flush()` and shutdown.
- Added documentation, changesets, and regression tests.
- Scope remains limited to review-status updates. No general `PATCH`
behavior or UI changes.

## Validation

- 21 files changed: 752 additions and 50 deletions.
- Reported HTTP suites passed for Hono, Express, Fastify, NestJS, and
Koa, with 92 tests per suite.
- Reported exporter HTTP tests, neighboring observability tests, and
server handler tests passed.
- Reported builds, client-js build, typed lint, formatting,
documentation checks, and route metadata checks passed.
- Vale validation used version 3.25.1.
- Validation used Node 23.11.0, outside the repository’s supported
engine range.
- Platform delivery requires deployment of the matching endpoint from
`mastra-ai/platform#4651`.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-11 19:08:11 +01:00
shreyas-mastra
9027829db3
fix(server): let the first matching auth rule decide access (#29324) 2026-11-11 08:45:14 -08:00
dane-ai-mastra[bot]
3a6ca42696
chore: version packages (alpha) (#30026)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-11-11 08:16:57 -08:00
Eric Pinzur
c860b9bb43
feat(observability): support OSS feedback replacement (OBS-887) (#30059)
Implements
[OBS-887](https://linear.app/kepler-crm/issue/OBS-887/add-oss-feedback-replacement-and-export).

Add OSS `PUT /api/observability/feedback/:feedbackId` with the existing
wrapped client request. Replacements retain the original feedback ID,
trace ID, timestamp, and tenant; omitted optional fields are cleared. A
full replacement can create a missing record. OSS persists locally
before responding, then independently notifies supporting exporters.
Resolve mode still requires the local anchor. The SDK also exposes
optional `replaceFeedback()` for independent exporter delivery without a
producer-side storage lookup.

Replacement events use a separate optional exporter hook.
`MastraPlatformExporter` sends PUT with stable identity across bounded
anchor retries, and flush/shutdown drain deliveries. Older exporters
skip replacements rather than replaying them as creates. Unsupported
storage/package combinations return 501 or skip unavailable export
support. No UI changes; review-status PATCH propagation remains tracked
in OBS-785.

In-memory, PostgreSQL vNext, DuckDB, and ClickHouse vNext support
replacement. In-memory, PostgreSQL, and DuckDB enforce replacement
identity at the write. PostgreSQL coordinates writes by feedback ID,
including duplicates submitted with a different timestamp. Duplicate
HTTP creates return the stored identity and timestamp and re-notify
exporters with accepted values. Tenant mismatches remain hidden, and an
omitted SDK replacement author stays null. HTTP/exporter creates use
`onConflict: 'ignore'` so a delayed original create doesn't undo an
edit; direct storage calls keep their legacy upsert default.
**ClickHouse requires no migration:** it uses the existing schema and
read-before-insert protection. Sequential delayed creates are covered,
but overlapping writes from separate processes can race; this is not a
globally ordered or exactly-once protocol.

Latest review fixes: DuckDB's lazy facade delegates replacement to its
guarded writer; concurrent coverage runs 20 overlapping request pairs
per identity variant. Direct storage replacements normalize an omitted
author to null. PostgreSQL single-feedback reads use the primary for
read-after-write consistency, while list/aggregate reads retain the
configured read client. Batch advisory locks use one ordered query with
unchanged lock keys.

Validation: the stronger DuckDB regression failed on all four identity
variants before the facade fix. Afterward, the entire DuckDB package
passed 718 tests across 21 files in three consecutive runs. PostgreSQL
passed 57 feedback tests, including a real stale read snapshot and
overlapping reversed 1,000-ID batches. Shared replacement tests passed
on in-memory (12), and the new author regression passed on ClickHouse
without a migration. Core/storage builds and declarations, typed lint,
and formatting passed. Earlier HTTP (85 cases on each of four adapters),
generic Hono routes (2,848), server/system, exporter, and docs checks
remain recorded in the PR history. Local tests use Node 23.11.0; CI
validates the supported runtime.

The unrelated Traces UI fade assertion failure was fixed in
https://github.com/mastra-ai/mastra/pull/30068; this branch includes
that fix from main.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## ELI5

This PR lets users replace feedback without changing its identity. It
stores the replacement locally and sends it to supported exporters
without allowing delayed creates to overwrite it.

## Changes

- Added `PUT /api/observability/feedback/:feedbackId`.
- Preserved the feedback ID, trace ID, timestamp, and tenant.
- Cleared omitted optional fields.
- Added capability detection and `501` responses for unsupported
storage.
- Added replacement event types, SDK support, client types, route
metadata, and documentation.
- Added replacement delivery, stable retries, flush handling, and
shutdown draining for `MastraPlatformExporter`.
- Added replacement support for in-memory, PostgreSQL vNext, DuckDB, and
ClickHouse vNext.
- Added `onConflict: 'ignore'` for HTTP and exporter creates. Direct
storage calls retain their upsert default.
- Older exporters skip replacements instead of replaying them as
creates.
- Added ClickHouse support without a migration. Concurrent writes from
separate processes can still race.
- No UI changes were included.

## Validation

The author reports passing the HTTP route and contract suites, feedback
storage suites, partition and SQL tests, server and system tests,
record-builder tests, build, typecheck, lint, and documentation checks.

For the current head, the available CI result is `2027dev Evals:
skipped`. Other listed CI checks target different commits or remain in
progress. Current-head CI results are otherwise not available.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-11 17:04:57 +01:00
Eric Pinzur
166ad37deb
fix(observability): deliver feedback and scores independently to exporters (#30052)
Feedback and scores submitted with only a trace/span ID can be dropped
before reaching remote exporters because the SDK first looks in local
storage. For example, `addFeedback({ traceId, feedback })` cannot
currently reach Platform when that trace exists only there. This change
dispatches to every supporting exporter immediately and moves local
lookup/retries into MastraStorageExporter and the deprecated
DefaultExporter. Each storage exporter enriches its own copy while
preserving the original ID and timestamp.

OSS HTTP creates keep their existing local persistence and response
contract, then notify exporters without writing through the storage
exporter again. Supplied context, including an empty object, stays
supplied. Exported feedback preserves the author and review status,
including an explicitly null author. Pending storage lookups and custom
exporter deliveries are included in flush/shutdown. HTTP creates return
after local persistence and enqueue exporter delivery without waiting
for custom handlers to finish. Studio routing is unchanged: writes
target the backend serving reads.

Local context resolution requires the target span’s actual ancestor
root. Missing parents are retried, then logged and skipped locally; we
intentionally do not borrow another root’s tags or store incomplete root
context. Other exporters still receive the record independently.
Transient storage-read errors use the same bounded retry window and
report the final read error when exhausted.

Validated after review with 316 exporter/bus/recorded-span tests and 69
HTTP contract tests each on Hono, Fastify, and Koa (523 tests). The four
custom-exporter timing cases also passed 20 repeated runs. The
read-error and HTTP-latency regressions failed before their fixes, and
temporarily allowing the orphan fallback failed the new root-context
regression. Six older mocked forwarding/race tests are replaced by real
storage and HTTP coverage. Package builds, observability production and
adapter-suite typechecks, changed-file lint, and docs checks pass;
generated route types and CLI metadata are unchanged.

Express and NestJS tests hit a JSON body-parser failure before our
handlers. Standalone Express with no Mastra code reproduces `getBody is
not a function` under the local Node 23.11.0 runtime. The standalone
observability typecheck also retains four existing errors in
`workflow-control-flow-suite.ts`. These are not fixed here.

Fixes [OBS-886](https://linear.app/kepler-crm/issue/OBS-886) and
addresses the create-delivery portion of
[#24054](https://github.com/mastra-ai/mastra/issues/24054). Feedback
replacement remains in
[OBS-887](https://linear.app/kepler-crm/issue/OBS-887), and
review-status PATCH propagation remains in
[OBS-785](https://linear.app/kepler-crm/issue/OBS-785).

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## ELI5

This PR sends feedback and score records to each exporter independently.
Missing local traces no longer prevent remote delivery, and HTTP-created
records keep their original data.

## Summary

- Added exporter-specific event routing.
- Moved trace and span resolution into `MastraStorageExporter` and
`DefaultExporter`.
- Added bounded retries for storage lookups.
- Added pending annotation delivery before `flush()` and shutdown.
- Added asynchronous exporter notifications after successful HTTP
persistence.
- Prevented duplicate storage writes for HTTP-created records.
- Preserved IDs, timestamps, context, authors, anonymous feedback,
metadata, and review status.
- Added nullable `feedbackUserId` and `reviewStatus` support.
- Added SDK and HTTP adapter integration tests.
- Updated documentation, package metadata, and changesets.

**Diff:** 30 files changed; 954 additions and 483 deletions.

## Validation

- Reported: 503 focused tests passed, including 65 HTTP contract tests
for each of Hono, Fastify, and Koa.
- Reported: builds, changed-file lint, and documentation checks passed.
- Express and NestJS tests fail during JSON body parsing with `getBody
is not a function`.
- Standalone observability typecheck retains four existing errors.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-11 14:41:54 +01:00
Eric Pinzur
9751742c44
feat(observability): add aggregated trace root contracts (#30054)
Adds the shared contract for the Platform aggregated-roots experiment in
[OBS-891](https://linear.app/kepler-crm/issue/OBS-891): optional
`rootSource`, `rootKind`, runtime/error totals, and availability
reporting. Legacy requests retain their cursor bindings; aggregated
cursors are separate and aggregated metadata predicates and delta
requests are rejected.

The planner requires host opt-in. OSS servers report the capability as
false and explicitly reject aggregated requests; storage implementations
and UI are outside this prerequisite. Generated client and CLI contracts
are updated.

Validated with 102 core tests, 146 server tests, core typecheck,
core/server/client builds, and formatting/lint checks. A mutation check
confirms that removing root-source cursor binding fails the regression
test. Platform implementation follows after this merges and a snapshot
is published.

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## ELI5

This PR defines how systems can report aggregated trace roots and their
totals. Systems without support reject these requests, while existing
legacy trace queries continue to work.

## Changes

- Added `rootSource` with `legacy` and `aggregated` values.
- Added aggregated-root response fields:
  - `rootKind`
  - `runtimeDurationMs`
  - `errorCount`
- Bound trace and group cursors to their root source.
- Rejected aggregated delta requests.
- Rejected metadata predicates for aggregated roots.
- Kept `runtimeDurationMs` and `errorCount` response-only.
- Added the `traceQueryAggregatedRoots` capability, which defaults to
`false`.
- Added a `501 TRACE_QUERY_UNSUPPORTED` response for unsupported
aggregated requests.
- Updated generated client and CLI route contracts.
- Added core and server regression tests.
- Added release changes for `@mastra/core`, `@mastra/client-js`,
`@mastra/server`, and `mastra`.

## Validation

Not available from completed checks on the current head.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-11 14:26:42 +01:00
Leo
8896651bd1
fix(server): stop custom route agent runs on client disconnect after GC (#29617)
## Description

### Summary

When a client disconnects from a custom API route that streams an agent
run (for example `chatRoute`), the run and its model request could keep
going. Server adapters re-dispatch custom routes through `new
Request(url, { signal })`. undici forwards the client abort to that
inner Request's own signal through a listener that holds the inner
controller only weakly (nodejs/undici#4068). Once the route returns its
streaming Response, nothing holds the inner Request, so a GC drops it
and the abort never reaches `c.req.raw.signal`.

The fix is in the shared `handleCustomRouteRequest` in `@mastra/server`,
so every custom route on every adapter gets it. The returned Response
gets a pass-through body whose closure holds the inner Request, and
drops it when the body is fully read, errors or is cancelled. Status,
status text and headers are unchanged; null-body responses are returned
as is.

```diff
 handleCustomRouteRequest(url, method, headers, body, requestContext, signal)
   const request = new Request(url, { ...init, signal })
   const response = await customRouteHandler(request, ...)
-  return response
+  return signal ? retainRequestWhileBodyIsOpen(response, request) : response
```

An earlier version of this PR used a `WeakMap<AbortSignal, Request>`
keyed by the client signal. Factory found it leaked every request whose
signal never aborts, which includes every normal Express response.
Cause: undici's `Request` constructor calls
`requestFinalizer.register(ac, { signal, abort })`, and a
FinalizationRegistry holds that held value (with the outer signal)
strongly while the inner controller lives, so signal -> WeakMap ->
request -> controller -> registry -> signal is a cycle the GC never
breaks. Holding the request from the body avoids the cycle: the body is
reachable exactly while an adapter is still sending the response.

```mermaid
flowchart LR
  A[client socket close] --> B[outer AbortController.abort]
  B --> C[undici listener on outer signal]
  C -. WeakRef .-> D[inner Request's controller]
  D --> E[c.req.raw.signal -> agent.stream abortSignal]
  G[adapter reading response body] ==> H[pass-through body]
  H == holds until done / error / cancel ==> F[inner Request]
  F --> D
```

### Evidence

Shared conformance suite `createCustomRouteDisconnectTestSuite`
(`@mastra/server-adapters-test-suite`), wired into Hono
(`@hono/node-server`), Express, Fastify, Koa and Elysia, over real HTTP:

1. Disconnect: a real `Agent` streams from a fake OpenAI-compatible
server, the route passes `c.req.raw.signal` as `abortSignal` (the same
wiring as `chatRoute`), the test forces GC, destroys the client socket,
and asserts the model request is aborted.
2. Release (new): a custom route streams a 201 response that completes,
or fails mid-stream; the test registers the inner `c.req.raw` and its
signal with a `FinalizationRegistry`, forces GC, and asserts both are
finalized.

| Server code | Disconnect | Release, completes | Release, fails
mid-stream |
|---|---|---|---|
| `origin/main` style, no retention | fails 5/5 adapters (`expected
'model request still running' to be 'model request aborted'`) | passes
5/5 | passes 5/5 |
| previous PR head 02fada0 (WeakMap) | passes 5/5 | fails 5/5 (`expected
[] to deeply equal [ 'request', 'request signal' ]`) | fails on Elysia;
others abort the signal on a broken body |
| this head | passes 5/5 | passes 5/5 | passes 5/5 |

- **Stability:** with the fix, 40/40 adapter suite runs passed (5 runs
of the 2-test suite plus 3 runs of the 3-test suite, on each adapter).
An independent reviewer ran Express and Hono 20 times each, all passing.
- **Factory's measurement, reproduced** (`new Request(url, { signal })`,
80 forced GCs, `FinalizationRegistry`):

| Node (undici) | No map | `WeakMap.set(signal, request)` | WeakMap +
abort |
  |---|---|---|---|
| v24.22.1 (7.30.1) | both finalized | neither finalized | both
finalized |
  | v22.22.1 | both finalized | neither finalized | both finalized |

- **Issue repro script** (`chatRoute` + `createNodeServer`, `node
--expose-gc`): `aborted after disconnect: false` before, `true` after,
on Node 24.22.1 and 22.22.1. CI runs Node 24.22.1, where the bug
reproduces.
- **No regressions:** `@mastra/server` `src/server/server-adapter` unit
tests 434/434. `tsc --noEmit` for `@mastra/server` and the test suite,
`oxfmt --check` and `oxlint --deny-warnings` are clean on the changed
files. The reviewer also checked status, status text, multiple
`set-cookie`, mutable headers (Fastify merges plugin headers into the
returned Response), explicit `content-length`, and Hono's node-server
`Response` override.
- **Not covered:** native Bun (Elysia's test runs on a Node HTTP shim;
Bun's `Request` isn't undici). `@mastra/nestjs` custom routes don't
forward a client abort signal at all, which is a separate gap this PR
doesn't touch.

### Merge Danger

**Door:** two-way. One helper in `server-adapter/index.ts` plus tests
and changesets; a revert undoes it.

**Blast radius:** every custom API route response with a body, on every
adapter. The body now passes through one extra `ReadableStream`: one
extra async read per chunk, and no BYOB reads of the route's body. On
Hono, `@hono/node-server` can no longer infer `content-length` for a
small non-streamed custom route body (for example `c.json(...)`), so it
goes out chunked unless the handler sets `content-length` itself.
Express, Fastify and Koa already pipe custom route bodies as chunked. A
body an adapter keeps but never reads or cancels keeps its request until
the body is collected; no adapter does that today. Conflicts: none with
#29549 (`feat(ai-sdk): add reconnectable chat routes`), which rewrites
`client-sdks/ai-sdk/src/chat-route.ts`; this PR does not touch that
file.

## Related issue(s)

Closes #29154

## Type of change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Code refactoring
- [ ] Performance improvement
- [x] Test update

## Checklist

- [x] I have linked the related issue(s) in the description above
- [ ] I have made corresponding changes to the documentation (if
applicable)
- [x] I have added tests that prove my fix is effective or that my
feature works
- [ ] I have addressed all Coderabbit comments on this PR

## Council review

Rounds: 3

| Seat | Round 1 | Round 2 | Round 3 (request release follow-up) |
| --- | --- | --- | --- |
| Claude Opus 5.5 | not run | 9/10 (Correctness 9, Tests 9, Scope 10,
Code quality 9) | not run |
| GPT-6.1 Sol | 9/10 (Correctness 9, Tests 9, Scope 10, Code quality 9)
| 9/10 (Correctness 9, Tests 9, Scope 10, Code quality 9) | 9/10
(Correctness 9, Tests 9, Scope 10, Code quality 9), no findings |
| Grok 4.7 | empty seat | empty seat | empty seat |

Created with Claude Opus 5.5 in T3 Code.

🤖 Generated with [Claude Code](https://claude.com/claude-code)


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## ELI5

When a client disconnects during a streamed response, the server keeps
the request alive until the response ends, fails, or is cancelled. This
allows the disconnect to stop the agent and model request after garbage
collection.

## Changes

- Updated `handleCustomRouteRequest` to retain the re-dispatched
`Request` while a response body is active.
- Preserved response status, status text, and headers.
- Left null-body responses unchanged.
- Added shared tests for disconnect handling and request release.
- Added test setups for Hono, Express, Fastify, Koa, and Elysia.
- Exported the shared test suite and configuration type.
- Added patch changesets for `@mastra/server` and
`@mastra/server-adapters-test-suite`.

**Diff size:** 10 files; 504 lines added and 1 removed.  
**CI, build, and test results:** not available.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 03:34:38 -05:00
dane-ai-mastra[bot]
8bce7717eb
chore: version packages (alpha) (#29986)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-11-10 20:51:40 -08:00
dane-ai-mastra[bot]
23cc34a9c5
chore: version packages (alpha) (#29938)
This PR was opened by the [Changesets
release](https://github.com/changesets/action) GitHub action. When
you're ready to do a release, you can merge this and publish to npm
yourself or [setup this action to publish
automatically](https://github.com/changesets/action#with-publishing). If
you're not ready to do a release yet, that's fine, whenever you add more
changesets to main, this PR will be updated.

⚠️⚠️⚠️⚠️⚠️⚠️

`main` is currently in **pre mode** so this branch has prereleases
rather than normal releases. If you want to exit prereleases, run
`changeset pre exit` on `main`.

⚠️⚠️⚠️⚠️⚠️⚠️

# Releases

> The changelog information of each package has been omitted from this
message, as the content exceeds the size limit.

## @mastra/factory@0.28.0-alpha.6


## @mastra/code-sdk@1.19.0-alpha.6


## @mastra/playground-ui@69.0.0-alpha.7


## @mastra/client-js@1.60.0-alpha.6


## @mastra/react@1.15.0-alpha.6


## @mastra/deployer-cloud@1.83.0-alpha.6


## @mastra/longmemeval@1.1.42-alpha.6


## @mastra/opencode@0.1.42-alpha.6


## create-factory@0.4.3-alpha.6


## mastracode@0.50.0-alpha.6


## @mastra/agent-builder@1.2.1-alpha.3


## mastra@1.39.0-alpha.6


## @mastra/core@1.83.0-alpha.6


## @mastra/deployer@1.83.0-alpha.6


## @mastra/editor@0.17.1-alpha.4


## @mastra/mcp@2.9.0-alpha.3


## @mastra/mcp-docs-server@1.3.13-alpha.9


## @mastra/memory@1.41.1-alpha.3


## @mastra/rag@2.7.3-alpha.2


## @mastra/schema-compat@1.3.18-alpha.0


## @mastra/server@1.83.0-alpha.6


## @mastra/elysia@0.1.23-alpha.6


## @mastra/express@1.5.27-alpha.6


## @mastra/fastify@1.5.27-alpha.6


## @mastra/hono@1.7.25-alpha.6


## @mastra/koa@1.7.27-alpha.6


## @mastra/nestjs@0.3.0-alpha.6


## @mastra/next@0.2.41-alpha.6


## @mastra/server-adapters-test-suite@0.3.0-alpha.3


## @mastra/tanstack-start@0.2.41-alpha.6


## @mastra/upstash@1.6.1-alpha.0


## @mastra/vectorize@1.1.5-alpha.0


## @mastra/voice-google-gemini-live@0.14.19-alpha.0


## @mastra/voice-openai-realtime@0.14.9-alpha.0


## @mastra/voice-xai-realtime@0.2.18-alpha.0


## @mastra/inngest@1.11.2-alpha.4


## @mastra/temporal@0.6.0-alpha.6


## create-mastra@1.39.0-alpha.6


## @internal/playground@1.39.0-alpha.6

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-11-10 15:51:29 -08:00
Daniel Lew
2dbb9c83b3
test(server): harden the Observational Memory ownership tests and correct the changeset (#29955)
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-10 16:12:20 -05:00
Daniel Lew
94bf8761f4
fix(server): enforce thread ownership on gateway Observational Memory routes (#29926)
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-10 12:36:51 -08:00
dane-ai-mastra[bot]
779d2875b1
chore: version packages (alpha) (#29912)
This PR was opened by the [Changesets
release](https://github.com/changesets/action) GitHub action. When
you're ready to do a release, you can merge this and publish to npm
yourself or [setup this action to publish
automatically](https://github.com/changesets/action#with-publishing). If
you're not ready to do a release yet, that's fine, whenever you add more
changesets to main, this PR will be updated.

⚠️⚠️⚠️⚠️⚠️⚠️

`main` is currently in **pre mode** so this branch has prereleases
rather than normal releases. If you want to exit prereleases, run
`changeset pre exit` on `main`.

⚠️⚠️⚠️⚠️⚠️⚠️

# Releases

> The changelog information of each package has been omitted from this
message, as the content exceeds the size limit.

## @mastra/auth-studio@1.4.0-alpha.1


## @mastra/factory@0.28.0-alpha.5


## @mastra/mcp-apps-components@0.1.0-alpha.5


## @mastra/playground-ui@69.0.0-alpha.6


## @mastra/client-js@1.60.0-alpha.5


## @mastra/react@1.15.0-alpha.5


## @mastra/deployer-cloud@1.83.0-alpha.5


## @mastra/longmemeval@1.1.42-alpha.5


## @mastra/opencode@0.1.42-alpha.5


## create-factory@0.4.3-alpha.5


## @mastra/code-sdk@1.19.0-alpha.5


## mastracode@0.50.0-alpha.5


## @mastra/agent-builder@1.2.1-alpha.2


## mastra@1.39.0-alpha.5


## @mastra/core@1.83.0-alpha.5


## @mastra/deployer@1.83.0-alpha.5


## @mastra/editor@0.17.1-alpha.3


## @mastra/mcp@2.9.0-alpha.2


## @mastra/mcp-docs-server@1.3.13-alpha.8


## @mastra/memory@1.41.1-alpha.2


## @mastra/rag@2.7.3-alpha.1


## @mastra/server@1.83.0-alpha.5


## @mastra/elysia@0.1.23-alpha.5


## @mastra/express@1.5.27-alpha.5


## @mastra/fastify@1.5.27-alpha.5


## @mastra/hono@1.7.25-alpha.5


## @mastra/koa@1.7.27-alpha.5


## @mastra/nestjs@0.3.0-alpha.5


## @mastra/next@0.2.41-alpha.5


## @mastra/server-adapters-test-suite@0.3.0-alpha.2


## @mastra/tanstack-start@0.2.41-alpha.5


## @mastra/libsql@1.30.0-alpha.2


## @mastra/turso@0.1.21-alpha.2


## @mastra/inngest@1.11.2-alpha.3


## @mastra/temporal@0.6.0-alpha.5


## create-mastra@1.39.0-alpha.5


## @internal/playground@1.39.0-alpha.5

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-11-10 10:50:08 -08:00
shreyas-mastra
bfda77de97
fix(core,server): scope experiment comparison by organization and project (#29479)
`mastra.datasets.compareExperiments` had no way to scope by organization
or project, and the compare route ignored the tenancy query params the
other dataset routes accept. A caller scoped to one tenant could compare
experiments from another by ID.

`compareExperiments` now takes `organizationId` and `projectId`. When
either is set, every experiment must match, otherwise it throws
`EXPERIMENT_NOT_FOUND` (same as a missing row, so other tenants' IDs
don't leak). The route reads `tenancyQuerySchema` and passes the scope
to both the dataset lookup and the comparison. Unscoped calls behave as
before.

Added manager tests for a cross-tenant pair (rejected, fails without the
fix) and a same-tenant pair. Core datasets tests (490), server datasets
handler tests (106), tsc and lint pass.

Fixes PLTFRM-3165


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## ELI5

When a caller chooses an organization or project, experiment comparisons
now stay within that scope. Experiments outside it are treated as not
found, so their results are not exposed.

## Changes

- `mastra.datasets.compareExperiments` accepts optional `organizationId`
and `projectId` values.
- When either scope is set, the manager checks every distinct experiment
ID. It throws `EXPERIMENT_NOT_FOUND` if an experiment is missing or
outside the scope.
- The comparison route reads tenancy query parameters and passes them to
the dataset lookup and comparison.
- If scoped comparison is requested with a core version that does not
advertise tenancy enforcement, the route returns HTTP 501 before reading
data. Unscoped comparisons remain unchanged.
- Tests cover cross-organization rejection, same-organization
comparisons, and the route’s behavior when the core feature is
unavailable.
- Updated generated route metadata and added patch changesets for
`@mastra/core` and `@mastra/server`.

## Validation

Current-head test, TypeScript, and lint results are not available.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
2026-11-10 12:27:39 -05:00
shreyas-mastra
ce76df95d5
fix(server): check auth against the custom route that handles the request (#29325) 2026-11-10 09:21:04 -08:00
dane-ai-mastra[bot]
7c4dd88400
chore: version packages (alpha) (#29889)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-11-10 15:48:17 +01:00
Eric Pinzur
2cfa92405b
feat(observability): add shared text search query contracts (#29897)
Adds shared text-search query contracts for Platform integration:
optional `textSearch` on `querySpans()` and `queryTraces()`,
normalization, a 3–256 character limit, and cursor binding. This does
not implement or enable text search in OSS stores.

Adds capability reporting, request forwarding, and unsupported-store
rejection, with generated client types and CLI metadata. Platform search
implementation and rollout flags follow in OBS-867. Delta search is
rejected for now. Public documentation is unchanged; changesets only
describe the contract additions.

Validated with 404 focused tests, 5 type tests, and core/server/client
typechecks. The 228 core query tests were rerun after reducing the limit
to 256. New contract tests also fail against the original
implementation.

Fixes
[OBS-866](https://linear.app/kepler-crm/issue/OBS-866/add-shared-text-search-query-contracts).


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## ELI5
This PR gives span and trace queries a standard way to request text
search. It also lets clients check whether a storage provider supports
that search, so unsupported searches return an error instead of
misleading results.

## Summary
- Add optional `textSearch` to span and trace query contracts. Trim
outer whitespace, convert input to lowercase, and require 3–256 Unicode
code points.
- Bind normalized search text to query cursors. Reject `textSearch` for
delta trace queries.
- Add span and trace text-search capability fields. Default missing
fields to `false` for compatibility with older responses.
- Forward search input to query planners. Return HTTP 501 when the
configured storage provider does not declare support.
- Report text-search capability only when Core can parse the field and
the storage provider declares the matching feature.
- Add tests for validation, normalization, cursor binding, unsupported
stores, and compatibility behavior.

## Validation
Reported test and typecheck results: not available.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-10 15:12:03 +01:00
Ward Peeters
1892f79532
chore: remove stale scripts, workspace entries and package metadata (#29891)
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-10 14:09:52 +01:00
mastra-platform[bot]
3655736ec9
feat(ai-sdk): add reconnectable chat routes (#29549)
## Summary

- add opt-in `chatRoute({ resumable: true })` support for stock AI SDK
`useChat({ resume: true })`
- register the existing POST route plus `GET <path>/:chatId/stream`
- use the AI SDK chat ID as the Mastra thread ID so the GET route can
resolve the active run and resume it through `agent.observe(runId)`
- preserve AI SDK v5/v6/v7 stream conversion, SSE heartbeats, Editor
agent resolution, and resource/thread/FGA checks
- allow route factories to return explicit route arrays while Mastra
normalizes stored server configuration to a flat route list

## Usage

```ts
const routes = chatRoute({
  path: '/chat/:agentId',
  resumable: true,
});

const mastra = new Mastra({
  server: {
    apiRoutes: [routes],
  },
});
```

On the client, standard AI SDK configuration is enough:

```ts
useChat({ resume: true });
```

No custom `DefaultChatTransport` request callbacks or client-managed
Mastra run IDs are required.

## Behavior

With `resumable: true`:

- the POST body chat ID becomes the Mastra memory thread ID
- closing the POST connection detaches the client without aborting the
agent run
- `GET <path>/:chatId/stream` finds the active run for that chat thread,
replays retained events, and follows live output
- unavailable, inaccessible, expired, or finished runs return `204`
- abort-based cancellation through `useChat().stop()` is unavailable
because the server cannot distinguish an intentional stop from refresh,
tab closure, or network loss

Without `resumable: true`, existing behavior is unchanged and the POST
request abort signal still cancels execution.

## Current limitation

Active-run discovery is process-local. Refresh reconnection works while
the original server process still owns the active thread run.
Cross-process discovery requires a separate Core-level shared active-run
registry and is outside this PR.

## Test plan

- `pnpm test src/__tests__/chat-route-resumable.test.ts
src/__tests__/abort-signal.test.ts` — 16/16 passed
- `pnpm test` in `client-sdks/ai-sdk` — 41 files, 345 tests, no type
errors
- `pnpm build:lib` in `client-sdks/ai-sdk`
- `pnpm lint` in `client-sdks/ai-sdk` — 0 warnings/errors
- Prettier and `git diff --check`

Closes #24426. This implements browser-refresh reconnection with stock
`useChat`. Cross-process active-run discovery remains a future
enhancement rather than a requirement for this issue.

---------

Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: Ehindero Israel <iehindero419@stu.ui.edu.ng>
2026-11-10 11:11:19 +01:00
dane-ai-mastra[bot]
6deb16047f
chore: version packages (alpha) (#29719)
This PR was opened by the [Changesets
release](https://github.com/changesets/action) GitHub action. When
you're ready to do a release, you can merge this and publish to npm
yourself or [setup this action to publish
automatically](https://github.com/changesets/action#with-publishing). If
you're not ready to do a release yet, that's fine, whenever you add more
changesets to main, this PR will be updated.

⚠️⚠️⚠️⚠️⚠️⚠️

`main` is currently in **pre mode** so this branch has prereleases
rather than normal releases. If you want to exit prereleases, run
`changeset pre exit` on `main`.

⚠️⚠️⚠️⚠️⚠️⚠️

# Releases

> The changelog information of each package has been omitted from this
message, as the content exceeds the size limit.

## @mastra/slack@1.9.0-alpha.0


## @mastra/factory@0.28.0-alpha.3


## @mastra/code-sdk@1.19.0-alpha.3


## mastracode@0.50.0-alpha.3


## @mastra/observability@1.24.0-alpha.2


## @mastra/core@1.83.0-alpha.3


## @mastra/mcp-apps-components@0.1.0-alpha.3


## @mastra/playground-ui@69.0.0-alpha.4


## @mastra/server@1.83.0-alpha.3


## @mastra/server-adapters-test-suite@0.3.0-alpha.1


## @mastra/platform-workspace@1.13.0-alpha.0


## @mastra/auth-better-auth@1.1.11-alpha.1


## @mastra/client-js@1.60.0-alpha.3


## @mastra/react@1.15.0-alpha.3


## @mastra/deployer-cloud@1.83.0-alpha.3


## @mastra/longmemeval@1.1.42-alpha.3


## @mastra/opencode@0.1.42-alpha.3


## create-factory@0.4.3-alpha.3


## @mastra/arize@1.3.30-alpha.2


## @mastra/arthur@0.4.30-alpha.2


## @mastra/braintrust@1.3.27-alpha.2


## @mastra/datadog@1.4.22-alpha.2


## @mastra/deepeval@0.1.24-alpha.2


## @mastra/laminar@1.3.32-alpha.2


## @mastra/langfuse@1.6.6-alpha.2


## @mastra/langsmith@1.4.3-alpha.2


## @mastra/otel-bridge@1.5.22-alpha.2


## @mastra/otel-exporter@1.5.2-alpha.2


## @mastra/posthog@1.4.7-alpha.2


## @mastra/sentry@1.2.32-alpha.2


## @mastra/agent-builder@1.2.1-alpha.1


## mastra@1.39.0-alpha.3


## @mastra/connect@1.3.2-alpha.2


## @mastra/deployer@1.83.0-alpha.3


## @mastra/editor@0.17.1-alpha.2


## @mastra/fastembed@1.3.7-alpha.0


## @mastra/mcp-docs-server@1.3.13-alpha.6


## @mastra/memory@1.41.1-alpha.1


## @mastra/elysia@0.1.23-alpha.3


## @mastra/express@1.5.27-alpha.3


## @mastra/fastify@1.5.27-alpha.3


## @mastra/hono@1.7.25-alpha.3


## @mastra/koa@1.7.27-alpha.3


## @mastra/nestjs@0.3.0-alpha.3


## @mastra/next@0.2.41-alpha.3


## @mastra/tanstack-start@0.2.41-alpha.3


## @mastra/convex@1.8.1-alpha.0


## @mastra/pg@1.36.0-alpha.2


## @mastra/inngest@1.11.2-alpha.2


## @mastra/temporal@0.6.0-alpha.3


## create-mastra@1.39.0-alpha.3


## @internal/playground@1.39.0-alpha.3

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-11-10 10:33:29 +01:00
mastra-platform[bot]
4854e36419
fix(core, server): stop a peer server from approving an aborted parked durable run (#29799)
> Opened by @user_01KNA8J74D4RF84RXSDRX26BS9

## Problem
A durable agent run that is waiting for tool approval (with no thread)
can be aborted over HTTP. The abort returns `200 {"aborted":true}`, but
that was only recorded in memory on the server that handled the abort.
When the app runs on more than one server, approving the tool call on a
different server still resumed the run and **ran the tool**. When the
abort and approval happened on the same server, the approval was
rejected with a `500` rather than a clear error code. Fixes COR-1518.

## Fix
- **Abort saves the cancellation in storage before it is acknowledged**
(`packages/core/src/agent/durable/durable-agent.ts`):
- Stores that support concurrent updates: a guarded
`updateWorkflowState({ status: 'canceled', expectedStatus: 'suspended'
})`.
- Stores without `updateWorkflowState` (snapshot-only, e.g. LanceDB) and
stores without concurrent updates (e.g. Redis): reread the run, then
rewrite its snapshot as `canceled` with `persistWorkflowSnapshot(...,
expectedStatus: 'suspended')`, keeping `resourceId`.
- Storage errors propagate. The abort does not report success while the
run can still be resumed.
- If a resume has already claimed the run (status `running`), the
guarded write makes no change, and the existing abort of a running run
applies.
- **Resume on any server rejects runs canceled in storage** with
`AGENT_RESUME_ABORTED_RUN`, before it claims the run. The in-flight
resume marker is still taken synchronously before the first `await`
(#27365); the storage check runs right after it and releases the marker
when it rejects the run.
- **Observers of a canceled run are closed on every server**: the abort
that wins the `suspended → canceled` write publishes the abort event
right away on the shared pubsub, so `observe` streams on all servers end
and their history/listeners are cleaned up; the `canceled` row is kept.
If that publish fails, the abort still succeeds (the cancel is stored)
and a later refused approval/resume on that server retries the publish.
- **Docs and changeset**: `docs/.../agents/resumable-streams.mdx` and
`reference/agents/durable-agent.mdx` now point parked runs in
multi-server apps at `POST /agents/:agentId/runs/:runId/abort`, describe
the stored cancellation and the `409 Conflict`
(`AGENT_RESUME_ABORTED_RUN`) refusal, and qualify `abortRunStream` as
process-local. The changeset is scoped to
`DurableAgent`/`createDurableAgent` (evented agents inherit it; Inngest
agents are not covered) and states the best-effort limit on stores
without concurrent updates.
- **Approve route** (`packages/server/src/server/handlers/agents.ts`): a
`canceled` snapshot is treated as final instead of waiting 10s for a
suspension. The resource, thread and agent ownership checks still run
first, so other callers get `403` and learn nothing about the abort.
- **API contract** (`packages/server/src/server/handlers/error.ts`):
`AGENT_RESUME_ABORTED_RUN` now maps to **`409 Conflict`**, joining the
existing resume-claim conflict codes. It used to fall through to a
`500`.

## Proof
**Lifecycle regressions found in review and fixed in this PR** (final
head `1e0af6b5e8`):
1. *Healthy-lifecycle regression* (found by independent review at
`635c8837e3`): after a same-server abort and refused approval, an
attached observer stayed open and the run's history/listeners were
retained, because the `canceled` row skipped the old abort event. Fixed
in `c4cbdb987a`.
2. *Failed-first-publish recovery* (found by independent review at
`c4cbdb987a`): if publishing that abort event failed once, later
refusals never retried it and the observer stayed open. Fixed in
`7a856a33a3`, which also restores the #27365 marker ordering.
3. *Cross-server observer gap* (found by review at `7a856a33a3`): when
the abort and the refused approval landed on different servers,
observers stayed open because only the refusing server's local fence
published the abort event. Fixed in `6d444bee4f` by publishing at abort
time from the cancel winner.
4. *Human review (NikAiyer)*: docs, changeset scope, and a test that
pins the guarded write — addressed in `1e0af6b5e8`.

**Author: in-repo tests at final head `1e0af6b5e8`**
-
`server-adapters/hono/src/__tests__/parked-run-abort-across-servers.test.ts`:
two Hono servers over real TCP. They share a store and cache, and each
has its own pubsub and runtime state. 10/10 pass:
  - No abort, approve on the other server: `200`, tool runs once.
- Abort on the executing server, approve on the other server: `409`,
tool runs 0. **On main this returns 200 and the tool runs once (the
bug).**
- Abort on the other server, approve there: `409`, tool runs 0. Abort
and approve on the executing server: `409`, tool runs 0. On main both
return `500`.
- In all three abort rows, observers attached on **both** servers close
within 2s with exactly one abort frame each. With core from `7a856a33a3`
the executor-abort/other-approve row fails (observers stay open);
removing the abort-time publish makes it fail again.
- Another user's approval of an aborted run gets `403`, and so does
approval through another agent. In both cases the abort is not revealed.
- Race: a run that a resume has already claimed stays `running` after
the abort.
- Race inside the abort: a resume claims the run between the abort's
status read and its guarded write → the abort returns `200
{aborted:false}` and the run stays `running`. Removing `expectedStatus:
'suspended'` from the write makes this test fail.
- Observer: observe → abort → two refused approvals (409, 409) → the
observer closes within 2s, exactly one abort event is published, the row
stays `canceled`, and a peer approval still gets 409 with tool runs 0.
At `635c8837e3` the observer stays open; removing the once-guard
publishes 2.
- Failed first publish: the abort's own publish rejects, then the broker
recovers → the next refused approval on that server republishes → the
observer closes, one abort published, tool runs 0. Removing the
reservation release makes it fail (observer open, 0 published).
- `stores/lance/src/storage/parked-run-abort.test.ts`: real LanceDB with
two peers. After the abort, status is `canceled` and the peer's approval
is rejected with `AGENT_RESUME_ABORTED_RUN`, tool runs 0. Running it
with only the first commit fails with `updateWorkflowState is not
implemented`.
- `packages/server/src/server/handlers/error.test.ts`: 27/27 pass,
including the new 409 mapping.
- Revert checks: undoing the core change brings back `200`/1 tool run;
undoing the error mapping gives `500`; undoing the approve-route change
makes the approval wait out the 10s timeout.

**Author: real Redis, two processes — run on earlier heads
(`635c8837e3`/`c4cbdb987a`/`6d444bee4f`), NOT on the final head
`1e0af6b5e8`; this harness does not check observer closing** (two Node
processes running Hono, each sharing `RedisStore`, `RedisServerCache`
and `RedisStreamsPubSub` on a local Redis 7, using the public HTTP API)
| scenario | abort | approve on peer | tool commits |
|---|---|---|---|
| no abort | n/a | 200 | 1 |
| abort on executing server | 200 `{aborted:true}` | 409
`AGENT_RESUME_ABORTED_RUN` | 0 (main: 200, 1) |
| abort on peer | 200 | 409 `AGENT_RESUME_ABORTED_RUN` | 0 (main: 500,
0) |

**Independent reviewer** (separate session): approved the exact final
head `1e0af6b5e8`, including the `6d444bee4f` runtime change. Hono
10/10, HTTP ownership 4/4, Lance 1/1, resume-claim tests 37, build and
tsc. Failed-first-publish recovery and observer cleanup on both peers
were proven with real-TCP probes. Earlier rounds approved `635c8837e3`
(Lance 1/1, Hono 7/7; a LanceDB abort that returned `500` on the first
commit now returns `200` and the canceled snapshot keeps its other
fields) and `7a856a33a3` (concurrent refusals publish one terminal;
resume-marker release).

**Measured caveat (independent reviewer):** with simultaneous aborts,
the single CAS winner publishes one terminal and that closes the
observers on both servers; each original observer sees exactly one
abort, every approval gets `409`, and the tool runs 0 times. But a
**later** approval on the server whose abort lost the race can publish a
**second** terminal, because the once-guard is a per-instance set; after
cleanup this leaves 1 history entry retained. This PR does **not**
guarantee a globally-once terminal or unconditionally empty history.

Checks: tsc passes for core, server and hono. Lance oxlint is clean.
Prettier is clean on the changed lines; `agents.ts` already fails
Prettier on `main`, and that existing drift is left alone.

## Self-review (board self-review, approved at `635c8837e3`; the later
lifecycle fixes were approved by the independent re-review above)
The run abort route now records the cancellation in shared storage, and
every later resume or approval checks it on any server before anything
runs. A blocked approval returns `409 AGENT_RESUME_ABORTED_RUN`.
Adversarial check: if the resume claims first, the abort's guarded write
fails and the run stays `running` (tested). If the abort writes first,
the resume either sees `canceled` and gets 409, or loses its own claim
and gets the existing claim-lost 409. Authorization runs before the
canceled state is revealed. Nothing blocking was found.

| Check | Result | Tests |
|---|---|---|
| Build `@mastra/hono...` + `@mastra/lance...` | ✅ | — |
| Hono two-server HTTP (`parked-run-abort-across-servers.test.ts`) | ✅ |
7/7 |
| LanceDB parked abort (`parked-run-abort.test.ts`) | ✅ | 1/1, plus 8
reruns including under CPU load (1 early failure that could not be
reproduced) |
| Server error mapping (`error.test.ts`) | ✅ | 27/27 |
| Core durable suite (both storage projects, type-check on) | ❌ | 3966
passed, 1 failed, 4 skipped; no type errors |
| That failing file rerun on its own
(`durable-agent-tool-call-resumed.test.ts`) | ✅ | 30/30 |

Not run by self-review: a revert of the production files to re-run the
Hono test against the old code (Linear's main repro stands in for it,
and the author's revert checks above cover it); a real two-process Redis
run (covered by the author's harness above); repo-wide lint/format.

## Unverified
- The full Hono adapter suite was not run to completion.
- In the core durable suite, `durable-agent-tool-call-resumed.test.ts >
applies the display transform…` failed once with
`AGENT_RESUME_ALREADY_CLAIMED` and passed when run on its own. It looks
like test-isolation contention, not a confirmed cause. Separately,
`durable-agent-crash-recovery.test.ts` runs out of memory on `main` too.
- The Redis two-process harness was not run on the final head, and it
does not check observer closing; the cross-server observer tests use an
in-process shared-emitter pubsub, not Redis.
- A truly concurrent abort and approval on stores without concurrent
updates was not tested.

## Risk
- On stores without concurrent updates (Redis, Valkey, Elasticsearch,
LanceDB, ClickHouse, Cloudflare KV/DO), the canceled write is
**best-effort, not atomic**: the status is checked and then the snapshot
rewritten. An approval that lands between the two can still go ahead.
This PR does **not** guarantee that a racing abort and approval resolve
cleanly on every store; it guarantees that an abort that has already
completed is honored on every server. No new `supportsConcurrentUpdates`
requirement is added.
- The abort-event dedupe is per process and bounded (1000 run ids). It
is not global: see the measured caveat above (a later approval on the
losing-abort peer can publish a second terminal and retain one history
entry).
- A failed abort-time publish is retried only by a later refused request
on the aborting server; a peer's refusal does not retry it, and there is
no background retry.
- Aborted parked runs now keep a `canceled` row instead of a `suspended`
one.
- The thread abort route (`__abortThreadStreamAcrossProcesses`) does not
write the storage fence. That is out of COR-1518's scope.
- An abort that arrives while the run is still executing and parks just
afterwards keeps the existing behavior.
- `AGENT_RESUME_ABORTED_RUN` is also thrown by the non-durable `Agent`,
which now also gets `409` instead of `500`.



<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## ELI5

When a run pauses for tool approval, canceling it now records that
decision so another server cannot approve the run and start the tool.
This helps prevent canceled work from continuing elsewhere.

## Summary

- Persist cancellation for parked `DurableAgent` runs before confirming
the abort. Use a guarded status update when the storage adapter supports
concurrent updates. Otherwise, save the updated snapshot. On adapters
without concurrent updates, an approval that overlaps the save may still
proceed.
- Reject approval or resume attempts for canceled runs with
`AGENT_RESUME_ABORTED_RUN`. Check ownership before returning `409
Conflict`.
- Publish an abort event after cancellation so observers can close. If
publication fails, a later refused resume can retry it.
- Add cross-server integration tests and a LanceDB regression test.
Update the documentation to describe the behavior and clarify that it
applies to `DurableAgent`, not Inngest agents.

## Validation

Reported final-head results: the Hono two-server test passed 10/10, the
LanceDB test passed 1/1, and the server error-mapping test passed 27/27.
Core, server, and Hono type checks passed. The core durable suite
reported 3,966 passed and 1 failed; the failed test passed when rerun
alone. The full Hono suite was not completed. The Redis two-process
harness ran on earlier heads, not the final head. Repository-wide lint
and format results are not available.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-09 20:49:41 -08:00
mastra-platform[bot]
8a10dfe648
fix(core): allow authorized finished durable replay across servers (#29791)
## Summary

Fix finished `DurableAgent` and evented-agent output replay returning
404 on a different server while the executing server can still replay
the same retained output.

- Publish shared, read-only replay ownership before execution starts;
remove it alongside replay-history cleanup.
- Consult that ownership only for observation when persisted workflow
ownership is missing. Explicit denials and unverifiable workflow rows
remain authoritative, and existing resource, RequestContext, thread and
FGA checks still apply.
- Keep abort/write authorization separate: replay ownership never
permits stopping a finished run.
- Add real-TCP Hono regressions for durable/evented replay, ownership
denial, thread-read denial, anonymous access, finished abort, unknown
runs and post-cleanup 404; include core/server patch changesets.

Fixes COR-1512. Independent branch from main; no COR-1518 cancellation
or COR-1517 snapshot changes.

## Proof

Reviewed candidate: `c412839fb8`, based on
`6bc7614a8f`.

Author verification:
- Real local Redis, two HTTP processes: baseline owner replay was 200 on
executor / 404 on peer for durable and evented agents; candidate returns
200 / 200. Foreign users receive 403 / 403, anonymous callers 401 / 401,
and both servers return 404 after cleanup. Finished abort remains `{
aborted: false }`. The Redis ownership key is present during the replay
window and removed after cleanup.
- Reverting the production changes makes both committed durable/evented
regressions fail with peer 404.
- Core/server/Hono typechecks, changed-file lint/format, 290 server
agent tests, full Hono suite and 62 affected durable test files passed.

Independent exact-head review:
- Fresh core/server builds and core build typecheck passed; verified
candidate module resolution rather than stale distributions.
- 381 committed tests passed: 8 TCP replay/access tests, 315 server
ownership/agent tests and 58 focused core lifecycle/cleanup tests.
- Additional handler-level probes verified RequestContext-dependent
memory, denied/unverified workflow rows never consulting shared
ownership, cache-read failure returning 503, WRITE never using replay
ownership, and owner-publication failure preserving live completion
while remote access fails closed.

## Unverified

- The committed TCP tests share in-memory objects within one process.
The author's two-process Redis harness is uncommitted and was not
independently rerun; Redis results above are author evidence, not
independent proof.
- No hosted Redis, cluster/TLS/failover, load, browser, full-repository
CI or real Inngest replay qualification. The separate Inngest proxy does
not acquire the new replay-owner capability in this patch.
- Fresh GitHub CI and maintainer review remain pending.

## Risk

Adds one bounded shared ownership record per durable run. Its TTL is 24
hours; normal deletion follows existing replay cleanup and ownership
guards. Cleanup remains best effort/asynchronous, not a transaction
promising retention under backend failure. Cache expiry/eviction can
shorten access, and failed owner publication can leave peer replay
unavailable while the initiating response succeeds. Existing
unique-run-ID requirements remain unchanged; this is not a new
namespace, reuse protocol, durable event log or write/cancellation
authority.

Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-11-09 12:32:03 -08:00