mirror of
https://github.com/mastra-ai/mastra.git
synced 2026-11-17 08:44:46 +00:00
23,235 commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
566e2081d3 |
Fix transcript gap ordering when answered suspension prompts are removed (#30163) | ||
|
|
c1fb13f325 |
fix(agent-controller): resume reopened approvals with request context (#30159)
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com> |
||
|
|
a2998f4084 |
test(storage): verify rollback reporters settle before client release (#30160)
## Summary - Make PostgreSQL pooled/pinned and DSQL pooled async rollback reporter tests assert that reporting finishes before transaction settlement and pooled release. - Use plain async reporters to catch unhandled promise rejections rather than `vi.fn` wrappers. ## Test plan - PostgreSQL transaction tests: 18 passed; DSQL transaction tests: 9 passed. - Both package TypeScript checks, targeted Oxlint, Prettier and `git diff --check` passed. - Confirmed the changed tests fail against the parent of merged #30157: PG 2 failures, DSQL 1 failure (plus unhandled rejections). Follow-up to #30157; test-only correction to the regression coverage for its already-merged implementation. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ELI5: The change makes the database tests check the right order of events. A rollback error must be reported before the database connection is released and before the transaction ends. The tests now fail if that order is wrong. ## Summary This change updates two test files for the rollback reporter behavior in PostgreSQL and DSQL transaction clients. It changes test code only. No production code changes. Diff stats: 2 files changed, 33 insertions, 9 deletions. ### `stores/dsql/src/storage/client.tx-serialize.test.ts` - The reporter is now a plain async function, not a `vi.fn` wrapper. - The reporter stores the error it receives. - The reporter waits 10 ms, records `reported`, and then throws `async logger failed`. - The test mocks `client.release` to record `released`. - The test records `tx-settled` after the transaction call rejects with the original error. - Assertions: - The reporter received `rollbackError`. - `client.release` was called with `true`. - The event order is `['reported', 'released', 'tx-settled']`. ### `stores/pg/src/storage/client.tx-serialize.test.ts` - The same reporter change applies to the shared async rollback reporter test. - For the pooled case (`kind === 'pool'`): - `client.release` records `released`. - Assertions check that `client.release` was called with `true`. - The event order is `['reported', 'released', 'tx-settled']`. - For the pinned case: - No release tracking is added. - Assertions check that `adapter.shouldDestroyClient` is `true`. - The event order is `['reported', 'tx-settled']`. ## Not verified - The PR reports test runs, type checks, lint, and format checks. I did not run them. Their results are not available from this review. - The PR reports that the changed tests fail against the parent of the referenced prior change. I did not verify this. It is not available from this review. <!-- 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> |
||
|
|
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> |
||
|
|
b1948fb073 |
fix(storage): await rollback diagnostics before releasing clients (#30157) | ||
|
|
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>
|
||
|
|
743a02786e |
feat(valkey): identify Mastra-created clients with a clientInfoTag (#30156) | ||
|
|
ce631e94c6 |
fix(storage): prevent poisoned PostgreSQL transactions from returning to the pool (#30144) | ||
|
|
d432f1ea67 |
feat(factory-ui): pick a route's repository, team or project from the project's own (#29982)
## Summary
An intake route with `source.repository equals mastra` never matches. On
GitHub the value is `owner/repo` (`mastra-ai/mastra`), and the route
editor gave no hint of that. Now you pick the value from the project's
own sources:
- **Searchable list of the project's sources.** In Settings › Work
Intake, the value of **Repository, team or project** is a combobox. It
lists the project's linked repositories (`owner/repo` on GitHub,
`group/project` on GitLab), then the team keys of the Linear teams and
projects bound to it, then the keys of its bound Jira projects. All of
this comes from data the UI already loads (`/web/factory/projects`,
`/web/intake/bindings`, `/web/linear/{projects,teams}`,
`/web/jira/projects`), and the Linear and Jira lists are only fetched
when the project has a binding for them. No new endpoint.
- **Narrowed by provider.** When the condition's own AND group, or an
AND group around it, limits `source.integration` or `source.provider`
with **is** or **is any of**, only those providers' values are offered.
A limit in an OR group doesn't count, since a card meets only one
branch. A key two providers share (Linear and Jira `ENG`) shows once.
- **Free typing still works.** The search box offers `Use "<text>"` for
any value not in the list, after the suggestions it matches, so typing
`mastra` and pressing Enter picks `mastra-ai/mastra`; with no match it's
the only option. The control is the same before and after suggestions
load, so a value being typed is kept. Saved values that aren't listed
still show. With **is any of** / **is none of** you can pick several.
The empty trigger reads `owner/repo, ENG, PLAT`. A project with nothing
to suggest gets the same picker with an empty list.
- **Bare-name warning.** When every card a condition tests must come
from GitHub or GitLab (the same AND-group limits as the narrowing, from
one shared helper) and the condition requires a repository with no `/`
(**is**, or any value of **is any of**), the editor shows "GitHub
repositories are owner/repo, such as mastra-ai/mastra." (or the GitLab
equivalent). **contains** / **is not** / **is none of** stay quiet,
since those can still match.
- **README:** the `source.repository` row gives each provider's exact
format and says the comparison ignores case. incident.io items have none
(test `source.provider equals incidentio`), and manual cards have no
`source.*` facts (test `source.kind not_exists`).
`main` replaced the playground-ui `RuleBuilder` in this editor with
factory-ui's own condition rows (#29978). The earlier playground-ui
`examples` placeholder change and its changeset are therefore gone, and
this PR only touches factory-ui and the Factory README.
## Screenshots
<img width="1280" height="900" alt="repository-picker-desktop"
src="https://github.com/user-attachments/assets/60483565-0a47-4ded-88b8-d74f4cfc3da2"
/>
This image predates
|
||
|
|
e60ea1f681 |
fix(factory): rebuild environment templates on push for Platform GitHub (#30135)
Factories connected to GitHub through Mastra Platform never rebuilt
their sandbox template on push, even with build-on-push turned on.
Sessions kept starting from whatever template was built last, so they
spent time fetching and checking out weeks of commits (and
`last_push_build_at` stayed null).
On the Platform lane GitHub events only reach Factory through the
polling event worker. The worker's integration context was built without
the `onRepositoryPush` hook (only the routes context had it), so
`GithubRules` dropped every default-branch push. This passes the hook
into the worker context too:
```ts
// factory.ts, integration worker context
...(this.#environmentBuilds ? { onRepositoryPush: this.#environmentBuilds.onRepositoryPush } : {}),
```
The new test in `event-worker.lifecycle.test.ts` boots a real
`MastraFactory` with `PlatformGithubIntegration`, polls a `push` event
from a stubbed Platform event log, and checks that the build starts,
`lastPushBuildAt` is recorded and the active template is pinned to the
new head. It fails without the fix and passes with it on both LibSQL and
Postgres 16 (`FACTORY_TEST_STORAGE_BACKEND=postgres`).
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->
ELI5: When someone pushes new code to a Factory's GitHub repository, the
Factory now rebuilds its sandbox template. New sessions then start from
the latest code, not an old copy.
## Summary
This PR fixes build-on-push for Factories connected to GitHub through
Mastra Platform. Platform GitHub events reach Factory through the
polling event worker. That worker did not receive the `onRepositoryPush`
hook, so default-branch pushes did not trigger an environment build.
## Changes
- `mastracode/factory/src/factory.ts`: When `#environmentBuilds` exists,
`MastraFactory.prepare()` adds `onRepositoryPush` to the integration
context used to build each ready integration's workers. When no
environment build runner exists, the property is omitted. The change is
two added lines, placed beside the existing optional
`sourceControlOwnerId: 'github'` entry.
- `mastracode/factory/src/integrations/platform/github/event-worker.ts`:
Comments only. They now describe default-branch pushes as triggering
environment-template rebuilds, and they name
`GithubRules.onRepositoryPush` as the hand-off. The comments no longer
refer to base-checkpoint rebuilds or `withBaseCheckpointWebhookTrigger`.
No executable behavior changed.
-
`mastracode/factory/src/integrations/platform/github/event-worker.lifecycle.test.ts`:
Adds 143 lines. The test adds PostgreSQL test-storage support and a mock
sandbox that records build starts and returns a ready template. It
configures a project for push builds with a 60-minute debounce, links
its default-branch repository, and polls a stubbed GitHub push event. It
checks that the project is marked as having a push build, that an
environment build starts, and that the resulting template becomes active
with the pushed commit SHA recorded as the repository head. Cleanup
closes storage and stops workers.
- `.changeset/free-horses-grin.md`: Adds a patch changeset for
`@mastra/factory`.
## Test results
The author reports that the new test fails without the change and passes
with it. The author reports this on LibSQL and on Postgres 16 with
`FACTORY_TEST_STORAGE_BACKEND=postgres`. This review did not run the
tests. CI status is not available.
## Diff scope
4 files changed, 153 lines added, 3 lines removed.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
|
||
|
|
c014d187bb |
chore(deps): update docker images (major) (#19788) | ||
|
|
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> |
||
|
|
a8130955fe |
chore(deps): update cgr.dev/chainguard/minio docker digest to db3f583 (#30139) | ||
|
|
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) | ||
|
|
834c0c5635 |
fix(factory): honor board triage routes and return labeled cards to Intake (#30100) | ||
|
|
9497c2edfb |
test(mastracode): make schedules multi-line e2e scenario independent of the clock (#30128)
## Summary The `schedules-multiline-prompt` TUI e2e scenario failed depending on the time of day. The `/schedules` picker cuts each row off at the dialog width, and the row label's length changes with the clock: the next-fire time includes a date when it falls on another day, and the countdown (`in 5s` vs `in 59m 59s`) changes width. When the label got long enough, the end of the schedule summary was cut off and the "whole summary is visible on one row" check failed. This happened on `main` and on unrelated PRs. The scenario now resizes the terminal to 160 columns, which leaves room for the longest possible label plus the full summary. The test still proves the same things: each schedule takes exactly one row while arrowing through the picker, rows aren't duplicated or wrapped, and the whole summary is visible. A summary with line breaks would still split the row at any width. No product code changes. ## Test plan - [x] Reproduced the failure by running the scenario with `MC_E2E_COLUMNS=114`: the summary was cut off the same way it was in CI. - [x] With the fix, the scenario passes at `MC_E2E_COLUMNS` 80, 114 and 120. - [x] `schedules-multiline-prompt` and `schedules-command` passed 5 runs in a row. - [x] `pnpm --filter ./mastracode/tui lint` and `check` pass, and `oxfmt --check` is clean. Co-authored-by: CalebBarnes <CalebBarnes@users.noreply.github.com> Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com> |
||
|
|
8ea9c0e552 |
fix(factory): surface incomplete working-phase runs instead of marking them successful (#30101) | ||
|
|
b75348adbd |
docs: redirect commonly hallucinated docs URLs to real pages (#30126) | ||
|
|
0fe65182d8 |
docs(evals): link datasets, experiments, and the eval loop from the Evals overview (#30124) | ||
|
|
064c1ff2e2 |
docs: redirect /docs/agents/mcp-guide to the MCP page (#30122) | ||
|
|
f5c7626fe7 |
docs(mcp): link runtime-tools example to durable agents and background tasks (#30120) | ||
|
|
4e028252d1 |
docs(sandbox): clarify that LocalSandbox workingDirectory doesn't copy the project (#30119) | ||
|
|
edb61ca939 |
docs(workspace): explain provider requirement when indexing supplied text (#30117) | ||
|
|
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) | ||
|
|
8e26648e8b |
docs(schedules): explain that workers must be running for schedules to fire (#30116) | ||
|
|
0b3514eb8a |
fix(code-sdk): keep schedule summaries on one line (#30108)
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com> |
||
|
|
38327de07a |
Avoid Event-Loop Stalls in Instruction Lookup (#30104) | ||
|
|
1689ce38e1 |
perf(agent-controller): read only the newest page when listing threads with a limit (#30090)
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com> Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com> |
||
|
|
f3f304bc1f |
docs(mastracode): fix goal continuation, ResolutionPolicy, and mode default models (#30103)
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com> |
||
|
|
3ca0af7cf4 |
docs: show how to save audit records with agent tool hooks (#30106) | ||
|
|
fdd242c2a4 |
chore(ci): remove 2027dev evals workflow (#30107)
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com> |
||
|
|
9efd1ea8df |
fix(factory): report a missing schedule cron as null (#30098)
Schedules can now be one-off runs with no cron expression (#25131), so `schedule.cron` is optional. The Factory environment build schedule view still assigned it to a `string | null` field, which fails the `@mastra/factory` typecheck on `main`. The view now reports a missing cron as `null`, the same as when there is no schedule. ## Test plan - [x] `tsc --noEmit` in `mastracode/factory` passes (fails on `main` at `build-schedule.ts:68`) - [x] `vitest run src/environment`: 61 passed <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## ELI5 When a schedule has no cron expression, Factory now returns `null` instead of an invalid missing value. This supports one-off schedules and matches the declared output type. ## Changes - Updated `toView` to map an undefined `schedule.cron` to `null`. - Added a patch changeset for `@mastra/factory`. ## Testing Not available. <!-- end of auto-generated comment: release notes by coderabbit.ai --> Co-authored-by: CalebBarnes <CalebBarnes@users.noreply.github.com> Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com> |
||
|
|
47dfae5d3a |
fix(factory): mint GitHub tokens ten repositories at a time (#30093)
## Summary A Factory with more than ten repositories asked GitHub for one token per repository every time a session started or an environment built, because one token can name at most ten repositories. Rebuilds and a handful of sessions together ran into the per-installation token limit, and a failed request quietly left that repository unsynced. - Sessions, environment builds and branch-head lookups now request access for each group of up to ten repositories once, and serve every repository in the group from that token. Eleven repositories need two tokens instead of eleven. The group token stays with those callers; a lookup for a single repository still gets a token for that repository only. - Minted access is reused for 20 minutes instead of 5. Sessions replace their `GH_TOKEN` after 30 minutes instead of 45, so a reused token is never close to GitHub's 60-minute expiry. - If a group can't be granted, each repository falls back to its own token as before. ## Test plan - [x] New: the Platform GitHub integration serves an eleven-repository environment from two token requests (twelve without this change) - [x] New: a group mint returns each repository's access under the group token, and a later single-repository lookup still gets a single-repository token - [x] New: `groupedRepositoryAccess` falls back to per-repository tokens when a group can't be granted or the group request fails - [x] Updated token refresh tests for the 30-minute refresh - [x] `@mastra/factory` tests, typecheck, oxlint and oxfmt pass <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## ELI5 Factory now requests shared GitHub tokens for groups of up to ten repositories. This reduces token requests while preserving individual-token fallback when group access is unavailable. ## Changes - Added grouped repository access with deduplication and shared in-flight requests. - Added a 60-second cooldown after failed or unavailable group requests. - Applied grouped access to environment builds, branch-head resolution, and workspace setup. - Extended the version-control contract for multi-repository access. - Increased repository-access token reuse from 5 to 20 minutes. - Updated session `GH_TOKEN` refresh from 45 to 30 minutes. - Added tests for batching, fallback, cooldowns, cache expiry, and token refresh. - Added a patch changeset for `@mastra/factory`. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: CalebBarnes <CalebBarnes@users.noreply.github.com> Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com> |
||
|
|
eb683b45fe |
fix(core): find channel tool approvals older than the newest 50 messages (#29618)
## Description
### Summary
After an `AgentChannels` rebuild (the `channelConfig` pattern) or a bot
restart, the new instance has no card cache, so a click on Approve/Deny
looks up the pending approval in Memory. That lookup read only the
newest 50 messages. An approval followed by a longer thread was silently
ignored (`No pending approval found`) while its metadata still existed.
The same window also hid the user turn that triggered the tool, so the
requester check was skipped and anyone could answer the card.
The lookup in `packages/core/src/channels/agent-channels.ts` now reads
history newest-first, 50 messages per page, and only on a cache miss:
```diff
on approval click, card not in cache
- read newest 50 messages
- find pending entry for toolCallId, else "No pending approval found"
+ for each page of 50, newest first
+ pending entry for toolCallId found -> keep reading until its user turn is complete
+ assistant message carrying the tool call, no entry -> already answered, stop
+ no more messages -> stop
+ recover requester from that user turn (ambiguous turn -> no one may answer)
```
Storage can't filter on the nested
`pendingToolApprovals[...].toolCallId` (the `listMessages` metadata
filter is shallow scalar only), so this pages rather than querying.
Earlier pages are dropped and `includeTotal: false` skips the count
query. Both approval writers (`tool-call-step.ts` and the durable
`tool-call.ts`) store the entry on the newest assistant message carrying
the tool call, which is what makes the "already answered" stop safe.
The scan runs before the requester check, so its result is cached per
card (thread, card message, toolCallId) to stop repeat clicks from
forcing repeat scans (Superagent finding):
- Pending and answered results are kept for 10 minutes, unknown cards
for 60 seconds. At most 1000 entries per instance; concurrent clicks on
one card share one read.
- Core decides whether a second answer applies:
`approveToolCall`/`declineToolCall` claim the suspended run atomically
(`AGENT_RESUME_ALREADY_CLAIMED` for the loser) and hand it back if the
resumed run fails before it starts. The channel only reads core's resume
errors by `MastraError` id: a finished, aborted or no-longer-waiting run
marks the card answered, so later clicks neither resume nor read
history; a resume already in progress is ignored quietly. While one
click edits the card and dispatches, other clicks on that card on the
same instance are ignored.
- No hard page cap: a cap would strand approvals behind it again. The
cache bounds the cost instead, to one scan per card per window.
### Evidence
New colocated test
`packages/core/src/channels/__tests__/agent-channels-approval-history.test.ts`
follows the issue's steps: a real `Mastra` + `InMemoryStore`, a mapped
thread, an `AgentChannels` rebuilt from `channelConfig` with the same
adapter and StateAdapter, and clicks through the real Chat
`processAction`. Only the dispatch boundary is recorded, via the
documented subclass hooks.
- **Before** (fix reverted to `origin/main`'s `agent-channels.ts`):
`Tests 7 failed | 3 passed (10)`. Failures: approval 60 back not
dispatched, approval 400 back not dispatched, wrong user could approve
when the requester's message was outside the window, two-author turn
could still be answered (whole and split across pages), and an answered
card read the full thread. The 3 passing are controls (recent approval,
`toolApprovers: 'anyone'`, unknown id).
**After:** `Tests 10 passed (10)`.
- Existing channel tests (`src/channels/**`, 13 files): `616 passed`.
`oxlint --type-aware --deny-warnings` and `oxfmt --check` are clean on
changed files. `tsc --noEmit` shows no errors under `src/channels/`.
- Mutation checks: removing either stop condition, or checking
"answered" before the pending entry, fails at least one of the new
tests.
- Not tested: storage adapters other than in-memory (paging relies on
standard `page`/`hasMore`), or a live channel transport or LLM resume.
Lookup cache follow-up (same test file, 12 more tests, storage reads
counted with a spy on the real `InMemoryStore.listMessages`):
- **Before** (`e37d64d`): `Tests 9 failed | 11 passed (20)`. A
non-requester clicking a 400-message-deep card 11 times caused 99 reads
instead of 9; repeated clicks on an unknown or answered card read the
thread every time (45 vs 9); 3 simultaneous clicks read it 3 times; the
requester could answer the same card twice.
**After:** `Tests 22 passed (22)`. Each card is read once; the requester
can still approve after a non-requester was rejected; a failed resume
leaves the card usable; an approval saved after a miss is found once the
60-second window passes; a reused tool call id on a new card or in
another thread gets its own lookup; a claim survives the resumed run
reseeding its card and cache eviction.
- Channel tests (`src/channels/**`, 16 files): `645 passed`. `oxlint
--type-aware` and `oxfmt --check` clean on changed files; `tsc` shows no
errors in the changed files.
Resume follow-up (`5ef5b4a..aaa7eec`). An independent review of
`
|
||
|
|
259f142f46 |
fix(pg): support scalar and nested operators in vector elemMatch filters (#30095) | ||
|
|
0da9a5275d |
fix(observability): redact span errors on traces that hide input or output (#29716)
## Description `tracingOptions.hideInput` / `hideOutput` clear span input and output at export, but `exportSpan()` passed `errorInfo` through untouched. Error messages, the stack header (which repeats the message) and error details often quote exactly the data the flags are meant to hide. Examples: a tool throwing `Invalid IBAN: <the user's IBAN>`, or a provider that refuses a prompt and echoes it back in its response body. This applies to every span type, not just scorers. It came up in review of #29174 ([comment](https://github.com/mastra-ai/mastra/pull/29174#discussion_r4444454609)). On a trace that sets either flag, the exported error now keeps what identifies it and drops the text: ```json // Before { "name": "Error", "message": "Invalid IBAN: DE89370400440532013000", "stack": "Error: Invalid IBAN: DE89370400440532013000\n at validate (tools/iban.ts:12:11)" } // After { "name": "Error", "message": "[REDACTED]", "stack": "Error: [REDACTED]\n at validate (tools/iban.ts:12:11)" } ``` `id`, `name`, `domain`, `category` and the stack frames are kept. From `details`, only the provider fields that `apiCallErrorDetails` already sanitizes are kept (`statusCode`, `url`, `isRetryable`), so `responseBody` and free-form `MastraError.details` are dropped. Either flag triggers this, because an error can quote either side. The redaction happens at export, next to the existing input/output check, so all exporters and bridges get it and the live span keeps the real error for in-process use (metrics status, span processors). Traces without the flags are unchanged. New integration test (`observability/mastra/src/hidden-trace-errors.integration.test.ts`) runs a real agent, Observability instance and TestExporter. It covers a tool error and a provider API error under `hideInput` only and `hideOutput` only, plus unhidden controls and stack-header edge cases. All four hidden-trace cases fail on `main`. Two open questions for reviewers: should we keep a small allowlist of id-like `MastraError.details` keys (`agentName`, `toolId`, `runId`) instead of dropping them all? And are we fine with `error.message` grouping in Datadog-style dashboards showing `[REDACTED]` for hidden traces? After #29174 merges, a failing scorer step on a hidden trace is covered by this same rule. I'll add that case to the scorer redaction test once both have landed. ## Related issue(s) Follow-up to #29174. ## Type of change - [x] Bug fix (non-breaking change that fixes an issue) ## 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 When a trace hides input or output, this change also hides secrets in exported errors. It preserves safe error identity and relevant stack frames without exposing hidden data. ## Changes - Redacts exported error messages and stack headers as `[REDACTED]`. - Applies redaction when `hideInput` or `hideOutput` is enabled. - Preserves error identity fields and safely correlated stack frames. - Omits free-form error details from redacted exports. - Replaces unsupported stack formats with a redacted header. - Leaves live errors and unhidden traces unchanged. - Uses wrapped error causes when capturing stack information. - Adds integration tests for tool errors, provider errors, wrapped causes, and stack edge cases. - Adds a patch changeset for `@mastra/observability`. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Ehindero Israel <iehindero419@stu.ui.edu.ng> Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com> |