mastra-harness
Skill2 starsChanged 29 days agoApache-2.0View on GitHub
Run Mastra agents beyond a single request with the harness capabilities: durable agents that survive disconnects and restarts (createDurableAgent, createEventedAgent, createInngestAgent, durable: true), background tasks for slow tools and subagents, thread-scoped goals judged until done, AgentController sessions with modes, approvals, subagents, and channels, workers, and the coding agent factory (createCodingAgent, buildBasePrompt) plus the Mastra Code SDK (mountAgentControllerOnMastra, ACP server). Use this skill whenever the user wants a long-running, resumable, steerable, or interactive agent, a coding agent, a plan-then-build mode switch, or work that keeps going after the HTTP request ends. Triggers on harness, DurableAgent, observe(runId), resumable stream, crash recovery, backgroundTasks, untilIdle, setObjective, goal judge, AgentController, createSession, session.steer, respondToToolApproval, submit_plan, MASTRA_WORKERS, @mastra/code-sdk, mastracode --acp.
- Reads credentials
In this repository46 other files it gives its agents.
- mastra-a2a-acpSkill
- mastra-agent-approval-hitlSkill
- mastra-agentic-uiSkill
- mastra-agent-skillsSkill
- mastra-agentsSkill
- mastra-authSkill
- mastra-browserSkill
- mastra-build-playbookSkill
- mastra-channelsSkill
- mastra-classifierSkill
- mastra-cli-apiSkill
- mastra-client-sdkSkill
- mastra-datasets-experimentsSkill
- mastra-deploymentSkill
- mastra-evalsSkill
- mastra-file-based-agentsSkill
- mastra-framework-integrationSkill
- mastra-guideSkill
- mastra-knowledgeSkill
- mastra-mcpSkill
- mastra-memorySkill
- mastra-migrationsSkill
- mastra-modelsSkill
- mastra-multi-agentSkill
- mastra-observabilitySkill
- mastra-observational-memorySkill
- mastra-platformSkill
- mastra-processors-guardrailsSkill
- mastra-project-setupSkill
- mastra-ragSkill
- mastra-schedulesSkill
- mastra-semantic-recallSkill
- mastra-serverSkill
- mastra-signalsSkill
- mastra-storageSkill
- mastra-streamingSkill
- mastra-structured-outputSkill
- mastra-studio-editorSkill
- mastra-tool-integrationsSkill
- mastra-toolsSkill
- mastra-troubleshootingSkill
- mastra-vector-storesSkill
- mastra-voiceSkill
- mastra-workflowsSkill
- mastra-workflow-suspend-resumeSkill
- mastra-workspace-sandboxSkill
The file
We split this skill into the rules it gives an agent
3 rules. About 0 are common, 1 is distinctive, and 2 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈1
Distinctive · estimate
This author's own choices. Worth a look.
2
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 99
Verify the API: If node_modules/@mastra/ exists, read node_modules/@mastra/core/dist/docs/ and the installed types for DurableAgent, …
- Very specific: line 105
Goals: add goal: { judge, maxRuns } to an agent with memory.
- Distinctive: line 168
Several users share one Session: Create one Session per user or task.
≈ “Common” is an estimate: at least 1 in 5 of the 408,460 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Mastra Harness
Pick and wire the harness capabilities that keep an agent's work durable, visible, and steerable across retries, disconnects, restarts, and long-running goals.
When to use
- A client may disconnect mid-stream and must reconnect without losing chunks
- A run must survive a process crash or rolling deploy
- A tool, workflow, or subagent is slow and should not block the agent's reply
- An agent should keep working toward one objective until a judge says it is done
- Building an interactive product: sessions per user, plan and build modes, tool approvals, steering, follow-ups
- Building a coding agent with a workspace, task tracking, and retry defaults
- Serving Mastra Code to your own UI or an ACP editor client
- Splitting API, scheduler, and background-task workers into separate processes
When NOT to use
- A plain request-response agent (use
mastra-agents) - Cron-driven runs of agents or workflows (use
mastra-schedules) - Sending messages, state, or notifications into a thread, signal providers, and cross-process leases (use
mastra-signals) - Tool approval on a regular agent outside AgentController (use
mastra-agent-approval-hitl) - Supervisor agents and
isTaskComplete(usemastra-multi-agent) - Workspace filesystems and sandboxes in depth (use
mastra-workspace-sandbox) - Chat platform adapters such as Slack (use
mastra-channels) - Container topology and deploy targets for workers (use
mastra-deployment)
Required inputs
- What must survive: a client disconnect, a process crash, or only a slow tool
- Storage adapter (required for background tasks, goals, recovery, and controller threads)
- PubSub and cache backends if more than one process serves the agent (Redis Streams, Redis cache)
- For goals: the objective, the judge model, and the run budget (
maxRuns) - For AgentController: modes, which tools need approval, subagent types, the UI type (in-process or browser)
- For coding agents: the repository path and whether commands may run on the host
The framework: pick the capability
| Need | Capability | Entry point |
| Reconnectable, crash-recoverable runs | Durable agent | createDurableAgent({ agent }) from @mastra/core/agent/durable, or durable: true |
| Fire-and-forget runs | Evented agent | createEventedAgent({ agent }) |
| Production step memoization and retries | Inngest agent | createInngestAgent({ agent, inngest }) from @mastra/inngest |
| Slow tools without blocking | Background tasks | new Mastra({ backgroundTasks: { enabled: true } }) plus tool or agent opt-in |
| Keep going until done | Goals | Agent goal: { judge, maxRuns } and agent.setObjective() |
| Interactive sessions, modes, approvals | AgentController | new AgentController({...}) from @mastra/core/agent-controller |
| Coding agent defaults | Coding agent | createCodingAgent() from @mastra/core/coding-agent |
| Mastra Code in your app | Code SDK | mountAgentControllerOnMastra() from @mastra/code-sdk |
Capabilities compose. A coding agent can be the backing agent of an AgentController, have a goal, and dispatch background tasks.
Durable agent in one screen
import { Mastra } from '@mastra/core'
import { Agent } from '@mastra/core/agent'
import { createDurableAgent } from '@mastra/core/agent/durable'
const agent = new Agent({
id: 'researcher',
name: 'Researcher',
instructions: 'You research topics thoroughly.',
model: 'openai/gpt-6.1-sol',
})
export const durableResearcher = createDurableAgent({ agent })
export const mastra = new Mastra({ agents: { durableResearcher } })
const { output, runId, cleanup } = await durableResearcher.stream('Research quantum computing advances')
for await (const chunk of output.fullStream) {
// render
}
cleanup()
// From another request after a disconnect:
const { output: resumed } = await durableResearcher.observe(runId)Workflow
- Verify the API. If
node_modules/@mastra/exists, readnode_modules/@mastra/core/dist/docs/and the installed types forDurableAgent,AgentController, andSession. Otherwise fetchhttps://mastra.ai/docs/harness/overview.mdand the page for each capability you use. Durable agents and workers are beta. Trust these over memory. - Choose the smallest capability set from the table. Do not add AgentController when a durable agent alone solves the problem.
- Configure storage on
Mastra. Background tasks, goals, crash recovery, and controller threads need it. - Durable agents: wrap with
createDurableAgentor setdurable: trueon the agent (applied at registration). Keep therunId. Callcleanup()when done, except for suspended runs you will resume. - Multi-process: share a cache (
RedisServerCachefrom@mastra/redis), a PubSub backend, and run storage. Setrecovery: { durableAgents: 'auto' }for boot-time recovery. - Background tasks: enable on
Mastra, then opt in per tool (background: { enabled: true }) or per agent (backgroundTasks.tools). UseuntilIdle: trueonstream()when the caller should see follow-up turns. - Goals: add
goal: { judge, maxRuns }to an agent with memory. CallsetObjective(text, { threadId, resourceId }), then stream on that thread. - AgentController: define modes, call
controller.init()once, create one Session per user or task, subscribe beforesendMessage(), and handletool_approval_requiredandtool_suspendedevents. - Coding agents: build with
createCodingAgent({ id, name, model, instructions }). Swap the default local workspace for a sandbox when untrusted code runs. - Make tools idempotent. Recovery and retries can re-execute tool calls and whole subagent delegations.
Deep dive: AgentController sessions
import { Agent } from '@mastra/core/agent'
import { AgentController } from '@mastra/core/agent-controller'
import { LocalFilesystem, Workspace } from '@mastra/core/workspace'
import { LibSQLStore } from '@mastra/libsql'
const controller = new AgentController({
id: 'assistant-controller',
agent: new Agent({
id: 'assistant',
name: 'Assistant',
instructions: 'Help the user plan and complete tasks.',
model: 'openai/gpt-6.1-sol',
}),
storage: new LibSQLStore({ id: 'agent-controller-storage', url: 'file:./mastra.db' }),
workspace: new Workspace({
id: 'assistant-workspace',
filesystem: new LocalFilesystem({ basePath: './workspace' }),
}),
modes: [
{ id: 'plan', name: 'Plan', metadata: { default: true }, instructions: 'Reason before changing anything.', transitionsTo: 'build' },
{ id: 'build', name: 'Build', instructions: 'Implement the approved plan.' },
],
})
await controller.init()
const session = await controller.createSession({ id: 'user-123:web', resourceId: 'user-123' })
session.subscribe(event => {
if (event.type === 'message_update' && event.event.type === 'text-delta') process.stdout.write(event.event.delta)
if (event.type === 'tool_approval_required') session.respondToToolApproval({ toolCallId: event.toolCallId, decision: 'approve' })
})
await session.sendMessage({ content: 'Plan a small TypeScript CLI.' })
await session.steer({ content: 'Focus on argument parsing first.' }) // aborts and redirects
await session.followUp({ content: 'Then add tests.' }) // queued until idleLifetimes: the controller is shared and initialized once. A Session is live, process-local state (mode, model, grants, pending approvals). Threads and thread settings persist in storage. Register the controller on new Mastra({ agentControllers: { controller } }) to expose it over HTTP and channels.
Failure patterns
- Durable stream replay is empty.
cleanup()ran, orcleanupTimeoutMs(30 s default) passed. RaisecleanupTimeoutMsor use a persistent cache. observe()throwsDURABLE_AGENT_OBSERVE_AGENT_MISMATCH. The observing DurableAgent must have the same effectiveidas the one that started the run.- Reconnect works locally but not across replicas. The default cache and
EventEmitterPubSubare in-process. Share a Redis cache, PubSub, and storage. - Nothing recovered after a crash. With
recovery.durableAgents: 'off'(default),runningcheckpoints are not written. Set'auto'or ashouldPersistSnapshotthat includesrunning. - Duplicate side effects after recovery. Recovery replays from the last snapshot. Make tools idempotent and honor
abortSignal. cleanup()called on a suspended durable run. It destroys the registry entry. Let auto-cleanup handle it and callresume()later.- Background tasks never run in the background.
backgroundTasks.enabledis false, storage is missing, or the tool was not opted in._backgroundfrom the model cannot enable an ineligible tool. - Goal does nothing. No
judgeresolved, or the thread has no memory and storage. The judge is the activation switch. - Goal stops early with status
paused.maxRunswas hit. Raise it withupdateObjectiveOptions(). - Session state lost on restart.
session.state, grants, and pending approvals are live only. Persist what you need yourself. - Several users share one Session. Create one Session per user or task. Do not route messages through the controller.
- Coding agent runs commands on the host. The default workspace uses
LocalSandbox. Pass a remote sandbox workspace for untrusted work. createCodingAgentwithout memory has no task tools.TaskSignalProvideris added only whenmemoryis set.
Output format
A finished harness delivery contains:
- The agent definition and its wrapper (
createDurableAgent,createCodingAgent, or anAgentController) new Mastra({...})with storage, plusbackgroundTasks,recovery,pubsub, oragentControllersas used- Client or route code that keeps
runIdand callsobserve(), or subscribes to Session events - Idempotency notes or guards on side-effecting tools
- Env vars in
.env.example(REDIS_URL,DATABASE_URL,MASTRA_WORKERSfor split deployments) - A test that disconnects and reconnects, or kills and recovers a run
Reference files
references/api.md- DurableAgent factories, options, and methods; background task config; goal config and methods; AgentController and Session API; coding agent and Code SDK; workers.references/examples.md- Reconnectable durable agent with Redis, background research tool, goal-driven worker, coding agent with tasks and goal.references/checklist.md- Production checklist for long-running agents.
Live docs
- https://mastra.ai/docs/harness/overview
- https://mastra.ai/docs/harness/durable-agents
- https://mastra.ai/docs/harness/background-tasks
- https://mastra.ai/docs/harness/goals
- https://mastra.ai/docs/harness/agent-controller
- https://mastra.ai/reference/agents/durable-agent
- https://mastra.ai/reference/agent-controller/agent-controller-class
- https://mastra.ai/reference/agent-controller/session
- https://mastra.ai/reference/coding-agent/create-coding-agent
- https://mastra.ai/reference/coding-agent/build-base-prompt
- https://mastra.ai/reference/code-sdk/mount-agent-controller
- https://mastra.ai/reference/code-sdk/acp-server
- https://mastra.ai/reference/workers/overview
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

