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

61 commits

Author SHA1 Message Date
Abhi Aiyer
ffc23d28fa
feat(mastracode): simplify Factory local development (#24632)
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-09-22 07:49:45 -07:00
Tyler Barnes
825285e155
chore(mastracode): replace understand-pr and understand-issue skills (#24625)
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
2026-09-21 20:21:14 -07:00
Caleb Barnes
752c0c98ba
perf(factory): skip the git pull in materialize; share the repo clone with templates (#22840)
Every session start ran `git pull --ff-only` on a checkout that was
already in the sandbox. That is the normal case: a VM booted from a repo
template image has the repo on disk at the template's pinned commit
(detached HEAD), and a VM resumed after idling is sitting on its session
branch. `git pull` fetches before it checks whether HEAD can move, so on
a fresh VM it was several seconds of network for a result git then
discarded; the session branch checkout that runs right after fetches the
base branch it needs anyway.

Materialize now leaves an existing checkout of the repo alone and clones
only when there is none (a base-image boot, a wiped disk). The one thing
it still does on re-open is scrub a tokenized `origin` an earlier failed
start might have left behind. Syncing a session branch with the remote
is the session's business, as it is for a human on a laptop.

The clone command itself moves into `@internal/workspace` (private,
bundled into consumers) so the repo templates in `@mastra/e2b` and
`@mastra/platform-workspace` bake the same `--depth=1 --single-branch`
clone into their images that Factory makes at runtime. Both paths yield
the same checkout, and template builds transfer far less history.

Start-path phases also log `[factory:timing]` lines now
(`workspace.onStart(<outcome>)`, `workspace.setup-marker`,
`workspace.setup`), plus a line saying whether the setup marker matched,
so a slow start shows where the time went. `*.local.mjs` / `*.local.ts`
probe scripts are gitignored.


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

Factory now keeps existing repository checkouts unchanged instead of
downloading them again. It clones missing repositories, verifies that
reused checkouts belong to the expected repository, and logs startup
progress.

## Changes

- Preserve existing Factory checkouts without running `git pull
--ff-only`.
- Validate reused `origin` remotes against the expected GitHub
repository format.
- Clone missing repositories and scrub tokens after failures.
- Add `[factory:timing]` logs for startup phases and setup-marker
checks.
- Add `repoCloneCommand` and `RepoCloneCommandOptions` to
`@internal/workspace`.
- Use shallow, single-branch clones in E2B and platform workspace
templates.
- Add tests for checkout reuse, remote validation, token cleanup, clone
commands, and template behavior.
- Ignore `*.local.mjs` and `*.local.ts` probe scripts.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: CalebBarnes <CalebBarnes@users.noreply.github.com>
Co-authored-by: Mastra Code (anthropic/claude-fable-5-1) <noreply@mastra.ai>
2026-09-02 14:52:50 -07:00
Lennart
e983f74987
chore(*): Update/unify/add READMEs (#22858)
Co-authored-by: Mastra Code (openai/gpt-5.6-sol) <noreply@mastra.ai>
2026-09-02 14:36:59 +02:00
Caleb Barnes
55c9e248c2
Run Slack messages as the sender's Mastra tenant (#20060)
Message the Slack bot and it answers as **you** — your agent, your model
credentials, your factory — instead of as whatever identity the server
happened to boot with. Message it without a linked account and it does
nothing except offer you a Connect button.

That requires the inbound Slack message to carry a Mastra tenant into
the run it starts. This PR adds the one piece of core plumbing that
makes that expressible, then builds the whole feature outside core.

## The core seam

An agent run resolves credentials from the `user` entry on its
`RequestContext`. Channel handlers had no way to reach that object: core
didn't construct it until three frames after a handler had already been
called, so a host could see the inbound message but couldn't influence
the run it triggered.

So core now builds the `RequestContext` **per message, at the handler
boundary**, and hands it to the handler:

```ts
handlers: {
  onDirectMessage: async (thread, message, defaultHandler, ctx) => {
    ctx.requestContext.set('user', { id, organizationId });
    await defaultHandler(thread, message); // runs as that user
  },
}
```

That is the entire addition to `@mastra/core`: **one field**,
`ChannelHandlerContext.requestContext`. Core still adds its own channel
and render-context entries afterward and dispatches with the same
instance. No new types — `RequestContext` is long-standing public API.

Per-message construction is the load-bearing detail. The handler context
is otherwise built once at `initialize()` and shared, so hanging a
request context on it would leak one Slack user's tenant into the next
user's run. A test drives two messages sequentially and asserts the
second cannot see the first's writes.

`ChannelHandler`'s `ctx` parameter is now **non-optional**. Handler
implementations are unaffected — TypeScript lets a 3-parameter function
satisfy a 4-parameter type — but code that *calls* a `ChannelHandler`
value with three arguments must now pass the context. The alternative
was forcing every host into `ctx!.requestContext` or a guard that
silently drops the tenant, which is the exact bug this feature exists to
prevent. Both changes are described in the changeset at a minor bump.

Everything else — who a Slack sender maps to, whether they're allowed to
run, which factory they route to — lives in the host, because none of it
is core's business.

## Linking an account

Linking is **OpenID Connect only**. `/connect/slack` is a bare redirect
to Connected accounts: it reads no tenant and writes no link. The link
row is written in one place, the OIDC callback, after Slack asserts the
`(team, user)` pair in a signed `id_token`.

This matters because the obvious alternative is unsound. Putting the
Slack identity in the Connect card's deep link means trusting the link
to name the account rather than proving the visitor controls it —
forward the card and the recipient binds *your* Slack identity to
*their* tenant. Requiring the assertion costs a client id and secret on
top of the signing secret and bot token a Slack app already needs.

The link is keyed `(platform, external_team_id, external_user_id)` in a
new `channel-identity` storage domain, and carries a default factory so
a user in several factories doesn't get asked every time.

## Gating

The host gate is the only gate, and it runs before any dispatch:

- **Unlinked** → ephemeral Connect card, no run.
- **Linked, no default factory** → factory picker, no run.
- **Linked and routed** → tenant stamped on the request context, then
dispatch.

The tenant stamp is written for *any* linked sender, before routing —
not only on the routed path. A linked sender whose factory routing
returns `ungated` still exits with a tenant; putting the stamp after
routing would silently run them on default credentials. A dedicated test
pins that, and fails if the stamp moves into the routed branch.

## Integrations own their channels

`FactoryIntegration` gains a `channels()` slot next to `routes()`, so an
integration contributes a channel provider and the factory calls
`setChannels` during `prepare()`, gated on its storage domain being
ready. Slack ships as the first implementation, `SlackIntegration`,
owning both its connect routes and its channel wiring.

The host entry no longer knows anything about Slack beyond passing
credentials — it constructs the integration when
`SLACK_APP_SIGNING_SECRET` is present and is otherwise net **smaller**
than before this feature existed.

## Session links

The "View Session" card deep-links into the resolved factory.
`?resourceId=` is appended only for chat-only threads, where the
workspace segment is the literal `channel` and the resource exists
nowhere else in the URL. Repo-backed threads already carry the real
resourceId as the path segment, so the parameter is redundant there and
omitted.

## Reviewing

Read `packages/core/src/channels` first — it's small, and 385 of its 443
lines are tests. Then `mastracode/web/src/web/channels/slack/` for
gating and card construction, then the factory integration slot.

Worth the most scrutiny: the per-message request-context construction in
`agent-channels.ts` (the leak risk), and the tenant stamp's position
inside `gateDispatch` (the silent-wrong-credentials risk). Both have
tests written to fail if the code moves.

Verified live end to end: unlinked DM → Connect card and no run; link
via Slack OIDC; DM again → session created under the linked tenant,
confirmed against the database.

## Not here

`/factory` is removed along with the `onSdkReady` seam it was built on.
A follow-up adds a declarative `handlers.onSlashCommand` slot and
rebuilds the command on it. Also deferred: factory selection during
linking, and work-item creation from Slack threads.

---------

Co-authored-by: CalebBarnes <CalebBarnes@users.noreply.github.com>
Co-authored-by: Mastra Code (anthropic/claude-fable-5) <noreply@mastra.ai>
Co-authored-by: Abhi Aiyer <abhiaiyer91@gmail.com>
2026-07-29 09:51:55 -07:00
Abhi Aiyer
ba369f2a0a
feat(isolated-vm): add IsolatedVmCodeModeTransport for in-process Code Mode isolation (#20359)
Co-authored-by: Mastra Code (anthropic/claude-fable-5) <noreply@mastra.ai>
2026-07-29 17:54:54 +02:00
Abhi Aiyer
62182171b6
fix(factory): reliable sandbox reattach and guaranteed review kickoff delivery, plus board UX affordances (#20294)
Co-authored-by: Mastra Code (anthropic/claude-fable-5)
Co-authored-by: Mastra Code (anthropic/claude-fable-5) <noreply@mastra.ai>
2026-07-28 19:05:07 +02:00
Ehindero Israel
9c1df2e153
Refactor GitHub triage command and consolidate skills (#19106)
Co-authored-by: Ehindero Israel <ehindero@Ehinderos-MacBook-Pro.local>
Co-authored-by: Mastra Code (openai/gpt-5.5) <noreply@mastra.ai>
2026-07-10 16:17:08 +02:00
Anurag Ojha
18c4288450
docs: add CRITICAL_PATHS.md for AI triage automation (#19091)
## Description

Adds a machine-readable list of 61 brittle code paths with owners and
reasons. The `gh-triage` agent reads this file to request reviews from
the right CODEOWNER when a PR touches sensitive areas.

- 61 entries covering loop, message-list, workflows, durable agents,
LLM, streaming, processors, memory, deployer, storage, server, auth,
license, signals, events, background tasks, agent-controller, and more
- All owners cross-verified against `.github/CODEOWNERS` — zero
mismatches
- File placed in `.mastracode/` alongside other triage automation config
- `.gitignore` updated to un-ignore the new file

## Type of Change

- [x] New feature (non-breaking change that adds functionality)

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## ELI5
This PR adds a “cheat sheet” that automation uses to spot when a pull
request touches especially fragile parts of the codebase. When that
happens, it automatically routes the PR to the right internal reviewers
(and sometimes closes it early for outside contributors).

## Summary
- Added `.mastracode/resources/CRITICAL_PATHS.md`, a machine-readable
list of brittle “critical paths” (65 `path` entries) with GitHub owner
lists and short explanations for why each area is sensitive.
- Documented triage behavior for `gh-triage`: compare PR-changed files
to the configured globs, auto-close PRs from non-`mastra-ai` authors
when they hit `packages/core/src/loop/loop.ts` or
`packages/deployer/**`, and otherwise add the matching `owners` as
reviewers while including matched paths + reasons in the triage comment.
- Covered critical areas including loop/workflows, message lists,
durable agents, LLM + streaming, processors, memory, deployer, storage,
server + route/handler boundaries, auth, license/signals/events,
background tasks, and agent-controller/session engines.
- Updated the root `.gitignore` so the broader `.mastracode/*` ignore
pattern is overridden to keep `.mastracode/resources/CRITICAL_PATHS.md`
tracked (un-ignoring the `resources` directory and explicitly
re-unignoring the file).
- Owners were cross-verified against `.github/CODEOWNERS` with zero
mismatches.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Signed-off-by: Anurag Ojha <aojharaj2004@gmail.com>
2026-07-08 17:39:28 +05:30
Ehindero Israel
7565cd3a33
OSS MastraCode gh-triage command (#18692)
## Summary

This PR adds `gh-triage`, a MastraCode command for turning a GitHub
issue or PR into a clear, evidence-backed next action.

`gh-triage` acts as the first point of contact for maintainer triage: it
resolves whether the input is an issue or PR, gathers the right context,
assigns severity/scope, writes one lifecycle artifact, and ends with
explicit action choices instead of a loose summary.

## What `gh-triage` can do

- Triage one open GitHub issue or active PR from first contact through
the next maintainer action.
- Resolve issue vs PR inputs before creating local output, and avoid
producing artifacts for closed issues, closed PRs, or draft PRs.
- Gather code-accurate context using shared PR-review and issue-debug
checklists.
- Find routing-relevant PRs that close or fix an issue, while keeping
mention-only PRs as debugging context.
- Inspect PR metadata, linked issues, changed files, checks, comments,
review threads, and automated reviewer feedback such as CodeRabbit.
- Produce concise severity, scope, assessment, evidence, branch output,
prepared comments, and label recommendations in a single lifecycle file.
- Always prepare maintainer notes for PR branches, with author
pre-review comments only when concrete author changes are needed.
- Offer a maintainer fix-up path for small low/medium-severity PR
issues, followed by posting maintainer notes with updated context.
- Keep GitHub side effects gated: no posting comments, labeling,
assigning, closing, tagging, external coordination, fixes, commits, or
PR updates happen without explicit user approval.

## Supporting context files

The command includes shared context-gathering checklists for:

- PR review context: changed files, checks, linked issues, review
threads, CodeRabbit/automated review comments, and relevant repo
evidence.
- Issue debug context: issue details, related PRs/comments, likely
affected areas, reproduction signals, and repo evidence.

These shared files are instruction-only. `gh-triage` owns the lifecycle
artifact and uses the shared context to keep triage accurate without
creating extra review/debug files.

## Test plan

- Ran semantic guard checks for command frontmatter, single-artifact
triage behavior, shared context wiring, stale `--file`/subagent wording,
maintainer-notes requirements, maintainer PR fix-up options, and
CodeRabbit/comment context.
- Ran Prettier checks on the changed MastraCode command and
shared-context markdown files.

---------

Co-authored-by: Ehindero Israel <ehindero@Ehinderos-MacBook-Pro.local>
Co-authored-by: Mastra Code (openai/gpt-5.5) <noreply@mastra.ai>
2026-07-01 10:57:12 +01:00
Abhi Aiyer
c241b929dc
feat(core): introduce the Harness Session — own per-conversation state (#18107)
## What

Introduces the Harness **`Session`** — the Harness now exposes
`harness.session`, a class that owns the per-conversation runtime state
that previously lived flattened on the `Harness` instance. The Harness
stays the **shared host** (storage, the thread lock, the agent registry,
the event bus); the Session owns the state scoped to a single user's
conversation.

This PR consolidates the full extraction series (grants → token usage →
mode → model → run identity/abort → stream subscription → suspensions →
follow-ups → approval → identity → thread binding + data domain).

## Why

In a multi-user host, one initialized Harness serves many users — so
per-conversation state can't live as globals on the Harness or two users
would clobber each other. Pulling that state onto a dedicated `Session`
draws a clean boundary: **Harness = initialized shared machinery; a
user's Session owns its own conversation state and reads.** Today this
ships single-player (one Session per Harness), but it's the foundation
the multi-session work builds on.

## What `harness.session` owns

| Domain | Surface |
| --- | --- |
| `session.identity` | `resourceId` / `defaultResourceId` — the stable
"who" |
| `session.thread` | active-thread binding
(`getId`/`set`/`clear`/`isSet`/`requireId`) + thread data domain
(`list`, `getById`, `listMessages`, `listActiveMessages`,
`firstUserMessage(s)`, settings) via an injected storage gateway |
| `session.mode` / `session.model` | selected mode/model (source of
truth), switch sequence, per-mode model memory (Harness keeps
`config.modes`) |
| `session.run` | transient run identity (run/trace id, op counter) +
abort control |
| `session.stream` | live agent-thread subscription handle + dedup key;
adds `session.getCurrentRunId()` / `session.abortRun()` |
| `session.suspensions` | parked-tool resume map for `ask_user` /
`request_access` / `submit_plan` |
| `session.followUps` | messages queued to send after the active run
finishes |
| `session.approval` | interactive tool-approval gate +
`session.respondToToolApproval(...)` |
| grants / token usage | session-scoped permission grants and the live
token-usage tally (Harness still persists usage to thread metadata,
since usage is thread-scoped) |

## Removed from the Harness public API

Read these through `harness.session.*` instead:

- `getSessionGrants()` / `getTokenUsage()` → `session.getGrants()` /
`session.getTokenUsage()`
- `getCurrentModelId()` / `hasModelSelected()` → `session.model.get()` /
`session.model.hasSelection()`
- `getCurrentRunId()` / `getCurrentTraceId()` / `isRunning()` →
`session.getCurrentRunId()` / `session.run.getTraceId()` /
`session.run.isRunning()`
- `getCurrentThreadId()` / `getThreads()` / `listThreads()` /
`listMessages()` / `listMessagesForThread()` /
`getFirstUserMessage(s)ForThread(s)()` / `getThreadSetting()` /
`setThreadSetting()` → `session.thread.*`
- `getResourceId()` / `getDefaultResourceId()` → `session.identity.*`
- `getFollowUpCount()` → `session.followUps.count()`
- `respondToToolApproval()` → `session.respondToToolApproval()`
- `getCurrentModeId()` → `session.mode.get()`
- `getCurrentMode()` → `session.mode.resolve()` (resolves the selected
mode id against the host's `config.modes` catalog, injected into the
Session)
- `hasPendingSuspensions()` → `session.suspensions.hasPending()`
- `isCurrentThreadStreamActive()` → `session.stream.isActive()`

Only `Harness.abort()` and `setResourceId()` remain — they are genuine
host orchestrators (they touch the display-state mirror, the
agent-stream subscription, and thread teardown) that delegate the
relevant reads/writes to the session.

`session.mode` exposes two complementary accessors: `get()` returns the
selected mode **id** (a `string`, mirroring `session.model.get()`), and
`resolve()` returns the full `HarnessMode` definition by looking that id
up in the injected mode catalog.

## Persistence

Grants and the live token-usage counter are in-memory (grants reset on
restart, matching prior behavior). Mode/model selection persists
per-thread through thread metadata via an injected store; token usage
persists to thread metadata (thread-scoped). No
`SessionRecord`/`SessionStorage` is introduced.

## Abort semantics

`session.abortRun()` tears down the run cleanly: it aborts the live
subscription, marks the run aborting, drops any parked tool
**suspensions**, and releases a parked tool-**approval** gate. A run
sitting in a tool `suspend()` (`ask_user` / `request_access`) or
awaiting `approval.arm()` is not actively streaming, so aborting the
controller alone would leave it orphaned. The approval gate is resolved
as a `decline` (rejecting the gated tool) so the run finalizes instead
of hanging.

## Verification

- `@mastra/core` typecheck clean; harness suite **350/350** pass
(includes a new test asserting abort releases a parked approval gate).
- `mastracode` typecheck clean; **1317/1319** pass (2 pre-existing
`mastraGatewayBaseUrl` failures, unrelated). The count dropped from 1324
because the deleted `HarnessCompat` shim took its dedicated test file
(and a now-moot v1 case) with it.
- Mastra Code **e2e: 102 passed / 18 skipped / 0 failed**.
- Single consolidated changeset: `@mastra/core` minor + `mastracode`
patch.

## Follow-ups (not in this PR)

Deferred, single-player-safe: move per-user **app state**
(`state`/`stateSchema`), **`displayState`**, and the **thread
lifecycle** (`create`/`switch`/`clone`/`delete`/`rename`) onto the
Session, and decide event-listener ownership for multi-session.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## ELI5
Previously, the “current conversation” state was stored on the main
`Harness` object. This PR moves that temporary, per-chat state into a
dedicated `Session` (`harness.session.*`), so the `Harness` can stay
focused on being the shared engine while each conversation owns its own
thread, model/mode, streaming, approvals, and permissions.

## Summary of Changes

### Core Refactor: Introduce `Session` as the per-conversation state
owner
- Added a new `Session` implementation
(`packages/core/src/harness/session.ts`) that consolidates state that
used to live on `Harness`, including:
  - **Identity** (`resourceId` / `defaultResourceId`)
- **Threads** (active thread binding, thread/message listing, thread
settings, first-user message helpers)
- **Mode/Model selection** (mode switching with a version guard;
per-mode model persistence)
  - **Run lifecycle** (run/trace IDs, operation counter, abort control)
- **Streaming** (deduped agent-thread subscription lifecycle + abort/run
linkage)
- **Suspensions** (parked tool-call resume map for approval-gated flows
like `ask_user`, `request_access`, `submit_plan`)
- **Follow-ups** (queued messages to send after the active run finishes)
- **Interactive tool approval gate** (`session.approval`, single
in-flight gate)
- **Grants + token usage** (session-scoped, in-memory only; resets on
restart)
- Permissions/token usage behavior remains in-memory and resets on
restart, matching prior behavior.

### Update `Harness` to delegate to the new `Session`
- `Harness` is now a thin orchestrator around an internal `#session`,
exposed via `harness.session`.
- Removed many session-flavored `Harness` public methods/getters;
callers now use `harness.session.*` for things like grants/token
usage/current mode/model/current thread identity and related
thread/message operations.
- `Harness.abort()` and `Harness.setResourceId()` remain on `Harness`,
delegating into session lifecycle where needed.

### Tool-approval gate no-hang fix
- Added `SessionApproval.cancel()`, so when
`session.abortRun()`/`harness.abort()` happens it releases any parked
tool-approval gate by resolving it as a **decline**, preventing runs
waiting for approval from hanging indefinitely.
- Covered by an updated harness ask-user test.

### Session request-context / observability updates
- `HarnessRequestContext` now includes a nested `session` snapshot
(`HarnessRequestSession` with `modeId` + `modelId`) instead of a
top-level `modeId`.
- Updated observability `requestContextKeys` paths to use
`harness.session.modeId` / `harness.session.modelId` (instead of older
`harness.modeId` / `harness.state.currentModelId` naming).

### Thread-list merging moved into Session (and compatibility shim
removed)
- The legacy/v1 thread merging behavior no longer lives in a
`HarnessCompat` shim; it now lives under the session thread-data store.
- As a result, `session.thread.list()` returns the merged thread result
set.

### MastraCode + TUI migration to `harness.session.*`
- Updated the TUI, scenarios, headless logic, analytics, and tests to
use `harness.session.*` for:
  - thread identity and thread listing
  - model/mode selection checks
  - run state (running/trace IDs)
  - stream activity checks
  - tool approvals and suspensions
  - follow-up counts
- session grants (notably the `/permissions` UI now reads via
`ctx.harness.session.getGrants()`)

### Exports + docs
- Re-exported `Session` from `packages/core/src/harness/index.ts`.
- Updated changeset documentation describing `harness.session` as the
owner of per-conversation runtime state and mapping removed `Harness`
APIs to `harness.session.*`.

### Verification
- `@mastra/core`: typecheck clean (349/349 tests passing)
- `mastracode`: typecheck clean (1322/1324 tests passing; 2 pre-existing
unrelated failures)
- Mastra Code e2e: 102 passed / 18 skipped / 0 failed
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Mastra Code (anthropic/claude-opus-4-8) <noreply@mastra.ai>
2026-06-18 06:47:14 +02:00
Ward Peeters
c624361369
use exact hash matching (#16873) 2026-05-21 15:22:11 +02:00
Abhi Aiyer
44fd5fc8a2
fix(cli): use cwd-relative temp dirs in source-hash tests (#16863)
Co-authored-by: Mastra Code (anthropic/claude-opus-4-6) <noreply@mastra.ai>
2026-05-20 17:10:51 -04:00
Mohamed BEN HAMDOUNE
522f44d947
fix(core): bound process handle output retention (#16574) 2026-05-14 10:46:42 -04:00
Shane Thomas
719e5b1d19
Add PR review workflow skills (#16456)
## Summary
Adds two local workflow skills for improving PR review quality:

- `pr-splitter` helps break large, tangled PRs into smaller reviewable
PRs while tracking extraction and drift in a local scratchpad.
- `pr-explainer` helps generate approachable, self-contained HTML review
aids in `.pr-review/` that explain what changed, why it matters, how it
works, and how it was verified.
- Adds `.pr-review/` to `.gitignore` so generated local review pages are
not committed by default.

## Test plan
- Read both skill files to verify trigger descriptions and workflow
guidance.
- Ran `git diff --cached --check` before committing to verify the patch
has no whitespace errors.

No package changes, so no changeset was added.

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

This PR adds two simple helpers to make code reviews easier: one helps
split big, messy changes into bite-sized PRs, and the other generates
local HTML review pages that explain what changed and how it was tested.
It also tells Git to ignore the folder where those HTML review pages are
written.

## Changes

**Added**
- `.claude/skills/pr-explainer/SKILL.md` — Workflow for creating
self-contained HTML "PR explainer" pages under `.pr-review/`. Covers git
inspection commands, recommended narrative/order and HTML section
structure, diagram guidance, focused diff-snippet formatting,
verification/proof requirements (example commands), a final checklist,
and expected default outputs (path, coverage, sections, evidence, and
untracked status).
- `.claude/skills/pr-splitter/SKILL.md` — Workflow for splitting large,
tangled PRs into multiple smaller PRs. Includes snapshotting the
original branch, inventorying changes by review unit, a local
uncommitted scratchpad template, strategies (stacked vs parallel,
foundation + follow-ups), safe extraction techniques (path-level and
hunk-level restore), independent verification steps, drift management
(rebasing dependent PRs, recording differences), a reviewer-facing PR
description template, common failure modes, and a required checklist.

**Modified**
- `.gitignore` — Added `.pr-review/` so generated local review pages are
not committed by default.

## Review Effort

Low to Medium — documentation-only changes. No code, dependency, or
changeset modifications. Total added documentation ≈ 260 lines across
the two skill files plus one .gitignore entry.

## Test Plan

Reviewer read both SKILL.md files to verify trigger descriptions and
workflow guidance; author ran `git diff --cached --check` before
committing to confirm no whitespace errors.

[![Review Change
Stack](https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui.svg)](https://app.coderabbit.ai/change-stack/mastra-ai/mastra/pull/16456)
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Mastra Code (openai/gpt-5.5) <noreply@mastra.ai>
2026-05-12 11:08:42 -05:00
Damien Schneider
8275db30af
chore(playground): add opt-in react-grab dev tool (#16258)
## Summary

- Add [`react-grab`](https://github.com/aidenybai/react-grab) as an
opt-in dev tool in `packages/playground`, gated by
`VITE_REACT_GRAB=true`
- Mirrors the same pattern already used in the `platform` repo
- Gitignore `.env.local` / `.env.*.local` so dev opt-in files stay local

## Why

Inspecting React components during studio dev work. Useful for me today;
opt-in for anyone else who wants to try it. No team-wide adoption
assumed.

## Bundle / consumer impact: zero

- Loaded via `if (import.meta.env.DEV && import.meta.env.VITE_REACT_GRAB
=== 'true') { void import('react-grab') }`
- In prod build, `import.meta.env.DEV` is replaced by Vite with literal
`false` → Rollup dead-code-eliminates the whole branch → `react-grab`
never enters the prod chunk graph
- `react-grab` lives in `devDependencies` of the private
`@internal/playground` package, so it is not installed for users of the
published `mastra` CLI

## How to enable locally

```bash
echo "VITE_REACT_GRAB=true" >> packages/playground/.env.local
pnpm dev:playground
```

## Test plan

- [x] `pnpm --filter @internal/playground lint` passes for the changed
files (pre-existing unrelated parser error in `vitest.setup.ts`)
- [x] Dev server with `VITE_REACT_GRAB=true` loads `react-grab`
- [x] Dev server without the env var does not load it
- [ ] Reviewer confirms prod build does not contain `react-grab` in the
output chunks

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

## ELI5
This PR adds an optional developer tool called react-grab to the
playground package that helps developers debug React applications. It
only loads when you specifically enable it with an environment variable,
and it has zero impact on users or production builds because it's
completely invisible when disabled.

## What Changed

### Core Addition
- **react-grab DevDependency**: Added `react-grab@^0.1.32` as a
development dependency in `packages/playground/package.json`

### Integration Points
- **Conditional Dynamic Import**: Added a development-only code block in
`packages/playground/src/main.tsx` that dynamically imports react-grab
only when both `import.meta.env.DEV` is true AND the environment
variable `VITE_REACT_GRAB` is set to `'true'`. The import is triggered
via `void import('react-grab')` to execute side effects without
awaiting.

### Type Safety
- **TypeScript Declarations**: Added `ImportMetaEnv` and `ImportMeta`
interface definitions in `packages/playground/src/vite-env.d.ts` to
properly type the new `VITE_REACT_GRAB` environment variable as an
optional readonly string property.

### Local Development Files
- **.gitignore**: Added `.env.local` and `.env.*.local` entries to
prevent local environment configuration files from being committed to
version control.

## How to Use Locally
To enable react-grab during local development:
```
echo "VITE_REACT_GRAB=true" >> packages/playground/.env.local
pnpm dev:playground
```

## Impact Assessment
- **Production**: Zero impact. Vite performs dead-code elimination on
the conditional `import.meta.env.DEV` branch, so react-grab is never
bundled in production builds.
- **CLI Consumers**: No impact. The tool is a devDependency of the
private `@internal/playground` package and doesn't affect published
consumers.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-05-06 13:01:21 +02:00
Daniel Lew
cf25a03132
feat(mastracode): add evals system with live scorers, offline experiments, and Studio feedback (#15642)
Adds an evals system for MastraCode with live scoring, offline
experiments, and a feedback loop that flows through to Studio.

**Live scorers** run during sessions to grade agent quality in real
time. An outcome scorer checks build/test pass status, tool errors,
stuck loops, regressions, and autonomy. An efficiency scorer measures
redundancy, turn density, retry patterns, and read-before-edit
discipline. Both are configurable and non-blocking.

**Offline experiment pipeline** lets you seed datasets from real traces,
run them in isolated sandboxes, and score results against ground truth.
Includes outcome-match, trajectory-efficiency, and LLM judge scorers.

**`/feedback` command** lets users submit thumbs up/down, ratings, and
comments on traces. Feedback routes through the observability event bus
so it reaches cloud exporters even when DuckDB is locked. Non-retryable
stream errors automatically emit thumbs-down feedback for error
tracking.

**`/experiment` command** seeds datasets from traces, runs experiments,
and shows results.

**Studio feedback tab** shows feedback on traces/spans with a count
badge, paginated list, and detail dialog — matching the existing scores
pattern.

Also adds `prepareRun`/`filterRun` utilities and `getCurrentTraceId()`
to core, enriches agent spans with model/settings metadata, and fixes
requestContext filtering in observability.

---------

Co-authored-by: Mastra Code (anthropic/claude-opus-4-6) <noreply@mastra.ai>
2026-04-27 12:42:43 -07:00
Damien Schneider
165e40a1ca
chore(examples/agent, playground): dev DX cleanup (#15786)
## Summary

Developer-experience cleanup for `examples/agent` plus a small
playground dev fix.

**1. `examples/agent` dev scripts**
- `dev:ui` now uses `concurrently --kill-others-on-fail` so `mastra dev`
and the playground subprocess die together on Ctrl+C — no more orphan
processes hogging port 4111.
- New `clean` script wipes regenerated state (`.mastra`, `*.duckdb*`,
`vector.db`, `database.sqlite`) for resets after schema bumps or core
rebuilds.

**2. Untrack runtime DB artifacts**
- Removed tracked `mastra-observability.duckdb`, `.wal`, `vector.db` —
regenerated on first run.
- Root `.gitignore` now ignores `*.duckdb*` and `*.sqlite*`.

**3. Playground vite proxy in dev**
(`packages/playground/vite.config.ts`)
- Sets `MASTRA_AUTO_DETECT_URL=true` in `studioStandalonePlugin` so the
playground hits `window.location.origin` and goes through the existing
`/api` vite proxy instead of hardcoded `http://localhost:4111`. Avoids
CORS+credentials mismatch in dev. Dev-only — production deployer
continues to read the env var at runtime, so prod behavior is unchanged.

## Test plan
- [ ] `pnpm dev:ui` from `examples/agent`, Ctrl+C, verify `lsof -i
:4111` reports nothing.
- [ ] Re-run `pnpm dev:ui`, confirm port 4111 is reused.
- [ ] `pnpm clean && pnpm dev:ui` regenerates duckdb without migration
errors.
- [ ] In dev, network tab shows API calls hitting same-origin `/api/*`
(proxied), no CORS errors.

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

## ELI5
This PR cleans up the developer experience when working with the agent
example by making it easier to run and reset the playground during
development. It adds a script that runs both the Mastra server and
playground together with better shutdown handling, provides a command to
clean up temporary database files, and fixes the playground to use the
same API endpoint as the dev server (avoiding cross-origin issues).

## Changes

### Developer Experience Improvements for examples/agent

Updated `package.json` dev scripts and dependencies:
- Modified `dev:ui` script to use `concurrently` with named processes
(`--mastra,playground`) and `--kill-others-on-fail` flag, replacing the
previous background process approach to ensure both services terminate
together on Ctrl+C
- Added `clean` script to remove regenerated runtime artifacts
(`.mastra/`, `mastra-observability.duckdb*`, `vector.db`,
`database.sqlite`)
- Added `concurrently@^9.1.2` as a devDependency

### Runtime Artifact Exclusion

Updated `.gitignore`:
- Added `*.duckdb*` and `*.sqlite*` patterns to prevent runtime database
artifacts from being tracked across the repository

### Playground Dev Configuration

Modified `packages/playground/vite.config.ts`:
- Extended `studioStandalonePlugin`'s HTML transformation to inject
`'true'` for the `%%MASTRA_AUTO_DETECT_URL%%` placeholder, allowing the
playground to detect and use `window.location.origin` in development
mode instead of hardcoding `http://localhost:4111`
- This change enables the playground to route API requests through the
existing same-origin `/api` proxy in dev, avoiding CORS and credentials
mismatches
- Production builds remain unaffected

### Minor Code Organization

Reordered React imports in
`packages/playground/src/hooks/use-background-tasks.ts` for consistency
(no functional changes).

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-04-27 17:12:44 +02:00
Ehindero Israel
edf8f9d9cd
feat: add Mastra Responses and Conversations APIs (#14339) 2026-04-01 13:05:13 +01:00
Daniel Lew
260fe1295f
feat(playground): evaluation dashboard, review pipeline & sidebar restructure (#14649)
Co-authored-by: Greg Lobinski <greglobinski@gmail.com>
Co-authored-by: Greg Lobinski <32480082+greglobinski@users.noreply.github.com>
Co-authored-by: Mastra Code (anthropic/claude-opus-4-6) <noreply@mastra.ai>
2026-03-26 13:23:59 -05:00
Tony Kovanen
7302e5ce0f
refactor(memory): Refactor ObservationalMemory internals (#14453)
## Summary

Major refactor of the ObservationalMemory (OM) class to clean up its
internal architecture. OM went from ~3840 lines to ~2770 lines by
extracting focused components and eliminating unnecessary coupling.

### Processor/OM boundary cleanup
- Processor owns orchestration (when to
buffer/activate/observe/reflect), OM owns primitives (how to do each
operation)
- Removed `observeWithActivation` and related processor-specific methods
from OM

### Strategy pattern for observations
- Replaced three duplicated observation methods (~650 lines) with proper
strategy classes sharing a common lifecycle via an abstract base class
- `ObservationStrategy.create(om, opts).run()` selects and runs the
right strategy based on scope
- Strategies take a `StrategyDeps` interface — no direct
`ObservationalMemory` class dependency

```
observation-strategies/
  index.ts           — exports + static factory (single OM import, builds deps)
  types.ts           — ObservationRunOpts, ObserverOutput, ProcessedObservation
  base.ts            — abstract ObservationStrategy + StrategyDeps interface
  sync.ts            — SyncObservationStrategy (thread-scoped sync)
  async-buffer.ts    — AsyncBufferObservationStrategy (background buffered)
  resource-scoped.ts — ResourceScopedObservationStrategy (multi-thread)
```

### Component extraction
Extracted three focused classes from OM — all fully decoupled (no OM
class import):

- **ObserverRunner** (194 lines) — LLM observer agent calling,
degenerate detection, retry logic
- **ReflectorRunner** (710 lines) — LLM reflector agent, sync/async
reflection, buffered reflection activation
- **BufferingCoordinator** (175 lines) — Static buffering state machine,
async operation tracking, interval boundary logic

### Turn/Step API
- ObservationTurn — per user→agent cycle, manages record caching and
cross-thread context
- ObservationStep — per agentic loop iteration, runs the
activate/buffer/observe/reflect pipeline
- Processor rewritten to use Turn/Step (~580 → ~170 lines)

### Storage improvements
- **Atomic swapBufferedToActive**: Added conditional WHERE clauses to
Postgres, MongoDB, LibSQL storage adapters to prevent double-activation
without in-memory locks
- **Sealed ID elimination**: Replaced ID-based sealed tracking with
message-level flag check (metadata.mastra.sealed)

### Cleanup
- Dropped threadIdCache (pointless memoization of xxhash)
- Removed as-any casts for private method access — made methods properly
public with @internal tsdoc
- Dead code removal: isObserving DB flag, countMessageTokens,
acquireObservingLock/releaseObservingLock, ~10 cascading dead private
methods
- Pure function extraction: filterObservedMessages, getBufferedChunks,
sortThreadsByOldestMessage, stripThreadTags → message-utils.ts
- Moved wrapWithThreadTag, wrapObservations, persistMarkerToStorage,
persistMarkerToMessage into strategy base class

## Test plan
- [x] npx vitest run — 612 passed
- [x] npx tsc --noEmit — no errors
- [x] Lint clean — 0 errors
- [x] No import type { ObservationalMemory } in any extracted component
(only in index.ts factory)
- [ ] Test with mastra code

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

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

* **New Features**
  - Persist observer-suggested thread titles
- Shared observational-memory engine with new getContext and direct
persistMessages APIs
- Exposed primitives (buffer → activate → observe) and an async
buffering coordinator
- Resource-scoped multi-thread observation and reflection/compression
workflows
- New demo scripts showcasing multi-step, streaming, and SDK
integrations

* **Bug Fixes**
  - Hardened buffered→active activation to avoid race conditions

* **Tests**
- Extensive integration suites for long, multi-turn, and edge-case
scenarios

* **Documentation**
- New demos, analysis, production-readiness, and refactor plans for
observational memory
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Tyler Barnes <tylerdbarnes@gmail.com>
Co-authored-by: Mastra Code (openai/gpt-5.4) <noreply@mastra.ai>
2026-03-25 16:12:38 +02:00
Tyler Barnes
367f8f4fee
fix: stabilize flaky observational memory token counter tests (#13871)
This keeps the observational memory token counter tests from timing out
in CI by reusing one explicit `o200k_base` counter instead of
constructing a fresh heavy encoder in each custom-encoding assertion.

Before:
```ts
const o200k_base = require('js-tiktoken/ranks/o200k_base');
const counter = new TokenCounter(o200k_base);
```

After:
```ts
const counter = getSharedCustomCounter();
```

It also adds the local `.mastra-om-repro/` debug directory to
`.gitignore` and includes a changeset for `@mastra/memory`.


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

## Summary by CodeRabbit

* **Chores**
  * Updated project ignore patterns.

* **Tests**
  * Optimized test infrastructure with enhanced utilities.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-03-05 12:54:02 -08:00
Eric Pinzur
31c78b3eb2
feat(core): Add unified observability type system and context propagation (#13058)
## Summary

- Introduces a new observability type system in
`packages/core/src/observability/types/` with interfaces for logging
(`LoggerContext`), metrics (`MetricsContext`, `Counter`, `Gauge`,
`Histogram`), scores (`ScoreInput`, `ExportedScore`), feedback
(`FeedbackInput`, `ExportedFeedback`), and an event bus
(`ObservabilityEventBus`)
- Creates `ObservabilityContext` — a unified interface combining
`tracing`, `loggerVNext`, `metrics`, and `tracingContext` (alias) — that
all internal execution contexts now extend
- Adds `createObservabilityContext()` factory and
`resolveObservabilityContext()` resolver with no-op defaults for
graceful degradation
- Refactors `tracing.ts` to extract a `SpanData` base interface, split
`RecordedSpan`/`RecordedTrace` (immutable storage types) from live
`Span` interfaces, and reorganize core infrastructure types into
`core.ts`
- Migrates 60+ sites across tools, workflows, agents, evals, processors,
LLM, and stream systems to use `ObservabilityContext` (or `Partial<>` at
public boundaries) instead of the former `TracingContext`.
- Establishes a consistent forwarding pattern using `...rest`
destructuring + `resolveObservabilityContext()` so observability fields
flow through without listing them individually
- Tightens internal-only sites from `Partial<ObservabilityContext>` to
full `ObservabilityContext` so future logging/metrics additions won't
require signature changes
- Adds `loggerVNext` and `metrics` getters to the `Mastra` class

## Motivation

This PR lays the groundwork for unified observability in Mastra. Today,
only tracing (`TracingContext`) flows through execution contexts.
Logging is ad-hoc via `IMastraLogger`, and there is no metrics system at
all. Neither logging nor metrics are available in
tool/workflow/processor execute callbacks.

By establishing the type system and context plumbing now (all within
`@mastra/core`), subsequent PRs can add concrete implementations (event
bus, storage adapters, exporters) without touching interface signatures
across the codebase.

## Design decisions

**`loggerVNext` naming**: Uses VNext suffix to avoid collision with the
existing `logger: IMastraLogger` infrastructure logger used throughout
the codebase (`MastraPrimitives.logger`, `LoopOptions.logger`,
`MastraBase.logger`). Follows established codebase pattern:
`MastraLLMVNext`, `streamVNext`, `generateVNext`.

**Partial vs Full boundary**: Public-facing APIs (tool execute, workflow
step execute, processor context) use `Partial<ObservabilityContext>` —
users shouldn't need full observability to call APIs.
Internal/infrastructure code uses full `ObservabilityContext` —
guarantees tracing/logging/metrics are always available.

**Source vs Derived**: `tracingContext` is the source (position in span
tree). `loggerVNext` and `metrics` are derived (rebuilt from current
span for correlation).

**Forwarding pattern**: To avoid listing `tracingContext`, `tracing`,
`loggerVNext`, `metrics` individually at every call site, all forwarding
uses a two-step pattern:

1. Destructure known fields + `...rest` to capture the observability
fields
2. `const observabilityContext = resolveObservabilityContext(rest)` to
fill in defaults
3. Forward via `...observabilityContext` spread at downstream calls

This keeps forwarding sites concise and means adding a new observability
signal requires zero changes at forwarding sites.

**Span-creation boundaries left intact**: Sites that call
`getOrCreateSpan()` or `createChildSpan()` to create a new span, then
derive a fresh `ObservabilityContext` via `createObservabilityContext({
currentSpan })`, are intentionally not changed — they correctly
establish new observability scopes rather than forwarding the parent's.

## What changed

### New files

| File | Description |
| --------------------------------------- |
--------------------------------------------------------------------------------------------------------------
|
| `observability/types/core.ts` | `ObservabilityContext`,
`ObservabilityInstance`, `ObservabilityExporter`, event bus, bridge,
config interfaces |
| `observability/types/logging.ts` | `LoggerContext`, `LogLevel`,
`ExportedLog`, `LogEvent` |
| `observability/types/metrics.ts` | `MetricsContext`, `Counter`,
`Gauge`, `Histogram`, `ExportedMetric`, `MetricEvent`, cardinality
config |
| `observability/types/scores.ts` | `ScoreInput`, `ExportedScore`,
`ScoreEvent` |
| `observability/types/feedback.ts` | `FeedbackInput`,
`ExportedFeedback`, `FeedbackEvent` |
| `observability/context-factory.ts` | `createObservabilityContext()`,
`resolveObservabilityContext()` |
| `observability/context-factory.test.ts` | Unit tests for factory and
resolver |

### Modified files (by area)

**Observability** — Refactored `tracing.ts` (extracted `SpanData` base,
split `RecordedSpan`/`RecordedTrace`), expanded `no-op.ts` with
`noOpLoggerContext`/`noOpMetricsContext`, updated barrel exports

**Agent** — `agent.ts` tool listing/conversion methods and
sub-agent/workflow execution callbacks use `...observabilityFields` rest
+ `resolveObservabilityContext`; `agent-legacy.ts` `__primitive` and
`prepareLLMOptions` use same pattern; `trip-wire.ts`
`getModelOutputForTripwire` forwards full context; workflow steps
(`prepare-memory-step.ts`, `stream-step.ts`, `map-results-step.ts`) use
rest spread

**Workflows** — `step.ts` removed redundant standalone `tracingContext:
TracingContext` from `ExecuteFunctionParams` (already provided by
`Partial<ObservabilityContext>`); `workflow.ts` agent-step and tool-step
execute functions use `...observabilityFields` rest pattern; handlers
(`entry.ts`, `step.ts`, `control-flow.ts`, `sleep.ts`) all use `...rest`
+ `resolveObservabilityContext(rest)` so `observabilityContext` is
available for future logging/metrics; `evented/workflow.ts` creates
context at processor call sites; `default.ts` passes context through
execution engine

**Evals** — `base.ts` scorer workflow uses rest spread; `run/index.ts`
forwards full obs context to `executeWorkflow`, `executeAgent`, and all
`scorer.run()` calls; `hooks.ts` `runScorer` requires full context;
`scoreTracesWorkflow.ts` resolves at boundary

**Processors** — `runner.ts` internal methods require full
`ObservabilityContext`; boundary methods (`runProcessInputStep`,
`runProcessOutputStep`) stay Partial; six processor implementations
(`pii-detector`, `moderation`, `structured-output`, `language-detector`,
`prompt-injection-detector`, `system-prompt-scrubber`) use
`...observabilityFields` rest in public methods and accept full
`ObservabilityContext` in private methods

**Memory processors** — `message-history.ts` and `semantic-recall.ts`
use `& Partial<ObservabilityContext>` on method signatures

**Stream** — `output.ts` bridges Partial options to Full at
`processPart`/`runOutputProcessors` calls via
`resolveObservabilityContext()`

**LLM** — `model.ts` methods destructure obs fields (with `_` prefix
aliases to exclude from AI SDK `...rest`), create `observabilityContext`
for internal use; `model.loop.ts`, `model.loop.types.ts`,
`base.types.ts`, `llm/index.ts` extend context

**Tools** — `types.ts` extends `Partial<ObservabilityContext>`;
`builder.ts` uses `createObservabilityContext()`

**Loop** — `types.ts` extends `Partial<ObservabilityContext>`;
`network/index.ts` resolves at bridge site

**Mastra class** — Added `loggerVNext` and `metrics` getters


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

* **New Features**
* Unified ObservabilityContext with factory/resolver to provide tracing,
structured logging, and metrics.
* Mastra accessors for structured logging and metrics (loggerVNext,
metrics).
* New public types for logging, metrics, scoring, and feedback to
surface observability signals.

* **Chores**
* Propagated ObservabilityContext across APIs and workflows for
consistent telemetry.
* Added no-op fallbacks and tests to ensure graceful degradation when
observability implementations are absent.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Sprite <noreply@sprite.dev>
2026-02-25 23:22:37 -06:00
Abhi Aiyer
cb8c38e6f8
feat(memory, opencode): add @mastra/opencode plugin and standalone observe() API (#12925)
Adds `@mastra/opencode` — a plugin that brings Mastra Observational
Memory into [OpenCode](https://opencode.ai) sessions. Also enhances the
core `observe()` API to support external integrations.

The plugin hooks into OpenCode's lifecycle to automatically observe
conversations, inject compressed observations into the system prompt,
and discard already-observed messages — keeping context lean as
conversations grow.

```ts
// .opencode/mastra.json
{ "model": "google/gemini-2.5-flash", "scope": "thread" }
```

```ts
// Standalone observe() with external messages and lifecycle hooks
await om.observe({
  threadId,
  messages: externalMessages,
  hooks: {
    onObservationStart: () => showToast('Observing...'),
    onObservationEnd: () => showToast('Done!'),
  },
});
```

Core `@mastra/memory` changes: `observe()` now takes object params
(breaking), accepts external messages without double-storing, includes
threshold checks, and exports `OBSERVATION_CONTEXT_PROMPT` /
`OBSERVATION_CONTINUATION_HINT` for reuse by integrations.

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

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

* **New Features**
* OpenCode plugin integration for Observational Memory with session
wiring and status reporting
* Standalone observe() API that accepts external messages and lifecycle
hooks
(onObservationStart/onObservationEnd/onReflectionStart/onReflectionEnd)
* New public observation helpers and prompts for injecting observations
and continuation hints
* Progress/status tools and a memory observations command plus an
example standalone observe script

* **Breaking**
* observe() signature changed to an object parameter: update calls to
use { threadId, resourceId, messages, hooks }

* **Tests**
* Added test suite covering the standalone observe() API and hook
behavior
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: Tyler Barnes <tylerdbarnes@gmail.com>
Co-authored-by: Mastra Code <noreply@mastra.ai>
2026-02-11 14:20:05 -08:00
Ward Peeters
1c861b669e
fixes (#12943)
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2026-02-11 11:40:04 +01:00
Tyler Barnes
61f44a2686
feat(memory): async buffering for observational memory (#12891)
Observations are now pre-computed in the background as conversations
grow. When the context window fills up, buffered observations activate
instantly — no blocking LLM call mid-conversation.

Async buffering is on by default. To disable:

```ts
observationalMemory: {
  model: "google/gemini-2.5-flash",
  observation: { bufferTokens: false },
}
```

Model is now required when passing a config object. Use
`observationalMemory: true` for the defaults (gemini flash + async
buffering), or set a model explicitly.

`shareTokenBudget` isn't compatible with async buffering yet — you need
to set `bufferTokens: false` if you're using it. This is temporary.

New streaming events: `data-om-status` (replaces `data-om-progress`),
plus `data-om-buffering-start`/`end`/`failed` markers for UI feedback.

While these are technically breaking changes - I'm deciding to roll them
out anyway: no one has tried the feature before yesterday for the most
part, and these new settings/defaults are much better than before, so
lets set people up for success now instead of in 6 months when we do a
v2

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

* **New Features**
* Async buffering for observational memory enabled by default with
background pre-computation, activation, and new streaming events for
buffering lifecycle and status.

* **Configuration Updates**
* New buffering controls (interval, activation, block thresholds);
observationalMemory true now selects a default model; buffering can be
disabled.

* **UI Improvements**
* Background Processing footer, buffering/activation markers, badges and
visuals to reflect buffering/activation states.

* **Bug Fixes**
  * Flushed assistant text parts now materialize as separate messages.

* **Documentation**
* Docs updated with async buffering guidance, examples, and
configuration notes.

* **Tests**
* Added tests for sealed-message flush behavior and buffering scenarios.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Mastra Code <noreply@mastra.ai>
2026-02-10 13:00:18 -08:00
Shane Thomas
3efbe5ae20
feat: implement agent versioning and storage system (#12038)
## Summary

This PR implements a comprehensive agent versioning and storage system
that enables dynamic agent management across the Mastra framework. The
implementation spans multiple layers from core storage interfaces to UI
components.

- Add storage interface for agent versioning with CRUD operations
- Implement PostgreSQL, LibSQL, and MongoDB storage adapters for agent
versions
- Add server API handlers and routes for agent and version management
- Create complete UI components in playground-ui for agent CRUD
operations (dialogs, forms, lists)
- Add React Query hooks for agent and version management
- Implement JavaScript client SDK with version management support
- Add comprehensive test coverage across client SDK and server
components
- Add EXPERIMENTAL_FEATURES flag to control dynamic agents UI visibility
- Remove .context folder from git tracking and add to .gitignore

## Test plan

- [ ] Verify agent CRUD operations work in the playground UI
- [ ] Test version management (create, list, compare, restore)
- [ ] Confirm PostgreSQL, LibSQL, and MongoDB storage adapters function
correctly
- [ ] Validate API endpoints return expected responses
- [ ] Check that existing tests pass
- [ ] Verify typecheck passes
- [ ] Confirm build succeeds

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

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

* **New Features**
* Full stored-agent workflows: create, edit, delete via dialogs and
comprehensive form.
* Agent versioning UI: list, paginate, save, activate, restore, delete,
compare with side-by-side and JSON diffs.
* AI-assisted Instructions Enhancer and enhanced model/tool/scorer
pickers (searchable multi-selects, per-scorer sampling).
  * Experimental feature flag to enable new UI flows.

* **Chores**
* Client, server and storage plumbing to support versioning and caching.

<sub>✏️ Tip: You can customize this high-level summary in your review
settings.</sub>
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Sonnet 4.5 <noreply@anthropic.com>
Co-authored-by: Abhi Aiyer <abhiaiyer91@gmail.com>
2026-01-21 23:42:30 -08:00
Marvin Frachet
39e28da0ac
feat: add e2e-frontend-validation skill for playground packages (#11804)
https://github.com/user-attachments/assets/cd9716db-4f90-47ae-b282-75884035a12c



Adds a Claude Code skill that uses Playwright MCP to visually verify
frontend changes in the playground packages.

When modifying `packages/playground` or `packages/playground-ui`, Claude
will now automatically test the affected routes in a browser to catch
visual/functional regressions before committing.

The skill:
- Starts the dev server if needed
- Navigates to impacted routes with Playwright MCP
- Verifies changes render correctly
- Captures screenshots for review

Also updated both playground package CLAUDE.md files to reference the
new skill.

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

* **Documentation**
* Added comprehensive end-to-end frontend validation workflow using
Playwright, including prerequisites and step-by-step testing guidance.
* Established mandatory E2E testing requirements for the frontend and
playground packages.

* **Chores**
* Ignored local Playwright MCP artifacts to keep working directories
clean.

<sub>✏️ Tip: You can customize this high-level summary in your review
settings.</sub>
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-01-12 10:35:26 +01:00
Tyler Barnes
c23723399c
feat(@mastra/memory): migrate memory to processors (#9254)
Co-authored-by: Daniel Lew <danielshlomolew@gmail.com>
2025-11-26 14:12:46 -05:00
Tony Kovanen
d3e89dd4fc
Server adapters (#10263)
Generic ServerAdapter class and hono/express implementations. Using the
new implementation in the mastra dev server.

## Description

<!-- Provide a brief description of the changes in this PR -->

## Related Issue(s)

<!-- Link to the issue(s) this PR addresses, using hashtag notation:
#123 -->

## 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
- [x] Test update

## Checklist

- [ ] 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


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

* **New Features**
- MCP support: server registry, server detail, tools listing/execution,
and SSE/message endpoints.
  - New A2A endpoints for agent card and agent execution.
- Server-adapter packages and export for Hono/Express enabling
adapter-based server integration.

* **Refactor**
- Routing consolidated to a route-driven / adapter pattern across
agents, memory, tools, voice, vector, scores, workflows, logs, and
observability; handlers migrated to route objects.

* **Chores**
  - Added npm scripts for building/testing server adapters.
  - .gitignore updated to ignore *.db files.

<sub>✏️ Tip: You can customize this high-level summary in your review
settings.</sub>
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: mfrachet <marvin@mastra.ai>
Co-authored-by: NikAiyer <nick.aiyer@gmail.com>
Co-authored-by: Taofeeq Oluder <oluderutaofeeq@gmail.com>
2025-11-20 10:08:33 -06:00
Abhi Aiyer
3ff2c17a58
Support aisdk voice models (#10304)
Fixes https://github.com/mastra-ai/mastra/issues/9947

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

* **New Features**
* Add AI SDK speech and transcription support and automatic wrapping of
AI SDK models in CompositeVoice for mixed-provider STT/TTS workflows.

* **Documentation**
* Add AI SDK usage examples and update CompositeVoice docs and examples
to use input/output configuration and real-time guidance.

* **Tests**
* Add comprehensive tests covering AI SDK speech, transcription, and
composite voice round-trip scenarios.

* **Chores**
  * Ignore test output folders and bump related AI SDK dependencies.

<sub>✏️ Tip: You can customize this high-level summary in your review
settings.</sub>
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2025-11-19 23:51:07 -08:00
Greg Lobinski
0d9d56b382
UI elements + Storybook - WIP part 1 (#6748)
## Description

<!-- Provide a brief description of the changes in this PR -->

## Related Issue(s)

<!-- Link to the issue(s) this PR addresses, using hashtag notation:
#123 -->

## Type of Change

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

## Checklist

- [ ] I have made corresponding changes to the documentation (if
applicable)
- [ ] I have added tests that prove my fix is effective or that my
feature works
2025-08-14 12:50:26 +02:00
Kehinde
97c1d5e4bd
Scorers subcommand for adding and listing scorers (#6704)
## Description

This PR adds the scorers subcommand for the cli.

It allows you to
 1. add scorers to the scorers directory
 2. list availble scorers with description

## 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)
- [x] Documentation update
- [x] Code refactoring
- [ ] Performance improvement
- [ ] Test update

## Checklist

- [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

---------

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
2025-08-13 12:14:16 +01:00
Tyler Barnes
8cfef290ee
chore: fix go-to-definition using tsc declaration maps (#6089) 2025-07-30 15:41:00 -07:00
Tyler Barnes
dc4ca0a60a
fix(@mastra/core): undo regression that parsed intentionally serialized message content (#5482) 2025-06-25 16:24:49 -07:00
Tyler Barnes
17d7493ea6
docs: AI SDK v5 beta (#5471)
Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
2025-06-25 09:42:36 -07:00
Ward Peeters
a528bdbb82
add dynamic port to dev server (#4672)
## Description

<!-- Provide a brief description of the changes in this PR -->

add dynamic port to dev server

When port is already in use and not explicetly set, we try to get the
next number


## Related Issue(s)

<!-- Link to the issue(s) this PR addresses, using hashtag notation:
#123 -->

## 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 made corresponding changes to the documentation (if
applicable)
- [x] I have added tests that prove my fix is effective or that my
feature works
2025-06-05 17:27:58 +02:00
Ryan Hansen
c5c615aed3
firebase auth (#4586) 2025-06-03 09:51:54 -07:00
Ward Peeters
3561110d11
update prettier lint (#4189) 2025-05-14 16:22:14 +02:00
Tyler Barnes
93875edd12
fix(@mastra/core, @mastra/memory, @mastra/pg): semantic recall perf + memory bundle size (#3419)
## Semantic recall perf + memory bundle size
Before this it would take around 2.5 to 3 seconds before we sent a req
to the LLM while we were processing semantic recall (embedding messages,
querying db, etc). After this change it takes between 800ms and 1.1s.
This is when using pgvector. This should also have a perf improvement
for other vector stores but probably not as big of a change.

Changes:
1. removed `@mastra/rag` from `@mastra/memory`, now it uses
`tiktoken-js` to do chunking (this should also fix the bundle size issue
https://github.com/mastra-ai/mastra/issues/3309 )
2. uses measured dimensions instead of hardcoded dimensions and
parallelizes embeddings as much as possible (most likely fixes
https://github.com/mastra-ai/mastra/issues/3236 )
3. combines 2 memory.saveMessages calls into one
4. combined another 2 memory.getThreadById() calls into one
5. adds a chunk/embedding in memory cache for Memory
6. swapped out pg vector advisory locks for in memory mutexes (saves
almost a second of time on each request)
7. combined multiple pg queries into single queries, removed extra
checks for if a table/index exists before the query to create it (since
the query that creates them uses `IF NOT EXISTS` anyway)
8. adds an in memory (on the class instance) cache for creating indexes
in pg and for getting index info, saves around 700ms per request

Semantic recall is between 2 to 3 times faster with these changes
2025-04-03 12:28:33 -07:00
chadgratts
ec9fa6a7ea
Add azure voice provider (#2859)
Co-authored-by: Yujohn Nattrass <Yujohn.natt@gmail.com>
Co-authored-by: YujohnNattrass <46704329+YujohnNattrass@users.noreply.github.com>
2025-03-21 22:11:41 -07:00
Ward Peeters
220bc6a432
improve NextJS integration + docs (#1969)
Add guides and update examples for nextjs

---------

Co-authored-by: Ehindero Israel <iehindero419@stu.ui.edu.ng>
2025-03-06 11:03:17 +01:00
YujohnNattrass
0821d6b6f5
feat: deprecate @mastra/speech-openai for @mastra/voice-openai (#1989)
This PR introduces the deprecation of the @mastra/speech-openai package
in favor of the new @mastra/voice-openai package.

OpenAIVoice provides both Text-to-Speech (TTS) and Speech-to-Text (STT)
capabilities
2025-02-24 09:38:22 -08:00
Ward Peeters
1a066d858d gitignore .npmrc 2025-02-19 16:15:19 +01:00
Abhi Aiyer
75b9e1ed15 Bring back ragie 2025-01-30 08:44:22 -08:00
Ward Peeters
4750dde22e
feat: add support first contributor (#1435)
Add contributor action to guide new users
2025-01-23 10:04:20 -08:00
Abhi Aiyer
4139b43627
Deployer revamp (#1481)
- Deployer
- pnpm lock
- Use hono for server
- Hono handler
- WIP deployer
- Deployer
- pnpm lock
- Use hono for server
- Hono handler
- WIP deployer
- serve playground
- rebase branch
- client refresh on file changes
- Fix tools
- fix memory error
- echo tsconfig on cli create
- delete old express server
- WIP new deployer
- Netlify deployer
- deployer moves
- Cloudflare
- Dev works
- Deployer moves
- Remove old templates

---------

Co-authored-by: Ehindero Israel <iehindero419@stu.ui.edu.ng>
2025-01-22 17:49:15 -08:00
Abhi Aiyer
c6248af49f Int progress 2024-12-12 12:38:19 -08:00
Shane Thomas
b95d4becac Remove prisma references and files 2024-11-21 23:26:12 -06:00
dayo
65908aaa79 regen spotify 2024-10-04 11:46:38 +01:00