@diagrid/agent-mastra

中文文档
0.2.0发布于 2026/09/18BUSL-1.1TypeScriptESM + CJS构建来源已验证近 30 天下载 5564

Durable execution of Mastra agents on Dapr Workflows

原始使用文档
文档目录8 节
  1. Status
  2. The two ⚠️ rows
  3. Install
  4. Usage
  5. Module layout
  6. Notes on metadata extraction
  7. License
  8. At-least-once, not exactly-once

@diagrid/agent-mastra

Durable execution of Mastra agents on Dapr Workflows.

The agent's control loop is modelled as a Dapr Workflow and each model call and tool execution as a durable activity, so an agent survives process crashes, sidecar restarts and provider outages without re-running work it already completed.

Status

Working, and verified by running it rather than by inspection — against a local dapr run sidecar and against Diagrid Catalyst, with Ollama (qwen2.5:7b) as the model.

AreaState
Runner lifecycle and workflow naming✅
Durable agent loop (agentWorkflow)✅ model call → tool activities → repeat
Model bridge✅ one step per iteration via clientTools
Tool bridge✅ one checkpointed activity per tool call
Crash recovery✅ tool not re-run after a mid-turn kill (see at-least-once below)
Activity retry (model and tool)✅ in-orchestrator, 3 attempts with durable backoff
Registry metadata (getMetadata())⚠️ the record is correct, but nothing publishes it — see below
Checkpoint persistence⚠️ implemented and tested, but the runner never calls it — see below
Native Dapr activity RetryPolicy❌ not in the JS SDK; the orchestrator retries instead
Component discovery for registry metadata❌ TODO(mastra-adapter)
Tools needing RequestContext / workspace❌ TODO(mastra-adapter)

The two ⚠️ rows

Both are built and unit-tested but have no caller — a working part is not the same thing as a working feature:

  • Checkpoint persistence. DaprMastraCheckpointer.save()/load()/list() have no callers outside their tests. The runner constructs one and exposes it as a public field; nothing writes to it, so load() always returns undefined in practice. Continuing a thread today means passing prior messages into invoke() yourself.
  • Registry metadata. getMetadata() returns a mostly correct record — the examples print it — but nothing publishes it to a state store or agent registry, and three of its fields are not configuration. memory.shortTerm reports { type: 'DaprMastraCheckpointer' }, accurate about intent and ahead of the wiring. agent.maxIterations is hardcoded to 1 and pubsub is { resourceName: '', broadcastTopic: null, agentTopic: null } — both TODO(mastra-adapter) in mapper.ts. Read those three as unset rather than as settings: inspect-agent.ts builds its runner with maxIterations: 10 and will still print 1.

grep -rn 'TODO(mastra-adapter)' . from the repo root lists what is left — six markers. Scoping it to src from this directory finds only three; the other three moved into packages/core with the durable loop. tests/e2e/ runs the examples under a real sidecar in CI, so these claims stay honest.

Install

pnpm add @diagrid/agent-mastra @mastra/core zod

@mastra/core and zod are peer dependencies: your application owns their versions, and installing this adapter never pulls another framework's SDK into your tree. Both have to be named on the install line — a peer dependency is not installed for you.

  • Node.js ≥ 22.13
  • @mastra/core ≥ 1.50 < 2
  • zod ^4

Usage

import { Agent } from '@mastra/core/agent';
import { openai } from '@ai-sdk/openai';
import { DaprWorkflowAgentRunner } from '@diagrid/agent-mastra';

const agent = new Agent({
  id: 'support-agent',
  name: 'support-agent',
  instructions: 'You help customers with billing questions.',
  model: openai('gpt-4o-mini'),
});

const runner = new DaprWorkflowAgentRunner({
  agent,
  name: 'support-agent',
  maxIterations: 10,
});

// Shut down cleanly on SIGINT/SIGTERM (opt-in: a library must not install
// process-wide handlers behind your back).
const disposeHandlers = runner.registerShutdownHandlers();

await runner.start();

const result = await runner.invoke({
  prompt: 'Why was I charged twice?',
  threadId: 'thread-123',
});

console.log(result.text, result.status, result.iterations);

disposeHandlers();
await runner.shutdown();

Prefer runner.schedule(...) when the caller should not block — an agent turn outliving an HTTP request is the normal case, not the exception. It returns the workflow instance id, which you can poll with runner.getWorkflowStatus(id).

Module layout

The same shape every adapter in this repo follows:

FileRole
bridge.tsDrives Mastra one step at a time — the only file that knows Mastra's API
mapper.tsMastraAgentMapper — the BaseAgentMapper implementation
runner.tsPublic entrypoint — DaprWorkflowAgentRunner, lifecycle and invocation
state.tsDaprMastraCheckpointer — core's checkpointer with the mastra prefix
version.tsVersion marker, stamped by the release workflow

The durable agent loop is not here. The orchestrator, its activities, the retry behaviour and the I/O schemas live in @diagrid/agent-core under src/agent/, and this package re-exports them so importing the adapter is still enough to work with a turn. They moved there because none of them mentioned Mastra: leaving them in an adapter meant adapter #2 would copy the durable loop and the cross-language checkpoint key layout, subtle invariants included, and the two would drift.

Notes on metadata extraction

MastraAgentMapper reads a Mastra Agent structurally rather than importing @mastra/core. That is deliberate: importing the framework here would put it in the runtime graph of anyone installing the adapter, which tests/guards/cross-framework-imports.test.ts forbids.

Four consequences worth knowing:

  • Config is read through the class accessors, not the plain properties. A real Agent keeps instructions and tools private and exposes them via getInstructions() and listTools(); reading agent.tools returns undefined. listTools() is async, which is why mapper.mapAgentMetadata() and runner.getMetadata() are async too.
  • All three of Mastra's model forms are supported: the model-router magic string ('openai/gpt-4o-mini'), an OpenAI-compatible config ({ id, url } or { providerId, modelId, url } — how you point at Ollama), and an AI SDK model instance. A malformed router id is echoed back verbatim so the typo is visible in the registry, rather than collapsed to unknown.
  • Mastra also accepts instructions, model and tools as a factory. A factory needs a RuntimeContext that does not exist at registration time, so dynamic config is skipped — the registry shows the static configuration. It does not guess.
  • Tool argument schemas are rendered as JSON Schema via Zod 4's z.toJSONSchema(). Zod 3 schemas and schemas containing transforms are not representable, and degrade to an empty string rather than to [object Object].

See examples/mastra/ — pnpm inspect prints the whole record for a real agent.

License

Business Source License 1.1 — © 2026–Present Diagrid Inc.

At-least-once, not exactly-once

The workflow engine guarantees that each activity runs at least once. Any activity with a side effect must therefore be safe to run twice.

The activity boundary makes a completed call durable: once its result is checkpointed, replay reads the checkpoint rather than calling out again. But there is a window between an activity function returning and the engine durably recording that completion, and a crash inside that window re-runs the activity. For invokeModel that means the model is called — and billed — twice. For a tool it means whatever the tool does happens twice.

So a tool that charges a card, sends an email, or writes a non-idempotent record needs its own idempotency key or conditional write. The engine narrows the window and cannot close it.

The crash-recovery example demonstrates one specific kill timing where the tool is not re-run. It does not, and structurally cannot, demonstrate the absence of this window.

版本与发布记录

@diagrid/agent-mastra 共发布 3 个版本,首次发布于 2026/08/23;过去 12 个月发布了 3 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.2.0latest2026/09/181 个月前
0.1.12026/09/181 个月前
0.1.02026/08/232 个月前

关于 @diagrid/agent-mastra 的常见问题

@diagrid/agent-mastra 是什么?

Durable execution of Mastra agents on Dapr Workflows

如何安装 @diagrid/agent-mastra?

在项目目录运行 npm install @diagrid/agent-mastra,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:zod(^4.0.0)、@mastra/core(>=1.50.0 <2)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@diagrid/agent-mastra 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@diagrid/agent-mastra 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@diagrid/agent-mastra 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=22.13.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@diagrid/agent-mastra 可以商用吗?

@diagrid/agent-mastra 使用 BUSL-1.1 许可。声明的许可为 BUSL-1.1,请阅读许可原文确认使用条件。以上为概括,不构成法律意见,请以许可原文为准。

@diagrid/agent-mastra 的下载量有多少?

根据 npm 官方下载统计,@diagrid/agent-mastra 在 2026/10/12 – 2026/11/10 这 30 天内被下载 5,564 次,日均约 185 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@diagrid/agent-mastra 还在维护吗?

最新版本 0.2.0 发布于 2026/09/18(1 个月前);至今共发布 3 个版本,其中过去 12 个月发布了 3 个;首次发布于 2026/08/23。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。