mirror of
https://github.com/mastra-ai/mastra.git
synced 2026-11-17 08:44:46 +00:00
14,145 commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
d60ba71be0 | chore: version - exit prerelease mode | ||
|
|
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> |
||
|
|
18168d518c |
feat(playground): show the built-in MCP server in Studio (#29932)
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com> |
||
|
|
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> |
||
|
|
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>
|
||
|
|
4fcc168fa1 |
fix(core): honor agent pubsub for durable thread coordination (#30215)
DurableAgent currently falls back to the Mastra pubsub for thread
coordination even when its wrapped Agent has a custom bus. Replicas
sharing only the Agent bus cannot consistently discover active runs,
receive thread updates, coordinate leases, or send Stop requests.
Delegate coordination pubsub resolution to the wrapped Agent and retain
injected coordination buses on Agent forks, without treating a
Mastra-inherited bus as owned configuration. The durable-option bus
remains independently configured for run-frame transport. For example,
`createDurableAgent({ agent: new Agent({ ...config, pubsub: sharedBus })
})` now uses `sharedBus` for thread coordination before and after
registration and forking.
Added regression coverage using independent Mastra instances and a
shared Agent bus for run visibility, subscriptions, leases and release,
remote Stop, fork behavior, and bus precedence. Updated the existing
queued-cancellation fixture to wait for visible output so it tests
queued cancellation rather than silent-model interruption. Includes an
@mastra/core patch changeset.
Verification: 110 tests passed across 11 Vitest project/file executions
covering seven source test files. Core `tsc --noEmit`, type-aware oxlint
(zero warnings/errors), formatting, and `git diff --check` passed.
Timing-sensitive coordination and cancellation cases passed 20
consecutive runs. Negative control: temporarily removing both production
fixes caused six of nine shared-bus regression tests to fail; both fixes
were restored before the final passing run.
Fixes #29882
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->
## ELI5
When an agent runs on several servers, the servers must share one
message bus for thread updates. Before this change, a durable agent used
a local bus for thread updates, so servers did not see each other's runs
or Stop requests. This change makes the durable agent use the agent's
own shared bus for thread updates.
## Overview
This change makes a `DurableAgent` use the wrapped Agent's pubsub for
durable thread coordination. Thread coordination covers run discovery,
thread subscriptions, thread leases, Stop requests, and notification
signals. Before this change, these operations called `getPubSub()` on
the durable wrapper. The wrapper did not override that method, so it
fell back to `mastra.pubsub`. That bus is in-process when no
Mastra-level pubsub is set.
Durable run frames still use `DurableAgentConfig.pubsub`. This change
does not alter that path.
## Changes
- `packages/core/src/agent/durable/durable-agent.ts`:
`DurableAgent.getPubSub()` now returns the wrapped agent's pubsub. The
setter documentation no longer states that the inherited `getPubSub()`
returns the wrapper's own stored pubsub. Memory and workspace setters
still forward to both instances.
- `packages/core/src/agent/agent.ts`: `Agent.__fork()` copies the source
agent's inherited pubsub reference to the fork. A fork keeps an injected
coordination bus.
-
`packages/core/src/agent/streams/__tests__/durable-shared-bus.test.ts`:
Adds parameterized tests for thread-run coordination, leases,
subscriptions, and Stop across agent buses. The tests run with and
without shared stream frames and forks. The tests also cover owned,
injected, and Mastra-provided coordination buses for plain and durable
agent forks. The `setup` helper gives Mastra instance B a separate bus
when an agent pubsub is supplied.
-
`packages/core/src/agent/durable/__tests__/durable-agent-abort.test.ts`:
`createAbortableModel` accepts optional response text and emits it as a
`text-delta` before it waits for abort. The remote-cancellation test
waits for that output before it queues and cancels input. This separates
queued cancellation from interruption of a silent model.
- `.changeset/big-zoos-call.md`: Adds a patch changeset for
`@mastra/core`.
## Scope
- 5 files changed, 115 lines added, 8 lines removed.
- No exported or public declarations changed.
## Verification
- The PR description reports 110 passing tests across 11 Vitest
executions. It also reports passing Core `tsc --noEmit`, type-aware
oxlint, formatting, and `git diff --check`. These results come from the
author's report. They were not confirmed from completed checks on the
current head.
- The author reports that a negative control with both production fixes
removed made six of nine shared-bus regression tests fail.
- Review severity counts: not available. No current review findings were
supplied.
## Linked issue
Issue `#29882` reports that thread topics stay in-process when a durable
Agent has a shared cross-process pubsub. This change addresses the issue
by making `DurableAgent.getPubSub()` delegate to the wrapped agent and
by preserving injected buses on `__fork()`. The issue also asks that
durable run frames stay separate from thread coordination. The diff
keeps `DurableAgentConfig.pubsub` for run frames. The change does not
add the internal `registered.__setPubSub(T)` workaround that the issue
rejects.
<!-- 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>
|
||
|
|
e58a7d5cd6 |
fix(core): keep a forwarded queued message until the owning run accepts it (#29142)
## What was broken When a process drains a queued message (`queueMessage`) while a run in another process holds the thread lease, it forwards the message to that run as `signal-enqueued` and forgets about it. If that run has already finished locally, the owner drops the forward at the `answersTo(runId)` check. No run picks the message up, and the caller has already been told it was queued, so the message is lost without any error. A 10 ms pause after every memory save in `MessageHistory` has been hiding this race. With that pause shortened to 0–1 ms, three `signals-pending-cancellation` cases lose the queued message on every run. ## What this changes - The follower now keeps a forwarded user message until the owning run admits it. The owner already announces admission as a `pending` user-message presentation, so there is no wire change. - If the run it was forwarded to completes, fails or is discarded without admitting it, the message goes back to the front of the idle queue and is drained again, taking the lease over from the ended run. - If the owner disappears without publishing a run-end event, the follower reads the lease every renewal interval while anything is held. After two consecutive checks in which the lease no longer names that run, it requeues the message. - Held messages count toward the queued-message count, and thread-level and by-id cancels clear them, so a cancelled message can't come back after the owner ends. - A stopped (aborted) run is deliberately not requeued: it still admits until its stream ends, and requeueing there ran the message twice. - Entries are keyed by the run id the owner resolves the address to (`forwardedSignalRunId`), so legacy retake lease tokens match. - Non-user signals keep the old forward-only behaviour. The 10 ms pause stays in this PR. Removing it exposes a separate createdAt tie, which a follow-up PR will fix. ## Known limits - If the owner admits the message but its `pending` presentation is lost and the run then ends, the message can run twice. - A crashed owner's forwarded message runs about two lease renewal intervals after the lease expires. ## Tests - `signals-pending-cancellation.test.ts`, new describe "follower idle message forwarded to a run that has already ended". It covers: requeue when the run ends without admitting; a stopped run runs the message exactly once; cancel while held; lease lost without a run-end event. - `signals-drain-handoff.test.ts` "removes observed messages after lease acquisition failure" pinned the bug: it asserted the message never ran. It now expects the message to run once after the lease is released. ## Test plan - [x] With main's runtime and the new tests: 2 of 123 fail on every run (3 runs). With this fix: 123/123 on all 3 runs. - [x] Full `@mastra/core` unit run: 26,439 tests, 0 failed. - [x] `tsc --noEmit` for core: 0 errors. oxlint clean. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## ELI5 A message sent to a run in another process should not disappear if that run cannot accept it. This change keeps the message queued and tries again if the run ends before accepting it. ## Summary - Keep forwarded user messages until the owning run accepts them. - If the run ends, fails, or is discarded before admission, return the message to the front of the idle queue. With a lease provider, requeue after two consecutive checks show that the lease no longer names the target run. - Count held messages in the queue total and support cancellation while they are held. - Do not requeue messages when the owning run stops. Keep non-user signals on their existing forwarding path. - During a takeover, keep messages held for lease checks when the follower did not register the successor. This avoids immediate requeueing that could cause duplicate execution. - Update tests for run endings, lease loss, cancellation, queue counts, and lease handoff. The author reports two limits: a message may run twice if its pending presentation is lost before the run ends, and recovery after an owner crash may take about two lease-renewal intervals. The 10 ms pause after memory saves remains because removing it exposes a separate `createdAt` tie. ## Tests The author reports that 123/123 targeted tests passed on each of three runs, 26,439 `@mastra/core` unit tests passed with no failures, `tsc --noEmit` reported no errors, and oxlint was clean. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: remy-builder[bot] <324360501+remy-builder[bot]@users.noreply.github.com> |
||
|
|
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> |
||
|
|
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> |
||
|
|
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> |
||
|
|
5ff479a34b |
fix(inngest): stop steps on every worker at the total deadline (#29002)
## Checks on ` |
||
|
|
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>
|
||
|
|
0b24f9cdb0 |
perf(core): read only stored run status when checking parked runs (#30175)
## Summary
Thread subscribers decide whether a remote or replayed run is still
parked by reading its stored status. They used `getWorkflowRunById`,
which loads the whole run snapshot (often 1–40 MB) into Node just to
read `status`. They now use `loadWorkflowRunStatus`, which returns only
the status for v1 and v2 rows.
On Shipyard, pg_stat_statements showed ~18.4k of these full-run reads
(~576 kB avg, 865 s DB time) since the last stats reset, contributing to
GC pressure and event-loop lag.
## Test plan
- New test in `thread-stream-stored-run-state.test.ts` asserts
status-only reads; fails on main, passes here
- `src/agent/__tests__`: 2414 passed
- agent-controller + thread-stream suites: 1064 passed
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->
**ELI5:** When the system checks whether a paused agent run is still
waiting, it now reads only the run's status. Before, it loaded the whole
saved run record, which could be several megabytes. Each check now uses
less database work and less memory.
## Summary
This change reduces the data read when a thread subscriber checks
whether a remote or replayed run is parked. In
`AgentThreadStreamRuntime.#readStoredRunStatus`
(`packages/core/src/agent/thread-stream-runtime.ts`), the method now
calls `workflowsStore.loadWorkflowRunStatus({ runId, workflowName })`
instead of `workflowsStore.getWorkflowRunById`. The full run snapshot is
no longer fetched or parsed.
### Behavior changes in `#readStoredRunStatus`
- The method checks the same workflow names in the same order.
- It returns the first string status it finds.
- If no workflow name returns a string status, it returns `'missing'`.
- The `catch` block is unchanged. The diff does not show what it
returns.
- Before, the first run found returned its snapshot status immediately,
even when that status was not a string. Now the loop moves to the next
workflow name when the status is not a string. This changes the return
value when no name yields a string status: the method returns
`'missing'`.
### Other changes
- `.changeset/stored-run-status-only.md` is a new file. It adds a
`patch` entry for `@mastra/core`. The entry states that memory use and
garbage-collection pauses drop for thread subscribers on adapters that
support a status-only read. Adapters without that read still load the
snapshot.
-
`packages/core/src/agent/__tests__/thread-stream-stored-run-state.test.ts`
adds one test, "reads only the stored run status, not the whole run
snapshot". It spies on `loadWorkflowRunStatus` and `getWorkflowRunById`
during a lease-lapse scenario. It asserts that the status method is
called and that the full-run method is not.
### Diff size
- 3 files changed, 23 lines added, 4 lines removed.
### Not verified
- The PR objectives report production figures: about 18.4k full-run
reads, a 576 kB average, and 865 seconds of database time. The diff does
not check these.
- The PR objectives report test results: the new test fails on `main`,
2,414 tests pass in `src/agent/__tests__`, and 1,064 tests pass across
the agent-controller and thread-stream suites. No test run output is
available, so these results are not available.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
---------
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
|
||
|
|
8d4abc4f88 |
chore(deps): Vanta 2026-11-12 — raise undici to 8.12.4 / 7.30.2 (#30205) | ||
|
|
79ff445aca |
fix(rag): reject JSON chunk sizes that stall string splitting (#30186)
## Summary - Require JSON chunk `maxSize` of at least 21 in strategy validation and direct transformer construction, preventing zero-length string splits from stalling chunking. - Add regressions for invalid integer and fractional limits and verify long strings reconstruct at the supported boundary. - Include a patch changeset for `@mastra/rag`. ## Test plan - `cd packages/rag && ./node_modules/.bin/vitest run src/document/document.test.ts --reporter=dot` (167 passed) - `./node_modules/.bin/tsc --noEmit -p packages/rag/tsconfig.json` - Type-aware oxlint for changed files; Prettier check; `git diff --check` Fixes #30166 <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> **ELI5:** The JSON text splitter could get stuck in an endless loop when a user set a small chunk size. This change rejects those small sizes with a clear error, so the splitter never hangs. ## Summary This change stops JSON chunking from hanging when `maxSize` is too small. The splitter subtracts a fixed overhead of 20 from `maxSize` and floors the result. At `maxSize` 20, the split point is zero. The splitter then never consumes input. Fractional values between 20 and 21 have the same problem. The change sets a minimum JSON `maxSize` of 21. It applies this minimum in two places: - **Option validation** (`packages/rag/src/document/validation.ts`): The JSON chunk options schema adds an optional `maxSize` field. It accepts the field only when the value is at least 21. - **Transformer constructor** (`packages/rag/src/document/transformers/json.ts`): `RecursiveJsonTransformer` throws a `RangeError` when `maxSize` is not finite or is below 21. Other chunking strategies keep their existing size rules. ### Documentation - `docs/src/content/en/reference/rag/chunk.mdx` states that the JSON strategy's `maxSize` is a target maximum for each chunk. It must be at least 21. Long values nested in objects can exceed it. - A patch changeset for `@mastra/rag` describes the new minimum. ### Tests (`packages/rag/src/document/document.test.ts`) - Adds cases that expect `maxSize` values `0.5`, `20`, and `20.9` to be rejected. The cases cover both `MDocument.chunk` and direct transformer construction. The expected error matches `maxSize.*21`. - Adds a case that splits a 100-character JSON string with `maxSize: 21`. The test checks that the output has multiple chunks. It also checks that the parsed string values rejoin to the original text. ### Behavior change Callers that pass a JSON `maxSize` below 21 now receive a configuration error. Before this change, those calls were accepted and could hang. Default JSON chunking remains valid. ### Reported validation (not verified in this summary) The PR description reports these checks: - `vitest run src/document/document.test.ts`: 167 passed. - `tsc --noEmit` for `packages/rag`. - Type-aware oxlint on changed files, Prettier check, and `git diff --check`. Diff size: 5 files changed, 38 lines added, 1 line removed. <!-- 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> |
||
|
|
da717f489c |
Fix GraphRAG leaking documents across reused tool requests (#30185)
## Summary - Rebuild the GraphRAG graph from each request’s retrieval results so tenant-specific indexes cannot reuse a previous request’s documents. - Return empty context and sources when retrieval yields no candidates. - Add a real LibSQL and embedding-server regression covering sequential, empty, and concurrent requests, plus a patch changeset. ## Test plan - `pnpm build:rag` - `pnpm test:rag` (454 tests) - `pnpm exec tsc --noEmit -p packages/rag/tsconfig.json` - `pnpm --filter ./packages/rag lint` - `pnpm exec prettier --check packages/rag/src/tools/graph-rag.ts packages/rag/src/tools/graph-rag-isolation.test.ts .changeset/graph-rag-request-isolation.md` Fixes #30168 <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> **ELI5:** A search helper that is reused can return a document from an earlier user's search. This change makes the helper build its answer only from the current search. Each request now gets results for its own search. ## Summary This change fixes a data-isolation defect in the GraphRAG tool that `createGraphRAGTool` creates in `@mastra/rag`. Linked issue `#30168` reports the defect. The tool kept one `GraphRAG` instance and an `isInitialized` flag across executions. Later requests that selected a different index could still receive documents from the first execution. ## Changes - `packages/rag/src/tools/graph-rag.ts` (+32/-37): - Removes the `GraphRAG` instance and the initialization flag that persisted across executions. - Returns empty context and sources when vector search finds no candidates. - Otherwise, builds a new graph from that execution's retrieved chunks and embeddings, then traverses it. - Keeps graph-build logging, tracing, and error propagation. - `packages/rag/src/tools/graph-rag-isolation.test.ts` (+84/-0): Adds a Vitest integration test. The test uses tenant-specific and empty vector indexes. It serves an `LLMock` through a local HTTP proxy. It checks that: - A request returns only the document from its selected index. - An empty index returns empty results. - Concurrent requests stay isolated. - `.changeset/graph-rag-request-isolation.md` (+5/-0): Declares a patch release for `@mastra/rag`. - `docs/src/content/en/reference/rag/graph-rag-guide.mdx` (+1/-1): States that each graph query tool execution builds its graph from that request's retrieved chunks. The guide no longer says that later queries reuse the first execution's graph. No exported or public declarations change. ## Tradeoff Each execution now builds a graph. The linked issue states that this adds work per request. The request-specific candidates require this work. A future cache would need correct candidate and scope keys. ## Verification Not available. The PR lists planned checks: `pnpm build:rag`, `pnpm test:rag`, a TypeScript check, lint, and a Prettier check. No completed results for these checks were supplied. <!-- 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> |
||
|
|
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> |
||
|
|
5251e7199e |
Fix atomic pubsub replay writes on Redis Cluster (#30174)
> Opened by @abhiaiyer91
## Summary
- Preserve existing `CachingPubSub` replay keys by default, so upgrading
does not make in-flight logs unreadable for other cache backends or
Redis standalone.
- Add `keyFormat: 'redis-cluster'` as an explicit option for new Redis
Cluster deployments. It encodes the topic into a hash tag shared by the
replay list and counter, allowing the atomic Redis Lua append instead of
the `CROSSSLOT` fallback. PubSub topic names remain unchanged.
- Retain the Redis cache fallback for callers that still supply untagged
keys; add coverage for both key formats and edge-case topics.
## Usage
Pass `{ keyFormat: 'redis-cluster' }` as the third argument to `new
CachingPubSub(innerPubSub, redisServerCache, options)` on **all workers
sharing the same cache**. Roll it out for new logs, or after existing
replay logs expire. The default remains the original
`${keyPrefix}${topic}` format; opt-in keys use
`${keyPrefix}{${encodeURIComponent(topic)}}` (with `%EMPTY` for an empty
topic).
## Test plan
- Seven focused core suites: 169 tests passed, with no type errors; core
build/type generation and targeted oxlint passed.
- Convex cache suite: 21 tests passed with original key expectations.
- Redis Docker Compose integration: 14 tests passed.
- Real slot-assigned Redis Cluster: confirmed untagged two-key `EVAL`
fails with `CROSSSLOT`; opted-in replay successfully publishes and reads
indexes 0–2.
Fixes #30149
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->
ELI5: Redis Cluster sometimes refuses to run one command that touches
two related cache keys. This PR puts those keys in the same place, so
the command works and event indexes stay in order.
## Summary
This PR changes `CachingPubSub` so that a topic's replay list and its
index counter share a Redis Cluster hash tag.
`RedisServerCache.listPushIndexed` can then run its Lua script on both
keys without a `CROSSSLOT` error.
## Changes
- **`packages/core/src/events/caching-pubsub.ts`**
- Adds an optional `keyFormat?: 'redis-cluster'` option. The default is
`'legacy'`.
- Legacy mode keeps the list key as `keyPrefix + topic`.
- `redis-cluster` mode builds the list key as `keyPrefix + {tag}`. The
tag is `encodeURIComponent(topic)`, or `%EMPTY` when that value is
empty.
- The counter key is now `<list key>:counter`. In `redis-cluster` mode,
it uses the same hash tag as the list key.
- **`stores/redis/src/cache.ts`**
- Updates the comment on the `CROSSSLOT` fallback. The fallback logic is
unchanged. Untagged keys can still trigger `CROSSSLOT`, so the fallback
remains for callers that do not use tagged keys.
- **`.changeset/redis-cluster-atomic-pubsub-replay.md`**
- Adds a patch changeset for `@mastra/core`.
## Behavior and compatibility
- Topic names used for publishing are unchanged.
- The default `legacy` format keeps existing replay keys. Existing logs
stay readable with the default setting.
- Opting into `keyFormat: 'redis-cluster'` changes replay key names.
Workers that use the new format cannot read logs written under the old
names until those logs expire by TTL.
## Scope limits
- The change co-locates only the replay list and counter for each topic.
It does not co-locate those keys with transport streams or other keys
for the same run.
- The change does not add a new default for `keyFormat`.
## Tests and checks
- The diff adds no test file. The PR objectives report test runs, but
this summary does not verify them.
<!-- 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>
|
||
|
|
6ad8e7eb9d |
feat(ui): one settings layout across Studio, Factory and Platform (#29400)
## Description Settings pages in Studio, Factory and Platform each had their own layout: different widths, section headers with buttons, add rows at the bottom of lists, fields starting at different x positions. This gives all three one layout, built from reusable Playground UI components: - A 640px page column with the title above the sections. - Each section is a dimmed title above one borderless card. The card owns all row spacing (14px padding, inset hairlines), so rows carry no padding of their own. - Settings rows: label and description on the left, control on the right. Text fields share one width, selects hug their value up to that width, switches and buttons keep their size. - Lists: a count and the list's action in a header row at the top of the card, one empty row (text plus the same action) when there's nothing in it, and `SettingsItem` rows with one icon tile size, so every list lines up. - Input, InputGroup and select values use the regular-weight `text-body-sm`, like Textarea. This is the Playground UI, Studio and Factory half. The Platform half, mastra-ai/platform#4174, pins a snapshot of this branch. ## Before / After Every settings page in Studio and Factory, `origin/main` on the left and this branch on the right (1440×1800, dark). Platform's pages are in mastra-ai/platform#4174. | Before | After | | --- | --- | | <br>Studio · Settings | <br>Studio · Settings | | <br>Factory · My account | <br>Factory · My account | | <br>Factory · Preferences | <br>Factory · Preferences | | <br>Factory · Connections | <br>Factory · Connections | | <br>Factory · Models | <br>Factory · Models | | <br>Factory · Memory | <br>Factory · Memory | | <br>Factory · Skills | <br>Factory · Skills | | <br>Factory · Tools | <br>Factory · Tools | | <br>Factory · Behavior | <br>Factory · Behavior | | <br>Factory · Repositories | <br>Factory · Repositories | | <br>Factory · Work Intake | <br>Factory · Work Intake | | <br>Factory · Work board | <br>Factory · Work board | | <br>Factory · Manage Factory | <br>Factory · Manage Factory | One loading state everywhere (`SettingsSkeleton`, New/Settings Loading story), built from the real rows and list items:  ## What changed Playground UI (`@mastra/playground-ui/new/settings`): - `SettingsLayout`: the page column and title (`header` for an app's own header). - `SettingsTitle`: dimmed, inset to the card; `info` keeps a section description as a tooltip. - `SettingsContainer`: the card, owning row spacing. Rows with nothing in them take no space, so a list can always render its notice row. - `SettingsRow` / `SettingsFieldsetRow`: control column with shared field width; selects hug (`fieldTriggerWidthStyle` reads `--field-max-width`). With `controlPlacement="below"` the control fills the row. - New `SettingsListHeader`, `SettingsEmptyRow` (now takes an `action`), `SettingsItem`, `SettingsItemIcon`. `SettingsNoticeRow` stays. - New `SettingsSkeleton`: the one loading state for settings, placeholder rows (`variant="row"`) or list items (`variant="item"`) inside the same card. - Removed `SettingsAddRow` and `SettingsContainer`'s `variant`. `Section`'s deprecated rows keep their old look on their own code. Studio: the settings page uses `SettingsLayout` with its title in the column. URL, API prefix and request headers are one "Mastra connection" card. They only work as a set, so edits stay a draft: an "Unsaved changes · Discard · Save changes" row shows up once something changed, and saving applies all of it at once. This replaces "Save configuration", which sat under the headers and read as saving only them. The first-run connect screen keeps its own form. `@mastra/react`: `useAuthCapabilities` and `usePermissionPatterns` keep their last result while a new client loads (`keepPreviousData`). Before, every connection change gave them a new query key, and the auth and permission guards showed a full-page spinner until it answered, so the page went blank on each save. Factory: every settings page is on the shared components. Section stacks are fragments under `SettingsLayout`, lists with an action use the header or empty row (repositories, custom providers, speech-to-text keys, Connect, intake pickers), and logo and icon rows are `SettingsItem`s. Factory's own `SettingsAddRow`, `SettingsActionRow`, `SettingsSectionHeader` and `SettingsRowsSkeleton` are gone. Every settings loading state is `SettingsSkeleton` (Skills used to show plain "Loading skills…" text). Models keeps its routing diagram; its lane and defaults cards use the borderless settings surface. Work board keeps its form layout. Memory is split into Personal memory and Factory memory, and Build history is its own section. ## Testing 1. `mdev up storybook`: New/Settings, Page, Controls and Loading stories. 2. `mdev up studio`, open Settings: change the URL, prefix or a header and the unsaved row appears; Discard restores; Save applies everything without the page going blank. Change the theme. 3. Factory settings: every section, especially Models. Playground UI, Studio and Factory typecheck clean; the settings, Studio connection, Factory settings and Models tests pass, and CI is green. Not seen locally: a loading state on screen (they resolve too fast), Models with providers connected, and Factory's Memory form (no models in the local org). ## Related issue(s) Fixes PLTFRM-3135 ## Type of change - [ ] Bug fix (non-breaking change that fixes an issue) - [x] 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 - [ ] 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 <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## ELI5 This PR makes settings pages in Playground UI, Studio, and Factory use a more consistent layout. It adds shared building blocks so settings and lists are easier to organize and read. ## Summary - Add shared settings components in Playground UI, including a centered 640px layout, consistent containers and rows, list headers, empty and notice rows, and settings items. - Update the Playground settings page and Studio connection form to use the shared layout. Add `CopyInput` for read-only values with a copy action. - Update Factory settings, workspace, and connection views to use the shared components. Separate Personal memory and Factory memory, and give Build history its own section. - Remove older layout helpers, including `SettingsAddRow`, `SettingsSectionHeader`, and the settings container variant. - Add or update component tests and Storybook examples for the new settings patterns. **Checks:** not available. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
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`]( |
||
|
|
72abae68eb |
feat(observability): export span-local originating error counts (#30088)
## Description Export `errorCount` as failures originating directly on each span. Child failures forwarded through a model step, workflow or agent add no parent count; independent parent failures do. Failed retries remain counted after recovery, and replay does not create new occurrences. No parent/child totals or suspend/resume rollup are maintained. Attribution stays in a WeakMap without modifying user errors. Explicit internal serializers and Inngest memoized operations preserve provenance across boundaries; public workflow results and stored workflow state omit transport metadata. Failures before child execution count on their actual originating span. Excluded spans preserve attribution so their failures cannot be misassigned to visible parents, but excluded failures are absent from exported totals. Retry context stays in the server-only context module, while shared origin utilities use global crypto. Guarded cross-package calls preserve mixed-version startup compatibility. Unsupported accounting and older snapshots remain unknown. Error-free spans do not allocate occurrence sets. Validation: 117 focused observability/workflow/compatibility tests, 23 real Inngest error/retry scenarios and 37 Inngest engine/nested-result checks pass. New regressions reproduced resolver undercounting, excluded-child misattribution and public transport-field leakage before the fixes. Real Inngest tests cover an empty execution graph, unavailable remote child, instrumented child errors, nested propagation, retries, public responses and stored state. Core/observability build, Inngest typecheck, changed-file type-aware lint and CI formatting checks pass. The preceding merge also passed 167 core checks and redaction integration coverage. Playground production builds were verified on Node 24. Docs checks with Vale report no errors (three warnings on unchanged API headings); the CI Vale configuration passes. Standalone observability `tsc` previously reported generic union-call errors in untouched `workflow-control-flow-suite.ts`; package builds and focused tests pass. No production rollout or query-table changes. CI reruns on the new head. ## Related issue(s) Fixes https://linear.app/kepler-crm/issue/OBS-901 Follow-ups: https://linear.app/kepler-crm/issue/OBS-902 and https://linear.app/kepler-crm/issue/OBS-903 Nonblocking review follow-up: https://linear.app/kepler-crm/issue/OBS-905 tracks explicit propagated classification on previously untagged errors and reuse of one Error object across separate foreach iterations. Changesets intentionally remain single sentences per maintainer direction. ## Type of change - [x] New feature (non-breaking change that adds functionality) - [x] Documentation update - [x] Test update ## Checklist - [x] I have linked the related issue(s) in the description above - [x] 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 <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## ELI5 This change counts each error on the span where it first happened. It keeps the count correct when errors are wrapped, retried, or rebuilt, so one failure is not counted twice. ## Summary - Adds span-local `errorCount` to exported spans. The count covers failures that start directly on that span. - Adds `claimSpanError`, `BaseSpan.recordError`, and `BaseSpan.restoreErrorCount`. Each claim records one occurrence ID on the span. - Ignores propagated failures on the receiving span. Propagated failures count only on their origin span. - Keeps error origin through cause chains, durable tool serialization, and event codecs. - Stores origin metadata in a `WeakMap` for live errors and formatted results. Omits it from public workflow JSON. - Stores occurrence IDs in span snapshots. Rebuilt spans restore them, so replayed attempts are not counted again. - Records failed attempts for default, evented, and Inngest workflow retries. Each attempt uses an attempt-scoped occurrence ID. - Reports `errorCount` as unknown when the runtime lacks the claim API or when an older snapshot has no accounting history. - Updates tracing types, the span record schema description, the span reference documentation, and changesets for `@mastra/core`, `@mastra/observability`, `@mastra/client-js`, and `@mastra/inngest`. - Adds tests for repeated reports, retry scopes, concurrent async spans, excluded children, cause-linked errors, tool and agent spans, rebuilt and legacy snapshots, codecs, durable serialization, workflow retries, and ESM/CJS compatibility with an older core build. ## Scope - Parent and child totals are not computed. - Suspend and resume rollups are not computed. - Query-time summation, display, filtering, sorting, and aggregate-table integration are not included. These are tracked in [OBS-902](https://linear.app/kepler-crm/issue/OBS-902) and [OBS-903](https://linear.app/kepler-crm/issue/OBS-903). - Counts reflect observed exported failures only. Filtering, sampling, or loss before export can leave counts incomplete. ## Change size - 32 files changed - 862 lines added - 161 lines removed ## Validation - Completed checks on the current head: not available from the supplied evidence. - Author-reported results, not verified here: - Focused observability tests, codec and durable-serialization checks, and engine and Inngest retry scenarios. - Node 24 builds, 167 core checks, 125 observability and redaction tests, and 19 real Inngest scenarios. - Type-aware lint and `lint:format`. - Known limitations: - A prior monorepo E2E attempt did not run application assertions. Fixture dependency installation failed with a pnpm store ENOENT error. - Earlier runtime tests ran on Node 23.11.0, which is outside the supported engine range. - Standalone observability `tsc` reports errors in an untouched test utility. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
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 -->
|
||
|
|
43d1e9c16d |
fix(ui): fix hover highlight not covering the corner (#30047)
Hovering a card (the credits card in Platform's sidebar, project cards, any clickable `Card`) tinted a second rounded shape 1-2px inside the card, so a thin untinted ring showed along the edge, widest at the corners. Now the hover tint is the surface's own background, so it covers the whole surface and follows any corner radius exactly. The fix is in the shared `state-layer` utility, so every surface that uses it changes. ## Before / After Hovered, dark, zoomed 4x on the bottom-left corner. Look for the darker crescent at the corner in "Before". | | Before | After | | --- | --- | --- | | Platform project card | <img src="https://github.com/user-attachments/assets/7ed1f23b-c0f0-45b0-8313-f1b3ff39058c" width="300" alt="Before project"> | <img src="https://github.com/user-attachments/assets/bb3a627a-668a-4002-9392-57dc8f5f3520" width="300" alt="After project"> | | Platform credits card | <img src="https://github.com/user-attachments/assets/88896a43-4a0f-451f-950f-865d8917b2cf" width="300" alt="Before credits"> | <img src="https://github.com/user-attachments/assets/04700558-04ee-4ece-a240-428964035c48" width="300" alt="After credits"> | | `CardLink` | <img src="https://github.com/user-attachments/assets/00675559-99de-4ccf-ac54-d87c53ac74b9" width="300" alt="Before card"> | <img src="https://github.com/user-attachments/assets/bbe15805-fd38-4282-88da-3ca12efc94fd" width="300" alt="After card"> | | Composer attachment | <img src="https://github.com/user-attachments/assets/6bdf4093-2dad-4a83-85be-003dcdc93a7d" width="300" alt="Before attachment"> | <img src="https://github.com/user-attachments/assets/d325d318-7eea-4554-b489-12b7f7c011b7" width="300" alt="After attachment"> | | Workflow edge Data button | <img src="https://github.com/user-attachments/assets/580d836d-6cc0-4f78-87bb-f559d9c614d7" width="300" alt="Before edge"> | <img src="https://github.com/user-attachments/assets/a0c68b78-0e34-43e4-b102-eb1d81dd8c15" width="300" alt="After edge"> | | Ask-user option | <img src="https://github.com/user-attachments/assets/7611683d-9b2c-453a-a674-a3f9b5950272" width="300" alt="Before ask"> | <img src="https://github.com/user-attachments/assets/105ad584-4a9c-4f18-b10b-f3cf553ef00b" width="300" alt="After ask"> | ## What changed - `state-layer` paints its hover/press tint as a flat `background-image` over the element's fill, instead of a `::before` overlay inset by 1px. The browser clips it to the element's own shape, borders and inset-shadow rims draw over it, and `position`, `isolation` and the negative z-index are gone. `surfaceGroupStateLayerStyle` does the same. - Two consumers painted on the old layer and move to the new one: the composer attachment's dark fill goes to `--surface-tint`, and the edge Data button's selected fill becomes the same `--fill` image the utility uses for press. - 14 files only re-sort the `state-layer` class (the formatter orders it with the background utilities now). ## Why The overlay existed to keep the tint layered over an opaque fill (swapping `background-color` for a translucent rung makes the surface see-through) and to let it fade. It was shrunk 1px so it wouldn't cover the inset rim, which is what made the second shape. A background image keeps the layering and needs no shrinking. It can't fade, so these hovers are now instant, in line with the other instant-hover changes. ## Testing 1. Platform home: hover a project card. The tint reaches the edge, no darker crescent at the corner. Same for the sidebar Credits card. 2. Storybook, Layout/Card "Interactive links", AI/Composer attachments, Workflows/Edge data, AI/Ask user: hover each. Same result. 3. Workflows/Edge data "External inspector": click Data, move the pointer away. It keeps the selected fill. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## ELI5 This PR makes hover and press highlights cover the full shape of cards and buttons. Highlights now follow rounded corners, remain below borders and inner shadows, and switch instantly. ## Summary - Replaced the inset `::before` state layer with clipped `background-image` fills. - Updated grouped surfaces to use the same highlight approach. - Moved composer attachment fills to `--surface-tint`. - Preserved the selected fill for the workflow edge Data button. - Updated state-layer documentation and the theme export test. - Reordered `state-layer` classes in affected consumers. - Added a patch changeset for `@mastra/playground-ui`. **Scope:** 21 files changed; 48 insertions and 63 deletions. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
f9088d8510 |
feat(mcp-apps-components): accept the editor's widget shapes in chat-authored dashboards (#30192)
Dashboards authored in chat rejected several widgets the dashboard
editor can build, so a model couldn't recreate what a user had in the
editor. This widens the shared option schemas in `@mastra/playground-ui`
and the renderers behind them, and the chat authoring schema in
`@mastra/mcp-apps-components` picks the changes up.
KPIs can now combine values (`ratio`, `minus`, `max`, `coalesce`), read
score, trace and span aggregates, and use the `duration`, `percent` and
`score` formats. Percentiles come through trace/span measures, which
give one whole-range value (metric percentiles are always bucketed, so
they can't make a single KPI figure). KPIs now also request the previous
window, so combined values show a change:
```ts
{
label: 'Error rate',
format: 'percent',
value: {
ratio: {
of: { traceAggregate: { measure: 'errorCount', compare: 'previousWindow' } },
over: { traceAggregate: { measure: 'count', compare: 'previousWindow' } },
},
},
}
// p95 latency
{ label: 'p95 latency', format: 'duration', value: { traceAggregate: { measure: 'duration.p95', compare: 'previousWindow' } } }
```
Line charts can plot `scoreTimeSeries`, and charts accept `blue`,
`orange`, `pink`, `yellow`, `red` and `purple`, all mapped to existing
data-viz tokens. KPI `icon` and `detail`, series `color` and table
`emptyMessage` are now optional: series without a color take one from a
palette by position, and tables without a message show "No data". Metric
types in the discovery API (counter vs. histogram) are not part of this
PR.
Tested with new widget tests that open dashboards through the real tool:
p95 latency and error-rate KPIs compared with the previous window, plus
a score line chart and a table that set no colors or empty message. The
KPI test fails against the old KPI request plan. Typecheck, lint and the
existing suites pass in both packages.
---------
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
|
||
|
|
56f654fc0d |
fix(core): name the agent in the memory missing-storage error (#30164)
Co-authored-by: Abhi Aiyer <abhiaiyer91@gmail.com> |
||
|
|
1fbc69aa9a |
feat(factory): count the new session page's starters and activity on the server (#30097)
**─────── TLDR ───────** > The new session page now gets its starter counts and activity dates from two small server reads instead of downloading every card of the project. To show a handful of numbers, the page read the whole board: 1,505 KB gzipped on the 8,078-card board measured in #28915. The rules that decide which cards a starter counts now run on the server, and the browser keeps the wording and the layout. Since #30099 a tab that already holds the board only reads the cards that moved. What this PR removes is the first download, and the board the tab had to keep to count on it. Fifth step of removing whole-board reads, after #30080, #30083, #30087 and #30081 (⌘K). The board page comes next. ### Behavior changed opening a new session page ├─ **was** — every card of the project downloaded, then counted in the browser └─ **now** — two reads: the starter counts, and the instants of the period a card changes while the page is open ├─ **was** — the cards that moved, merged into the board the tab kept └─ **now** — the two reads asked again; the instants come back only when one was added or removed, a `304` otherwise choosing "This month" in the activity band ├─ **was** — recounted at once on the board the tab kept └─ **now** — one more read; the band stays up on the week's instants until it answers the live session counts in the activity band ├─ **was** — read off the whole board └─ **now** — read off the sidebar's cards holding a session, already loaded a pull request card whose source reports no state ├─ **was** — finished only in a phase named `done` or `canceled` └─ **now** — finished in any terminal phase of the default board the page served by a Factory server without the two routes └─ **new** — starters and activity band stay hidden, the rest of the page works; feed frames do not ask the two routes again ### Shape changed | | | | |---|---|---| | **+** | `routes/work-item-starters.ts` | the starter rules, moved here from the browser; they read the cards as storage holds them | | **+** | `routes/work-item-activity.ts` | the instants one period needs | | **+** | `hashedBody()` in `routes/board-snapshot.ts` | a computed answer and the `ETag` naming it | | **~** | `starterPrompts.ts` | words the counts, no longer reads cards | | **+** | `queryKeys.boardFacts(id)` | answers computed from the board, refreshed with it | | **+** | `activityDepth(period)` | one home for "Today reads the week's answer" | | **−** | draft page in `pageLoadsBoard` | it no longer reads the board | | **−** | `doneAt` in `boardItems.ts` | its only caller moved to the server | what callers can now ask `GET …/work-items/starters` · `GET …/work-items/activity?since=<instant>` (answers `304` to `If-None-Match`) · `mastra api factory work-item starters` · `mastra api factory work-item activity` ### Decisions - **counted on the server, not from a smaller card list** — the page needs eight numbers, not cards; a new starter now takes a server rule plus its wording - **instants, not buckets** — the browser buckets in the viewer's time zone and Today reuses the week's answer; bucket on the server if the list ever weighs - **no whole-board fallback on an older server** — the two blocks hide until the server is deployed; one `catch` away if you disagree - **counted on stored cards, not on their wire copy** — copying every card per request was three quarters of the read's time; the rules merge the work item's facts with the card's where they read them - **recounted on every request, no memo per board** — a memo would have to expire with the clock (stale pull requests), the board registry and the decisions; the count costs 1 to 5 ms - **`ETag` on the instants, none on the counts** — the counts weigh about 150 bytes; the page asks the instants from the top of the hour so the address repeats and the browser can revalidate - **the other depth stands in while a period loads** — two observers, one enabled; a placeholder would set the band's clock to zero ### Gain Opening the page on 2,500 cards with ~2 KB descriptions: the whole board, 1.2 MB gzipped, becomes about 150 bytes of counts plus 27 bytes per card created or completed in the period. That is 1.9 KB when the cards were filed over 400 days, 67.9 KB when all 2,500 fall in the week (sent uncompressed: instants gzip about 3.5×). Once the page is open, this branch does not beat `main`, it costs a little more. One refresh of one open tab, at most every 5 s: | one refresh of an open tab | 2,500 cards | 10,000 cards | |---|---|---| | `main`, nothing changed | 0.5 ms · 124 B | 1.4 ms · 122 B | | here, nothing changed | 2.4 ms · 154 B | 7.7 ms · 156 B | | `main`, one card filed | 860 B | 868 B | | here, one card filed | 2,030 B | 5,921 B | "here" adds up the three reads the page makes: cards holding a session (`304`), starters, instants. Cards filed over 400 days, medians of 10 rounds in the in-memory route harness. When every card falls in the week the two counts take 0.98 + 1.15 ms at 2,500 cards and 4.27 + 4.60 ms at 10,000. Counting on stored cards took the starters function from 1.11 to 0.29 ms at 2,500 cards and from 4.61 to 1.15 ms at 10,000. ### Watch > [!WARNING] > The starter rules moved from the browser to the server together with their scenario tests. <mark>A porting mistake would show as a wrong number on a starter button</mark> and nowhere else, so compare a few buttons with the board after deploy. on merge: nothing to do. `main` with #30153 is merged into this branch and the CLI route metadata check passes. ### Not verified - [ ] against a real board or Postgres — the timings come from the in-memory route harness - [ ] the `304` in the signed-in app — the route is tested, and headless Chromium revalidated a stand-in answer with the same headers, but the real page was not watched against a real server --- > ████████████████████ **tests** `+1077 −431` — 58% of the additions > ███████████ **source** `+572 −222` > ███ **generated** `+177` > █ **changeset** `+24` > █ **docs** `+2` --------- Co-authored-by: Damien Schneider <damienschneider@damiens-MacBook-Pro.local> |
||
|
|
d97d3c5fd8 |
chore: version packages (alpha) (#30167)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> |
||
|
|
987566e882 |
fix(core): persist scores for scorer-target experiments (#30145)
Co-authored-by: Abhi Aiyer <abhiaiyer91@gmail.com> |
||
|
|
2742d51576 |
fix(cli): pass filters and lists to Factory list commands (#30153)
**─────── TLDR ───────** > `mastra api factory work-item list` now accepts its filters, and a list of values given to a Factory command reaches the server in the form it reads. Copilot found this on #30081 after it merged. That PR's changeset says `mastra api` can pass the list route's new filters (`started`, `q`, `limit`, `source`). It could not: the command was registered without input, so the JSON was dropped and the whole board came back. This makes that sentence true before it ships. ### Behavior changed `mastra api factory work-item list <project-id> '{"started":"false","q":"login flow"}'` ├─ **was** — the JSON input dropped without a word, every card of the project listed └─ **now** — the filters are sent a list in the input of a Factory command, such as `{"kind":["automation-failed","agent-waiting"]}` on `attention list` ├─ **was** — sent as one JSON string: answered 400, or read as one literal value that matches nothing └─ **now** — one query parameter per value, the form Factory routes read ### Shape changed | | | | |---|---|---| | **~** | `factory work-item list` | takes optional JSON input, like `attention list` and `decision list` | | **~** | `buildUrl(…, route)` | fifth parameter is `{ apiPrefix, repeatLists }`, no longer the prefix alone | ### Decisions - **only on Factory routes** — Mastra API routes parse object-typed query values from JSON, and a single-element `tags` on `trace list`, `log list`, `score list` and `feedback list` only parses in that form; repeating values there would break them - **an empty list and a list of objects keep the JSON form** — an empty list sent as no parameter at all would turn `{"source":[]}` into a request for the whole board ### Watch > [!WARNING] > <mark>A script that already passed a list to a Factory command now sends a different query string.</mark> The old form was answered 400 or matched nothing, so no call that worked changes. on merge: nothing to do. ### Not verified - [ ] against a running Factory server — the tests assert the URL the CLI requests, not the server's answer - [ ] list filters on Mastra API commands (`datasetIds`, `scorerId`, `feedbackType`, `level`) — reading their schemas suggests some are refused in the JSON form the CLI sends today; not run, and not touched here --- > ██████████████████ **tests** `+101 −6` — 77% of the additions > ████ **source** `+24 −4` > █ **changeset** `+7` --------- Co-authored-by: Damien Schneider <damienschneider@damiens-MacBook-Pro.local> |
||
|
|
a4258a989c |
chore: version packages (alpha) (#30127)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> |
||
|
|
c1fb13f325 |
fix(agent-controller): resume reopened approvals with request context (#30159)
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com> |
||
|
|
6f7eb696e9 |
fix(core): keep sub-agent snapshots out of the durable replay cache (#29151)
> Opened by @wardpeet Fixes #29035 (follow-up to #24160). ## Summary When a `DurableAgent` or `EventedAgent` delegates to a sub-agent, the sub-agent's chunks are forwarded on the run stream inside `tool-output` / `workflow-step-output`. Each nested `step-start`, `step-finish` and `finish` carries the sub-agent's full prompt, message history and cumulative steps. `CachingPubSub` stored them as-is in the run's 24h replay cache, so about 80 KB of real content grew to about 2.2 MB per run. Main already slims these chunks for the plain `Agent` publisher (#29965). The durable engines were left out because their callers read their own run back from the same topic, so slimming the published event would change what the caller sees on `fullStream`. ## Changes - `events/topics.ts`: new `toCachedLogFrame(topic, event)`, next to `cachedLogTtlMs`. For `chunk` events on agent stream topics it returns a copy with `slimNestedAgentChunks` applied. Everything else is returned by reference. - `events/caching-pubsub.ts`: `publish` stores `toCachedLogFrame(topic, fullEvent)` in the cache log. Live subscribers still receive `fullEvent` unchanged. - So a durable or evented caller streaming its own run gets the same full nested chunks as a plain `Agent` caller, and only the cached copy is slimmed. Top-level chunks (#28674) and data written by tools are cached unchanged. The sub-agent's usage, tool identity and `producedAt` are kept. - `agent-stream-log.scenario.test.ts`: "keeps a delegated agent's prompt off the log" now runs as `it` on every engine. On main it is `it.fails` on the durable engines. - New tests: `agent/durable/__tests__/delegated-chunk-snapshots-durable.test.ts`. They check that live subscribers get the chunk as published and the cache gets the slimmed copy, and that a real delegation's caller still sees nested `messages`. - Changeset: `@mastra/core` patch. **Known limit:** a cross-process live transport (for example Redis pub/sub) still carries the full delegated chunk while the run is live. This PR fixes the persisted growth reported in #29035, not live message size. ## Verification (head ` |
||
|
|
6937417bd4 |
fix(factory): ⌘K reads the clicked card by its id, and three search fixes (#30154)
**─────── TLDR ───────** > ⌘K now reads the card you click by its id before starting it, and three smaller search bugs are fixed. Copilot reviewed #30081 after it merged and left six findings. Four are about the palette and are fixed here, one commit each. The CLI one is #30153, and the sixth was declined on the PR. ### Behavior changed clicking a listed card the search would no longer return, because a more recently updated card took its place among the 20 ├─ **was** — "This card no longer exists", nothing started └─ **now** — the card is read by its id and its session starts Retry after the board cards failed to load, when the intake has no candidate ├─ **was** — the failure notice stayed up for good └─ **now** — only the reads that failed are asked again, and the notice goes typing a source label such as "review" with more than 20 intake items ├─ **was** — the item matching by its label could miss the 20 looked up, and its row never showed └─ **now** — the 20 are ranked on the same text the rows are filtered on typing the number of a card that has no key and no GitHub source ├─ **was** — the server found the card, the palette then hid its row └─ **now** — the row shows the list route asked for `?workItemId=<id>` └─ **new** — the cards with those ids and no other; an id no card has is left out, and a board cursor (`since`) sent with it is ignored, as on the other narrowed lists ### Shape changed | | | | |---|---|---| | **+** | `workItemId` on `workItemListQuerySchema` | repeatable, 100 ids at most, refused with any other filter | | **+** | `cardsWithIds` | beside `cardsFiledFrom` in `work-item-selection.ts` | | **~** | `useBoardRuns({ refetchItems })` | now given the id of the card clicked | | **~** | `useGlobalSearchWorkItems.refetch` | one card by its id, no longer both lists | | **+** | `candidateSearchValue` | one home for the text a candidate row is filtered and ranked on | | **+** | `searchedNumber` | the number the server's search reads, mirrored for the row | what callers can now ask `GET …/work-items?workItemId=<id>` · `mastra api factory work-item list` can pass it once #30153 is in ### Decisions - **a filter on the list route, not `GET /work-items/:id`** — a server older than the filter ignores it and sends the whole board, which still holds the card; a new route would answer 404 there and read as "deleted" - **not the listed copy as a fallback** — starting a run on an id the server no longer has creates the card again (`prepareRunStart`), so a deleted card would come back; the fresh read decides, and a deleted card still gets the toast - **the board page keeps refetching its list on a click** — it moves to the same read with the board page's own PR ### Gain A click in ⌘K asks for one card instead of two lists. ### Watch > [!WARNING] > <mark>Until a server with `workItemId` is deployed, each click on a card in ⌘K downloads the whole board.</mark> It still finds the card there, so the click works, only slower. on merge: `main` with #30099 is merged in and the CLI route metadata regenerated. #30097 regenerates the same file, so whichever merges second runs `pnpm --filter @mastra/factory generate:api-cli-route-metadata` again. ### Not verified - [ ] against a deployed Factory or Postgres — the route tests run on the in-memory harness, the palette tests against stubbed routes - [ ] in a real browser — the palette tests run in jsdom --- > ██████████████████ **tests** `+273 −5` — 65% of the additions > ███████ **source** `+110 −25` > █ **generated** `+18 −2` > █ **changeset** `+16` > █ **docs** `+2 −2` --------- Co-authored-by: Damien Schneider <damienschneider@damiens-MacBook-Pro.local> |
||
|
|
055a8c3b82 | chore: version packages | ||
|
|
a0cd52cdc1 |
refactor(core): extract shared observe() fullStream detach wrapper (#30111)
> Opened by @wardpeet ## Result: Approved — |
||
|
|
d7fa57619b |
fix(core): keep sub-agents streaming after a durable resume with a request context (#29616)
## Summary
A `DurableAgent` run started with `stream()` stopped streaming its
sub-agents after a resume that passed a `requestContext`. On a warm
resume with a request context, the run's tools are rebuilt, and the
rebuild picked `generate` whenever `closeOnSuspend` was set.
`closeOnSuspend` is also a `stream()` option, and `resumeStream()` (so
`approveToolCall()` too) always sets it, so `agent-<name>` delegation
tools ran the sub-agent through `generate` and its chunks never reached
the stream as `tool-output`.
The fix records the method that started the run on the run registry
entry and rebuilds for that method. The same line in the Inngest durable
agent gets the same change.
The same hunk restores a second outcome: tool calls that a delegated
sub-agent makes on durable and evented runs report `subagent_tool_end`
again. The agent controller emits
`subagent_tool_start`/`subagent_tool_end` only while it reads the
sub-agent's stream (`agent-controller/tools.ts`) and uses
`subagent_tool_end` to set the tracked call's status
(`agent-controller/session.ts`), so while the delegation tool was built
for `generate` those rows never got a status or result. That is why the
`it.fails` pins on the durable and evented `delegated` cases in
`controller-tool-errors.scenario.test.ts` are removed; the changeset
says so too.
```diff
// prepareForDurableExecution
registryEntry = {
tools,
requestTools: tools,
+ methodType, // 'stream' or 'generate', from the call that started the run
...
}
// warm resume with requestContext / delegation / hooks
getToolsForExecution({
...
- methodType: resolvedOptions.closeOnSuspend ? 'generate' : 'stream',
+ methodType: entry.methodType ?? 'stream',
})
```
## Evidence
New shared aimock scenario
`packages/core/src/loop/test-utils/aimock/scenarios/subagent-resume-streaming.scenario.test.ts`.
A lead agent with a suspending `ask_user` tool and a sub-agent `helper`
(with its own tool) talk to a real OpenAI provider pointed at the aimock
HTTP server. The lead suspends, is resumed, then delegates to `helper`.
Each case checks that `helper`'s `tool-call`, `tool-result` and
`text-delta` chunks arrive on the resumed stream as `tool-output`, and
that every `helper` model request was a streaming request. Cases:
- `resumeStream()` with a `requestContext` (the #29436 path)
- `resumeStream()` without one (control)
- durable only: `resume()` with `requestContext` and `closeOnSuspend:
true`, as in the issue's repro
- durable only: a `generate()` run resumed with `resumeGenerate()` still
runs the sub-agent through `generate` (non-streaming requests)
- **Before (origin/main):** normal, durable, evented: `Tests 4 failed |
6 passed | 4 skipped (16)`. The 4 failures are the request-context cases
on durable and evented: `expected [] to deeply equal ArrayContaining
["tool-call","tool-result","text-delta"]`.
**After:** `Tests 10 passed | 4 skipped (16)`.
- **Inngest engine** (real dev server,
`AIMOCK_SCENARIOS='subagent-resume-streaming' pnpm --dir
workflows/inngest test:aimock`): with the Inngest line reverted, `2
failed | 2 passed (4)`, the same two request-context cases. With the
fix: `4 passed (4)`.
- Neighbouring tests, unchanged and green (`Tests 130 passed | 3
expected fail | 11 skipped`): `durable-agent-resume-request-context`,
`durable-agent-request-context`, `durable-agent-delegation`,
`durable-agent-generate`, and the `request-context-resume`,
`supervisor-suspension`, `supervisor-delegation-generate`,
`parity-sub-agent-suspend`, `parity-sub-agent-delegation`,
`subagent-auto-resume`, `resume-stream` scenarios.
- `tsc --noEmit -p tsconfig.build.json` for core, `tsc --noEmit` for
`@mastra/inngest`, oxlint on the touched files and prettier on the
changed files all pass.
- `controller-tool-errors.scenario.test.ts` pinned its durable and
evented `delegated` cases with `it.fails` because those delegations
emitted no `subagent_tool_end`. This fix makes them pass (CI reported
`Expect test to fail` on all 14), so the marker is removed: `Tests 84
passed (84)`.
Not covered: a cold resume (registry entry gone, rebuilt from storage)
still calls `prepare()` with the default `stream`, so a `generate()` run
resumed in another process gets stream-built tools. That was already the
case before this PR, and the tools still work under `resumeGenerate()`,
so it is left as-is.
## Merge Danger
**Door:** two-way. A one-field registry change plus two one-line
call-site changes, all easy to revert.
**Blast radius:** warm `DurableAgent`, `EventedAgent` and Inngest
durable resumes that pass a `requestContext`, `delegation` or `hooks`.
One behavior change to know about: `resumeGenerate()` on a run started
with `stream()` now rebuilds its tools for `stream`, matching the first
segment and the no-context resume. Other open PRs touch
`durable-agent.ts` / `types.ts` (#28283, #28530, #29036, #29282,
#27522), but none changes these lines.
Closes #29436
## Council review
Rounds: 2
| Seat | Round 1 | Round 2 |
| --- | --- | --- |
| Claude Opus 5.5 | not run | 9/10 (Correctness 9, Tests 9, Scope 10,
Code quality 9) |
| 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) |
| Grok 4.7 | 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 paused run continues, it should keep working the way it started.
This change makes sub-agents keep sending progress updates after a
streamed run resumes. This holds even when the resume includes a
`requestContext` or `closeOnSuspend`.
## Summary
- Store the original method type (`stream` or `generate`) on each run
registry entry when the run is prepared.
- On warm resume, rebuild request-scoped tools with the stored method
type. If no method type is stored, use `stream`. Stop inferring the
method from `closeOnSuspend`.
- Apply the same change to the Inngest durable agent resume path.
- Add an AIMock scenario test for sub-agent streaming after resume, with
and without a request context. The test also checks that resumed
`generate()` runs make non-streaming helper requests.
- Remove the `it.fails` markers from the delegated-tool tests for the
durable and evented engines. These tests now run as ordinary tests.
- Add patch changesets for `@mastra/core` and `@mastra/inngest`. The
changesets reference issue `#29436`.
Scope:
- Cold resumes, which rebuild the run from storage, are not changed.
They still default to `stream`, including for a run that started with
`generate()`.
Test and CI results: not available.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
|
||
|
|
b9610409ab |
perf(factory): send an open board only the cards that changed (#30099)
Co-authored-by: Damien Schneider <damienschneider@damiens-MacBook-Pro.local> Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com> |
||
|
|
efc1fe40ba |
fix(core): drop supervisor reasoning from delegated sub-agent context (#29620)
## Summary
A supervisor on Claude with extended thinking could not delegate after
its first step in a run. Anthropic rejected every such delegation with
"`thinking` or `redacted_thinking` blocks in the latest assistant
message cannot be modified". Delegation forwards the supervisor's
messages to the sub-agent with tool calls and tool messages removed, but
it kept their reasoning parts. So the sub-agent got the supervisor's
signed thinking with no `tool_use` beside it, and `@ai-sdk/anthropic`
merged the now-adjacent assistant steps into one message.
`stripParentToolParts` in `@mastra/core` now removes reasoning parts
from forwarded assistant messages along with tool calls. It keeps their
text and still drops messages left empty.
```diff
stripParentToolParts(messages)
drop tool messages and the OM continuation hint
for each assistant message
- remove tool-call parts
+ remove tool-call and reasoning parts // text stays
drop the message if nothing is left
```
Why drop all forwarded reasoning, not only the reasoning in messages
that lost a tool call? The narrower rule (the one
`removeWorkingMemoryToolInvocationParts` uses for working-memory calls)
still fails here. Take an earlier turn recalled from memory, `[thinking,
text, tool_use] → tool_result → [thinking, text]`. After stripping it
reaches Anthropic as one merged message, `[text, thinking, text]`, with
signed thinking in the middle. The forwarded context always ends in the
delegation prompt (a user message, never a tool-use continuation), so no
provider needs thinking blocks in it. This is also the workaround the
issue suggests.
## Evidence
New scenario
`packages/core/src/loop/test-utils/aimock/scenarios/delegation-signed-reasoning.scenario.test.ts`
runs on the normal, durable, evented and fs engines. Both agents use the
real `@ai-sdk/anthropic` provider against AIMock's Messages endpoint,
and the assertions read the raw request body the sub-agent sends. No
real Anthropic calls are made. The five cases:
1. Think and call `get_time`, then delegate. The sub-agent request has
no `thinking`/`redacted_thinking` without a `tool_use`, and none of the
supervisor's signatures.
2. Text in the tool step survives; its thinking does not.
3. Two runs on one `MockMemory` thread. The recalled turn's signed
thinking (tool step and final answer) is gone, and its text is kept.
4. OpenAI supervisor with unsigned reasoning in history. `messageFilter`
receives text-only assistant messages.
5. `messageFilter` input carries no reasoning.
- **Before** (origin/main `agent.ts`): `Tests 20 failed (20)`. The
sub-agent body carried the supervisor's step-1 signed thinking and
redacted thinking:
```
+ { "data": "redacted-supervisor-step-1", "type": "redacted_thinking" },
+ { "signature": "sig-supervisor-step-1", "thinking": "First I need the
current time.", "type": "thinking" },
```
**After:** `Tests 20 passed (20)`.
- The narrower "drop reasoning only where tool calls were removed"
version fails cases 3 and 4 (8 of 20), which is why the final rule drops
all forwarded reasoning.
- Existing delegation and history tests still pass: `subagent.test.ts`,
`subagent-duplicate-prompt.test.ts`, `src/agent/__tests__/delegation*`,
the `delegation-message-filter`, `delegation-parent-context`,
`supervisor-message-history`, `parity-sub-agent-delegation` and
`supervisor-delegation-generate` scenarios, and
`provider-history-compat.test.ts`: 234 passed, 2 skipped.
- `tsc --noEmit -p tsconfig.build.json` and `oxlint --type-aware` on the
changed files pass.
Not checked: a live Anthropic or Bedrock request (AIMock does not
enforce Anthropic's thinking rule, so the tests assert it directly), and
the Inngest engine.
## Merge Danger
**Door:** two-way. One filter in one private method; reverting it
restores the old forwarded context.
**Blast radius:** context forwarded to every delegated sub-agent, on
every provider. Sub-agents and `messageFilter` no longer see the
supervisor's reasoning parts; its text, user messages and system
messages are unchanged. The `iteration` value passed to delegation hooks
is unchanged: it is still counted on the parent context with reasoning
kept.
Provider-executed tool results (`tool-result` parts inside assistant
messages, such as Anthropic web search) are now stripped by main
(#30134) at the same filter; after merging main, the filter drops tool
calls, tool results and reasoning.
Closes #29276
## Council review
| Round | Sol (GPT-6.1 Sol): correctness / tests / scope / quality |
Opus (Claude Opus 5.5): correctness / tests / scope / quality | Grok 4.7
|
|---|---|---|---|
| 1 | 9 / 8 / 10 / 9 | not run (Sol first) | empty seat |
| 2 | 9 / 8 / 10 / 9 | not run (Sol first) | empty seat |
| 3 | 9 / 9 / 10 / 10 | not run (Sol first) | empty seat |
| 4 | 9 / 9 / 10 / 9 | 8 / 9 / 10 / 8 | empty seat |
| 5 | 10 / 9 / 10 / 9 | 9 / 9 / 9 / 9 | 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 supervisor agent asks a helper agent to do work, it now leaves
out the supervisor's reasoning notes. Those notes can make the AI
provider reject the request. The helper still receives the supervisor's
text replies.
## Changes
- `stripParentToolParts` removes assistant `reasoning` parts along with
`tool-call` parts from the context forwarded to a delegated sub-agent.
- Assistant text parts are kept. Assistant messages with no content left
are dropped.
- Delegation computes its `iteration` value from the original parent
context. A new helper, `countParentAssistantSteps`, counts assistant
messages. It skips `om-continuation` messages and messages whose array
content holds only `tool-call` or `tool-result` parts. Removing
reasoning does not change the reported iteration.
- Added AIMock delegation scenario tests in
`delegation-signed-reasoning.scenario.test.ts`. They cover signed
reasoning, unsigned reasoning from another provider, and signed
reasoning recalled from memory. They check that forwarded context
excludes reasoning, signatures, and redacted thinking, and that text and
prompts remain. They also check that the `messageFilter` input has no
reasoning and that the reported iteration is unchanged.
- Added a patch changeset for `@mastra/core`.
- User and system messages are not changed by this PR. The
`messageFilter` input keeps its other message types.
## Validation
Test and check results: not available. The PR description reports
passing scenario and existing delegation tests, plus type-check and lint
results. These were not confirmed on the current head. Live Anthropic
and Bedrock requests and the Inngest engine were not tested.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
|
||
|
|
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>
|
||
|
|
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> |
||
|
|
5e3c087082 |
fix(core): strip provider-executed tool results from delegated sub-agent context (#30134) | ||
|
|
53b9bf64ba |
fix(core): accept null optional fields in strict structured output on durable, evented and Inngest agents (#30136) | ||
|
|
ddf1c08cf6 |
perf(factory): ⌘K asks the server for matching cards instead of downloading the board (#30081)
Co-authored-by: Damien Schneider <damienschneider@damiens-MacBook-Pro.local> Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com> |
||
|
|
fd139c9a14 |
test(core): fix channel approval-card tests broken by per-thread permission rules (#30137)
Co-authored-by: CalebBarnes <CalebBarnes@users.noreply.github.com> Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com> |
||
|
|
2d4284603a |
Fix MCP core compatibility, Windows browser paths, and AI SDK tool titles (#30125) | ||
|
|
9e82af0237 |
chore: version packages (alpha) (#30074)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> |
||
|
|
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> |
||
|
|
056d35d943 |
Enforce JSON Schema formats in MCP tool validation (#30113) | ||
|
|
7f0d2fd4b6 |
feat(core): trace agent setup before the first model call (#30002)
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com> |
||
|
|
4cfa256801 |
feat(coding-agent): link Linear issues with Fixes lines in PR descriptions (#30112) |