Pleach + Mastra
Coexist with Mastra — keep the workflow primitive, the hosted dashboard, vector DB, and evals; add `@pleach/core` for the audited LLM turn inside the step. Not a migration.
This page is the coexist pattern: @pleach/core as the LLM-turn
substrate inside a Mastra workflow step, neither package
replacing the other. The other coexist patterns —
Anthropic SDK,
OpenAI SDK,
Inngest — follow the same posture; if
you're moving off a different orchestration stack, see the
Migrate & coexist docs.
Mastra and Pleach aren't competing for the same slot. Mastra
wraps the workflow — Workflow and Agent primitives,
step-based durable execution, vector DB integrations, an evals
module, a hosted observability dashboard. Pleach owns the LLM
turn inside the workflow step — the typed AuditableCall row
in your Postgres, family-locked provider routing, replay from
the record, subagent cost rollup to the parent turnId.
If you're already on Mastra, don't rip it out. Wrap your
runtime.executeMessage call inside a Mastra workflow step — or
use Pleach's SessionRuntime as the engine behind what would
otherwise be a Mastra Agent. The hosted dashboard, the workflow
graph, and the evals stay; the agent turn underneath gains the
audit row, the family lock, and replay from the record.
The architecture
┌─────────────────────────────────────────────────────────────┐
│ Mastra Workflow │
│ - Step-based durable execution │
│ - Hosted observability dashboard │
│ - Vector DB integration │
│ - Evals module │
│ - Agent network / suspend + resume │
│ │
│ ┌───────────────────────────────────────────────────────┐ │
│ │ step.execute(async ({ inputData }) => { │ │
│ │ │ │
│ │ Pleach SessionRuntime │ │
│ │ - AuditableCall row → your Postgres │ │
│ │ - Family-lock at session start │ │
│ │ - Replay from the record │ │
│ │ - Subagent rollup to parent turnId │ │
│ │ │ │
│ │ }) │ │
│ └───────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────┘Mastra's workflow events and hosted dashboard are the
operational trail — what step ran, what suspended, what the
graph looked like, what the eval scored. Pleach's AuditableCall
ledger is the business trail — what tools the agent invoked,
which subagents spawned, what each cost, attributed to the turn
the user typed, written to a row in your Postgres. Finance
reads Pleach; product and on-call read Mastra.
Vocabulary mapping
If you're coming from Mastra docs, the rough one-to-one:
| Mastra | Pleach | Notes |
|---|---|---|
Agent | SessionRuntime + a system prompt | Pleach has no Agent class — the system prompt is plugin-contributed; the loop is runtime.executeMessage. |
agent.generate({ messages }) | for await (const e of runtime.executeMessage(sessionId, msg)) | Pleach is stream-first. Collect into a final string with collectStream(...) if you want generate-shaped sync. |
agent.stream(...).fullStream | runtime.executeMessage(...) (the same async iterable) | The Pleach StreamEvent discriminated union is richer than fullStream — tool / subagent / interrupt / checkpoint events. |
model: "openai/gpt-4o" (model-router string) | new AiSdkProvider({ model: openrouter("openai/gpt-4o") }) | Pleach goes through the AI SDK provider; OpenRouter gives the same <family>/<model> swap pattern. See Providers → Same shape, different provider. |
Workflow + createStep | Not a Pleach primitive | Workflows are out of scope for @pleach/core. Compose with Mastra (this page), Inngest (with-inngest), or LangGraph. |
| Scorers attached to an agent | @pleach/eval new EvalSuite({ ... }).run() | Pleach evals are CI-shaped, not in-line. Production sampling is @pleach/observe's job. |
| Memory primitives | @pleach/core/memory + @pleach/core/store; threads move with importMastraThread + importSessions (@pleach/core/sessions) | Similar conceptually; the import writes history only. See Memory. |
Hosted Mastra Studio (localhost:4111) | No Pleach equivalent | The explicit trade — see Playground & devtools. |
If you've never read Mastra docs, skip this table — it's only useful for translating between two vocabularies.
The code shape
// mastra/index.ts
import { Mastra } from "@mastra/core";
import { createWorkflow, createStep } from "@mastra/core/workflows";
import {
createPleachRuntime,
type StreamEvent,
} from "@pleach/core";
import { SupabaseAdapter } from "@pleach/core/sessions";
import { AiSdkProvider } from "@pleach/core";
import { anthropic } from "@ai-sdk/anthropic";
import { z } from "zod";
// Mastra's step primitive — durable, observable, replayable
// at the workflow layer. The body wraps a Pleach turn.
const agentTurnStep = createStep({
id: "agent-turn",
inputSchema: z.object({
sessionId: z.string(),
tenantId: z.string(),
userId: z.string(),
prompt: z.string(),
}),
outputSchema: z.object({
events: z.array(z.any()),
}),
execute: async ({ inputData }) => {
// Build the runtime per request. createPleachRuntime is the
// zero-config factory — pass the per-request fields.
const runtime = createPleachRuntime({
tenantId: inputData.tenantId,
userId: inputData.userId,
storage: new SupabaseAdapter({ client: supabase }),
provider: new AiSdkProvider({
model: anthropic("claude-sonnet-4-5"),
}),
});
// Inside the Mastra step, runtime.executeMessage gives you
// the AuditableCall row in your Postgres, family-lock, replay
// from the record, and the subagent rollup, on one chained
// record.
const collected: StreamEvent[] = [];
for await (const evt of runtime.executeMessage(
inputData.sessionId,
inputData.prompt,
)) {
collected.push(evt);
}
return { events: collected };
},
});
export const chatWorkflow = createWorkflow({
id: "chat-turn",
inputSchema: agentTurnStep.inputSchema,
outputSchema: agentTurnStep.outputSchema,
})
.then(agentTurnStep)
.commit();
export const mastra = new Mastra({
workflows: { chatWorkflow },
});Three things this pattern gives you that a plain Mastra Agent
doesn't:
- The
AuditableCallrow lands in your Postgres while the step is running. Finance can sum the model-call cost for a tenant since a given date straight from the call ledger, without parsing Mastra's workflow event store, which is shaped for the dashboard. Calls that write the prompt cache are priced only when the call reports its 5-minute/1-hour write split and there is a rate for each, and marked unpriced otherwise, so that sum leaves the unpriced ones out. The row is keyed(sessionId, turnId, stageId, seqWithinTurn), joinable to billing and to a compliance review, and it exists whether the Mastra step succeeds, suspends, or fails — it was written during the LLM call, not at workflow completion. - Family-lock survives step retry and suspend/resume. If the Mastra step resumes after an interrupt, the session stays in the model family it locked at start. When a model fails, the cascade retries within that family and never silently widens. Mastra's workflow primitive is provider-agnostic by design; the lock lives at the Pleach layer.
- Subagents spawned by the agent roll their cost back to the
parent
turnIdviaSpawnTreeState. Mastra's agent network lets you compose multiple agents, and@mastra/pgstoresestimatedCostper generation; rolling a child spawn's cost up to the turn that caused it is your code. Pleach's spawn record keys it for you.
Using Pleach instead of Agent inside a Mastra workflow
The pattern above wraps a Pleach turn inside a Mastra step. An
adjacent pattern is to keep Mastra's workflow + dashboard + evals
and use Pleach's SessionRuntime as the underlying engine for
what would otherwise be a Mastra Agent. The workflow node calls
runtime.executeMessage rather than agent.generate /
agent.stream. You keep Mastra's orchestration surface and you
get the Pleach audit row + family-lock + replay from the record in
exchange for hand-wiring the agent-shape Mastra's Agent class
gives you for free.
Both shapes are honest. Pick the wrap when the team is already
shipping Mastra Agents and you want the audit row added. Pick
the replace when you're starting fresh and want the runtime
substrate to be the agent.
Already on Mastra?
Mastra @mastra/core@1.78.0 is native for more of this than any
other host. Each other row alone is a side module beside it.
Pleach's column is what the runtime path does today; the four interactions that get hard
together are on the landscape page.
| Capability | Native on Mastra (@mastra/core@1.78.0) | Easy beside it | Hard in combination | Pleach today |
|---|---|---|---|---|
| Row per attempt | — | — | wrap every model slot (memory, titles, processors, scorers) | On the built-in providers, every request the runtime sends writes its own row, retries included, for sub-agents too; a provider that doesn't declare per-attempt rows keeps one row per call. The provider SDK's own retries are turned off so none hide inside it. An attempt cut off by an abort still closes its row. |
| Chained row | — | — | none at the row level (@mastra/pg rows aren't chained); 10 parallel tools commit out of order | Call rows are hash-chained by default, in Postgres and in the quickstart store. The verifier names the first row that doesn't match. It catches an edit, a backfill or a deletion; it doesn't stop one, and an unkeyed chain can be rewritten end to end by anyone with write access. |
| Typed keys + sub-agent rollup | — | with tracing sampling always | — | the root turn and the subagent depth on every row |
| Cost per turn and tenant | semi-native: @mastra/pg stores estimatedCost per generation, plus organizationId | — | — | modelCall.costUsd on each per-call row (costOmitted says why when it is absent). Calls that write the prompt cache are priced only when the call reports how many writes were 5-minute and how many 1-hour and there is a rate for each, and marked unpriced otherwise. Rollup by the root turn. |
| Tenant on row, span and HTTP | ≈native: requestContext | — | — | The tenant id on every row and span. Providers stamp it on outbound HTTP as x-tenant-id by default; tenantHeader: false turns that off and tenantHeader: "<name>" renames it. |
| Scrub before write | — | — | plaintext in 5+ tables first | A default PII redactor runs on the call ledger before the row is hashed. Opt out explicitly with piiRedactorNoop(). Event-log scrubbers run on the Postgres and SQLite writers by default; opt out of SQLite scrubbing with createSqliteDurableStore(path, { redaction: "off" }) (the sidecar uses PLEACH_REDACT=0). |
| Replay without re-firing | serves a recorded response (processLLMRequest → { response }, toolMocks); naming divergence is a hand-roll | — | — | Replay re-serves a turn's recorded responses instead of calling the model. replayRecordedTurn (from @pleach/replay/recorded) replays a recorded turn against its original record and names the first request that drifted; steps the runtime doesn't fingerprint yet (decision, synthesize) are marked blind, so a turn on a stock runtime is never reported matched. |
| Fork and rewind | timeTravel (step), cloneThread (message) | — | — | A fork's first row commits to the parent row it branched from; verifyBranchPoint checks it. A rollback leaves a tombstone row. |
| Erasure with a chain | — | — | not provided | Crypto-shred erasure keeps every event-log row hash verifying. Call-ledger rows are sealed per subject by default wherever a key store is configured; shredding the subject's key keeps every call-row hash verifying and makes the sealed fields unreadable. User ids and the row's wrapper columns aren't erased, and the quickstart's default store has no key store, so its rows stay plaintext unless you pass subjectKeys. |
| Human-in-the-loop | suspend and resume | — | — | N |
| Checkpoints and crash resume | workflow snapshots | — | — | N |
| Family lock | — | with a trap: fallback switches family with a warning | — | A session stays in one model family. When a model fails, the cascade retries within that family and never silently widens, including for models outside the routing matrix. The old cross-family fallback is opt-in. |
| OTel threading | retries aren't spans | — | — | parent-threaded spans |
What gets hard on Mastra together
- Every model slot is a call. Memory, thread titles, processors
and scorers each call a model. Memory's default model is
google/gemini-2.5-flash, so a session can leave your chosen family without any agent asking it to. - A refusal becomes a model switch. A middleware refusal is retried three times and then falls through to the next model in the fallback list, which can be a different family.
- Parallel tools commit out of order. Ten parallel tool calls write their rows in completion order, not call order.
Where each is load-bearing
| Concern | Mastra's slot | Pleach's slot |
|---|---|---|
Workflow primitive (Workflow, steps, suspend/resume) | Built-in | None — Pleach is per-turn |
| Hosted observability dashboard | Built-in (their key DX advantage) | None — bring Datadog / Honeycomb |
| Vector DB integration | First-class (multiple stores) | None — DIY behind a tool |
| Evals module | Built-in (@mastra/evals) | CI-shaped evals (@pleach/eval) |
Agent abstraction (Agent class) | Built-in (instructions + tools + model) | SessionRuntime + plugin contract |
| Per-call audit row in YOUR schema | Workflow events are dashboard-shaped | AuditableCall row keyed (tenantId, turnId) |
| Hosted control plane (cloud) | Yes (Mastra Cloud) | None — Pleach is a runtime library |
This table covers the slots outside the grid above. The coverage maps overlap on "agent abstraction" and "evals": both ship those, with different shapes. They diverge sharply everywhere else: Mastra owns the workflow graph and the hosted dashboard; Pleach owns the row in your DB and replay from the record. That's why the partnership reads cleanly — neither package is doing the other's job badly.
When you don't need Mastra
- A per-request agent turn that completes inside one HTTP
request, with no scheduled jobs, no fan-out, no vector DB
needs, and no workflow graph to model. You can call
runtime.executeMessagedirectly from an API route and skip the workflow layer entirely. - The Pleach checkpointer covers your in-session time-travel. Cross-step workflow durability — suspend a step, resume it later, fan out across N branches, schedule a cron — is Mastra's slot, not Pleach's.
Stay on Mastra alone if
- Single-tenant prototype with no audit obligation, no per-tenant cost rollup, and no replay requirement. Mastra alone is enough — the hosted dashboard gives you a perfectly good operational view for that shape.
- The comparison page covers when the AI SDK alone is enough and when Mastra alone is enough. Reach for Pleach when the audit row, the family lock, or replay from the record shows up on the requirements list.
Mastra Cloud, the dashboard, and the bits Pleach intentionally doesn't ship
Mastra's hosted dashboard is the part of the product Pleach has
no equivalent for, and intentionally so. Pleach is a library that
writes rows into a database you own. The dashboard you build on
top of those rows is yours to ship — wire Datadog, Honeycomb,
Grafana, or a custom Postgres view; the
OTel spans and the
AuditableCall row are the materials.
If you want a hosted dashboard out of the box, Mastra ships one. If you want the rows in your own schema with no vendor lock-in on the audit surface, Pleach ships that. The pairing pattern gives you both: Mastra's dashboard for the workflow trail, your own Postgres for the audit trail.
Where to go next
Pleach + Inngest
The same coexist posture for durable-execution platforms — Inngest, Trigger.dev, DBOS, Temporal.
Pleach + Anthropic SDK
Coexist with the Anthropic SDK as transport — prompt caching, the latest tools API, batches, files.
Pleach + OpenAI SDK
Coexist with the OpenAI SDK — Chat Completions, the Responses API, structured outputs.
The AuditableCall row
What lands in your Postgres for each model call, and what you can join it against.
Pleach + OpenAI Agents SDK
Already on @openai/agents? What the Agents SDK does natively, what is easy beside it, and what gets hard when you need all of it on one record.
Pleach + Inngest
Coexist with Inngest (or Trigger.dev / DBOS / Temporal) — keep durable steps, retries, and scheduling; add `@pleach/core` as the LLM-turn substrate inside the step. Not a migration.