⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.
TypeScript agenticagileai-agentsbug-reportingbug-trackerganttissue-trackerjirajira-alternativekanbanlinearlinear-alternativeopen-sourceproduct-managementproject-managementroadmapself-hostedsprint-planningteam-collaborationtrello-alternative
feat(runner): add a Mastra Code preset (#788)
Croff96319025061a
diff --git a/apps/web/src/features/teams/components/ai-agents/AgentRunnerHelpSheet.tsx b/apps/web/src/features/teams/components/ai-agents/AgentRunnerHelpSheet.tsxindex 4cc51d05..0255e37e 100644--- a/apps/web/src/features/teams/components/ai-agents/AgentRunnerHelpSheet.tsx+++ b/apps/web/src/features/teams/components/ai-agents/AgentRunnerHelpSheet.tsx@@ -145,6 +145,12 @@ const AGENTS = [agent: 'omp',files: [{ name: '.mcp.json', code: MCP_JSON }],},+ {+ id: 'mastracode',+ label: 'Mastra Code',+ agent: 'mastracode',+ files: [{ name: '.mcp.json', code: MCP_JSON }],+ },// A command of its own turns the preset off: the runner then knows nothing about// what it runs, keeps no session for it, and hands it the task on stdin.{diff --git a/docs/runner.md b/docs/runner.mdindex e2f28b15..acbbad09 100644--- a/docs/runner.md+++ b/docs/runner.md@@ -1,7 +1,7 @@# Coding agent setup[`@itsaplan/runner`](https://www.npmjs.com/package/@itsaplan/runner) runs an external agent-on your own machine. It has a preset for each of seven coding agent CLIs. A preset builds+on your own machine. It has a preset for each of eight coding agent CLIs. A preset buildsthe command itself: the flags for an unattended run, and the session resume.Each preset needs two files in the working directory:@@ -285,3 +285,40 @@ Oh My Pi reads `.mcp.json` from the working directory:- `--append-system-prompt` gives Oh My Pi the context of the run.- Headers in `.mcp.json` expand `${ITSAPLAN_API_KEY}` only if your Oh My Pi build does.If they stay literal, write the key in the file the way Copilot's config does.++## Mastra Code++Mastra Code reads `.mcp.json` from the working directory. It expands `${ITSAPLAN_API_KEY}`+in the headers, so the key stays out of the file:++```json+{+ "mcpServers": {+ "itsaplan": {+ "type": "http",+ "url": "http://localhost:3000/mcp",+ "headers": { "Authorization": "Bearer ${ITSAPLAN_API_KEY}" }+ }+ }+}+```++`itsaplan-runner.json`:++```json+{+ "url": "http://localhost:3000",+ "apiKey": "the key you copied on creation",+ "agent": "mastracode",+ "cwd": "/path/to/working-dir"+}+```++- The binary is `mastracode`. Sign in to a model provider once by running it interactively.+- The preset passes `--prompt -` and sends the task on stdin. Mastra Code has no+ system-prompt flag. The preset thus puts the context of the run before the task.+- The preset passes `--permission-mode auto`. Mastra Code then approves each tool and does+ not wait for a person.+- The preset passes `--output jsonl`. The stream gives the chat answer as it is written,+ includes the tool calls, and names the thread that `--thread` resumes.+- Add `--model provider/model` to `args` to choose the model of the run.diff --git a/packages/runner/README.md b/packages/runner/README.mdindex 8c8a98c2..cedf21eb 100644--- a/packages/runner/README.md+++ b/packages/runner/README.md@@ -8,7 +8,8 @@ This package runs such agents on your own machine — one, or several at once.- Polls your instance for the agent's queued runs. Runs each one with a coding agent CLI.Reports the result.- Has presets for Claude Code, Codex, opencode, Antigravity CLI, GitHub Copilot CLI,- Pi, and Oh My Pi (`omp`). Each preset sets the unattended flags and the session resume.+ Pi, Oh My Pi (`omp`), and Mastra Code. Each preset sets the unattended flags and the+ session resume.- Runs your own `command` instead, if you prefer. The command takes the task on stdin.- Answers the agent's chat. Sends the text and the tool calls while the CLI prints them.- Sends the messages and the tool calls of a queued run to the issue while the run works.@@ -23,9 +24,9 @@ of kind External. The key appears one time only, at creation.**2. Enable MCP** for the project, in Settings, MCP Server. MCP is off by default. Theagent reads the issue and writes its result through it.-**3. Give the coding agent the address of that server.** Claude Code, Oh My Pi, and Pi-(through `pi-mcp-adapter`) read `.mcp.json` from the folder they run in. For the other-CLIs, see+**3. Give the coding agent the address of that server.** Claude Code, Oh My Pi, Mastra+Code, and Pi (through `pi-mcp-adapter`) read `.mcp.json` from the folder they run in. For+the other CLIs, see[Coding agent setup](https://github.com/croffasia/itsaplan/blob/main/docs/runner.md).```json@@ -67,15 +68,16 @@ or mention it in a comment. The task then starts in your terminal.`agent` names a CLI that the runner knows. The runner then builds the command itself: theflags for an unattended run, and the session resume. Every preset keeps a chat session.-| Agent | Runs |-| ------------- | ------------------ |-| `claude` | Claude Code |-| `codex` | Codex CLI |-| `opencode` | opencode |-| `antigravity` | Antigravity CLI |-| `copilot` | GitHub Copilot CLI |-| `pi` | Pi |-| `omp` | Oh My Pi |+| Agent | Runs |+| ------------- | ---------------------------------------------------------------------------- |+| `claude` | [Claude Code](https://code.claude.com/docs/en/overview) |+| `codex` | [Codex CLI](https://github.com/openai/codex) |+| `opencode` | [opencode](https://opencode.ai) |+| `antigravity` | [Antigravity CLI](https://antigravity.google/docs/getting-started?tab=cli) |+| `copilot` | [GitHub Copilot CLI](https://github.com/github/copilot-cli) |+| `pi` | [Pi](https://pi.dev) |+| `omp` | [Oh My Pi](https://omp.sh) |+| `mastracode` | [Mastra Code](https://code.mastra.ai) |Each preset needs the CLI's own MCP config.[Coding agent setup](https://github.com/croffasia/itsaplan/blob/main/docs/runner.md) holds@@ -273,8 +275,8 @@ npx -y @itsaplan/runner --agent claudeThe server writes the task text. The text states what occurred, what to do, and to postthe result as a comment on the issue. Your own `command` receives the text on **stdin**. A-preset gives it to its CLI in the way that CLI accepts it: on stdin for `claude`, `codex`-and `pi`, as an argument for `antigravity`, `copilot`, `opencode` and `omp`.+preset gives it to its CLI in the way that CLI accepts it: on stdin for `claude`, `codex`,+`pi` and `mastracode`, as an argument for `antigravity`, `copilot`, `opencode` and `omp`.The agent reads all other data through the MCP server at `$ITSAPLAN_URL/mcp`. The agentsends `$ITSAPLAN_API_KEY` as a bearer token, and acts as its own user with its role.@@ -323,8 +325,8 @@ error.- `text` — all of stdout is the answer.- `claude-stream-json`, `codex-jsonl`, `opencode-json`, `antigravity-stream-json`,- `copilot-json`, `pi-json` — the event stream of that CLI. `pi` and `omp` both use- `pi-json`. The runner reads the text and the tool calls from it.+ `copilot-json`, `pi-json`, `mastracode-jsonl` — the event stream of that CLI. `pi` and+ `omp` both use `pi-json`. The runner reads the text and the tool calls from it.A preset sets `outputFormat` for you. Set it yourself only with your own `command`. If theoutput does not agree with the format, the runner uses the output as plain text.diff --git a/packages/runner/package.json b/packages/runner/package.jsonindex be55de12..38f79f7f 100644--- a/packages/runner/package.json+++ b/packages/runner/package.json@@ -20,7 +20,8 @@"antigravity","opencode","pi",- "omp"+ "omp",+ "mastracode"],"homepage": "https://github.com/croffasia/itsaplan/tree/main/packages/runner#readme","repository": {diff --git a/packages/runner/src/__tests__/agui.test.ts b/packages/runner/src/__tests__/agui.test.tsindex b16fd0ad..86e8053a 100644--- a/packages/runner/src/__tests__/agui.test.ts+++ b/packages/runner/src/__tests__/agui.test.ts@@ -545,6 +545,101 @@ describe('answer stream', () => {expect(result.content.endsWith('TAIL')).toBe(true);});+ it("reads Mastra Code's jsonl as text, tool calls and the thread it created", async () => {+ const sink = collect();+ const stream = new AnswerStream('mastracode-jsonl', 'chat:1:u:x', '7', sink.send);++ stream.write(+ [+ JSON.stringify({ type: 'thread_created', thread: { id: 'ee394567' } }),+ JSON.stringify({ type: 'message_start', message: { id: 'u1', role: 'signal' } }),+ JSON.stringify({+ type: 'message_update',+ id: 'u1',+ event: { type: 'text-delta', delta: 'task' },+ }),+ JSON.stringify({ type: 'message_start', message: { id: 'a1', role: 'assistant' } }),+ JSON.stringify({+ type: 'message_update',+ id: 'a1',+ event: { type: 'text-delta', delta: 'Reading' },+ }),+ JSON.stringify({+ type: 'usage_update',+ usage: { promptTokens: 9000, completionTokens: 40 },+ }),+ JSON.stringify({+ type: 'tool_start',+ toolCallId: 'call_1',+ toolName: 'view',+ args: { path: 'a.txt' },+ }),+ JSON.stringify({ type: 'tool_end', toolCallId: 'call_1', result: 'hello', isError: false }),+ JSON.stringify({ type: 'message_start', message: { id: 'a2', role: 'assistant' } }),+ JSON.stringify({+ type: 'message_update',+ id: 'a2',+ event: { type: 'text-delta', delta: 'hello' },+ }),+ JSON.stringify({+ type: 'usage_update',+ usage: { promptTokens: 9100, completionTokens: 5 },+ }),+ JSON.stringify({+ type: 'result',+ status: 'completed',+ text: 'hello',+ threadId: 'ee394567',+ }),+ // The terminal reset Mastra Code writes to stdout as it exits, with no newline.+ '\x1b[?2004l\x1b[<u\x1b[>4;0m\x1b[?25h',+ ].join('\n'),+ );+ await stream.finish('');++ expect(types(sink.events)).toEqual([+ 'RUN_STARTED',+ 'TEXT_MESSAGE_START',+ 'TEXT_MESSAGE_CONTENT',+ 'TOOL_CALL_START',+ 'TOOL_CALL_ARGS',+ 'TOOL_CALL_END',+ 'TOOL_CALL_RESULT',+ 'TEXT_MESSAGE_CONTENT',+ 'TEXT_MESSAGE_END',+ 'RUN_FINISHED',+ ]);+ expect(text(sink.events)).toBe('Readinghello');+ expect(stream.answer()).toBe('hello');+ expect(stream.startedSession()).toBe('ee394567');+ expect(stream.contextUsage()).toEqual({ inputTokens: 9100, outputTokens: 5 });+ const result = sink.events.find((e) => e.type === 'TOOL_CALL_RESULT');+ expect((result as { content: string }).content).toBe('hello');+ });++ it('takes the Mastra Code result text, or its error, when no delta arrived', async () => {+ const answered = collect();+ const answeredStream = new AnswerStream('mastracode-jsonl', 'chat:1:u:x', '7', answered.send);+ answeredStream.write(+ `${JSON.stringify({ type: 'result', status: 'completed', text: 'Done.' })}\n`,+ );+ await answeredStream.finish('');+ expect(text(answered.events)).toBe('Done.');++ const failed = collect();+ const failedStream = new AnswerStream('mastracode-jsonl', 'chat:1:u:x', '7', failed.send);+ failedStream.write(+ `${JSON.stringify({+ type: 'result',+ status: 'error',+ text: '',+ error: { name: 'ProviderAuthRequiredError', message: 'Anthropic sign-in expired.' },+ })}\n`,+ );+ await failedStream.fail('Command exited with 1', 'raw output');+ expect(text(failed.events)).toBe('Anthropic sign-in expired.');+ });+it('reports what a denied Copilot tool call said', async () => {const sink = collect();const stream = new AnswerStream('copilot-json', 'chat:1:u:x', '7', sink.send);@@ -569,6 +664,7 @@ describe('answer stream', () => {'antigravity-stream-json','copilot-json','pi-json',+ 'mastracode-jsonl',] as const) {const sink = collect();const stream = new AnswerStream(format, 'chat:1:u:x', '7', sink.send);diff --git a/packages/runner/src/__tests__/presets.test.ts b/packages/runner/src/__tests__/presets.test.tsindex 21be73a1..abbddeba 100644--- a/packages/runner/src/__tests__/presets.test.ts+++ b/packages/runner/src/__tests__/presets.test.ts@@ -63,6 +63,25 @@ describe('preset arguments', () => {expect(resumed).toEqual(['-p', '--mode', 'json', '--session-id', 'sess-9']);});+ it('runs Mastra Code headless with the task on stdin and resumes a thread by id', () => {+ const fresh = presetArgv(PRESETS.mastracode, null, 'context', ['--model', 'x/y'], 'do it');+ expect(fresh).not.toContain('--thread');+ expect(fresh).not.toContain('do it');+ expect(fresh.slice(-2)).toEqual(['--prompt', '-']);++ const resumed = presetArgv(PRESETS.mastracode, 'ee394567', '', [], 'do it');+ expect(resumed).toEqual([+ '--output',+ 'jsonl',+ '--permission-mode',+ 'auto',+ '--thread',+ 'ee394567',+ '--prompt',+ '-',+ ]);+ });+it('prints through omp json mode unattended and resumes with --resume', () => {const fresh = presetArgv(PRESETS.omp, null, '', [], 'do it');expect(fresh).toContain('--auto-approve');diff --git a/packages/runner/src/agui.ts b/packages/runner/src/agui.tsindex af11e8e1..0ceb1ae8 100644--- a/packages/runner/src/agui.ts+++ b/packages/runner/src/agui.ts@@ -34,6 +34,9 @@ const DELTA_LIMIT = 12_000;// indents and highlights. An outsized one is cut from the front, where a long output says// least.const TOOL_TEXT_LIMIT = 32_000;+// Node's stripVTControlCharacters leaves the `u` of ESC [<u behind.+// eslint-disable-next-line no-control-regex+const TERMINAL_CODES = /\x1b\[[0-?]*[ -/]*[@-~]/g;// Produces the events of one answer and hands them to `send` in batches. The caller// writes the command's output as it arrives and calls flush on a timer, so a long@@ -54,6 +57,7 @@ export class AnswerStream {private openTextPart = '';private readonly openToolCalls = new Set<string>();private readonly closedToolCalls = new Set<string>();+ private mastraMessageId: string | undefined;// Whether the command reported partial text of its own. Its final message repeats// that text, and emitting both would say everything twice.private sawPartialText = false;@@ -187,7 +191,9 @@ export class AnswerStream {} catch {// Output that is not the format it was configured with still has something to say.// A CLI writing its own diagnostics to stdout alongside the stream lands here too.- this.appendText(`${trimmed}\n`);+ // Mastra Code writes a terminal reset to stdout as it exits.+ const plain = trimmed.replace(TERMINAL_CODES, '').trim();+ if (plain) this.appendText(`${plain}\n`);return;}// A line that parses to null, a number or a string carries none of the fields below,@@ -213,6 +219,45 @@ export class AnswerStream {case 'pi-json':this.readPiLine(parsed as PiJsonLine);break;+ case 'mastracode-jsonl':+ this.readMastraLine(parsed as MastraLine);+ break;+ }+ }++ // A new thread is named on thread_created, before the answer. The task arrives as a+ // message of its own under the role `signal`, so only the deltas of an assistant message+ // count. The closing result repeats the text, and carries the error of a failed run:+ // Mastra Code writes nothing to stderr in this mode.+ private readMastraLine(message: MastraLine): void {+ switch (message.type) {+ case 'thread_created':+ if (message.thread?.id) this.sessionId ??= message.thread.id;+ return;+ case 'message_start':+ if (message.message?.role === 'assistant') this.mastraMessageId = message.message.id;+ return;+ case 'message_update':+ if (message.id === this.mastraMessageId && message.event?.type === 'text-delta') {+ this.appendText(message.event.delta ?? '');+ }+ return;+ case 'tool_start':+ if (message.toolCallId) {+ this.pushToolCall(+ message.toolCallId,+ message.toolName ?? 'tool',+ JSON.stringify(message.args ?? {}),+ );+ }+ return;+ case 'tool_end':+ if (message.toolCallId)+ this.pushToolResult(message.toolCallId, toolResultText(message.result));+ return;+ case 'result':+ if (!this.sawAnyText) this.appendText(message.text || message.error?.message || '');+ return;}}@@ -244,7 +289,7 @@ export class AnswerStream {case 'tool_execution_end': {if (!message.toolCallId || this.closedToolCalls.has(message.toolCallId)) return;this.closedToolCalls.add(message.toolCallId);- this.pushToolResult(message.toolCallId, piResultText(message.result));+ this.pushToolResult(message.toolCallId, toolResultText(message.result));return;}case 'message_end':@@ -549,9 +594,22 @@ export class UsageReader {case 'pi-json':this.readPi(parsed as PiJsonLine);return;+ case 'mastracode-jsonl':+ this.readMastra(parsed as MastraLine);+ return;}}+ // usage_update reports one model call. promptTokens is the number Mastra Code itself+ // shows as the size of the conversation.+ private readMastra(message: MastraLine): void {+ if (message.type !== 'usage_update' || !message.usage) return;+ this.last = {+ inputTokens: message.usage.promptTokens ?? 0,+ outputTokens: message.usage.completionTokens ?? 0,+ };+ }+// Claude reports one model call in two events: message_start opens it with the tokens// read, message_delta closes it with the tokens written. They belong to the same call,// so the second completes the first rather than replacing it. The `result` line is not@@ -636,7 +694,7 @@ function textOfResult(content: unknown): string {return '';}-function piResultText(result: unknown): string {+function toolResultText(result: unknown): string {if (result && typeof result === 'object' && !Array.isArray(result) && 'content' in result) {return textOfResult(result.content);}@@ -775,6 +833,22 @@ interface PiJsonLine {message?: { role?: string; content?: unknown };}+// The parts of Mastra Code's --output jsonl this adapter reads.+interface MastraLine {+ type?: string;+ id?: string;+ thread?: { id?: string };+ message?: { id?: string; role?: string };+ event?: { type?: string; delta?: string };+ toolCallId?: string;+ toolName?: string;+ args?: unknown;+ result?: unknown;+ usage?: { promptTokens?: number; completionTokens?: number };+ text?: string;+ error?: { message?: string };+}+interface StreamEvent {type?: string;delta?: { type?: string; text?: string };diff --git a/packages/runner/src/config.ts b/packages/runner/src/config.tsindex 2e516493..267c9f44 100644--- a/packages/runner/src/config.ts+++ b/packages/runner/src/config.ts@@ -50,6 +50,7 @@ const OUTPUT_FORMATS = ['antigravity-stream-json','copilot-json','pi-json',+ 'mastracode-jsonl',] as const;export type OutputFormat = (typeof OUTPUT_FORMATS)[number];diff --git a/packages/runner/src/presets.ts b/packages/runner/src/presets.tsindex c2fe64e7..9b5e64bb 100644--- a/packages/runner/src/presets.ts+++ b/packages/runner/src/presets.ts@@ -9,7 +9,8 @@ import type { OutputFormat } from './config';// Anything else about the invocation — MCP servers, model, working directory — is the// operator's, passed through `args` and the `--` tail.-export type PresetName = 'claude' | 'codex' | 'opencode' | 'antigravity' | 'copilot' | 'pi' | 'omp';+export type PresetName =+ 'claude' | 'codex' | 'opencode' | 'antigravity' | 'copilot' | 'pi' | 'omp' | 'mastracode';export interface Preset {bin: string;@@ -17,8 +18,7 @@ export interface Preset {// A CLI that takes the prompt as an argument gets it after everything else, which is why// `tail` exists.promptVia: 'stdin' | 'arg';- // Only Claude Code has a flag for the run's context; the rest get it in front of the- // task.+ // A CLI without a flag for the run's context gets it in front of the task.systemPromptFlag?: string;// The arguments before the operator's own, given null for a fresh session.head: (sessionId: string | null) => string[];@@ -150,6 +150,24 @@ export const PRESETS: Record<PresetName, Preset> = {],tail: ['--'],},++ // --prompt is what runs Mastra Code headless, and `-` makes it read the task from stdin.+ // --permission-mode auto approves each tool and resolves a suspended one, so nothing+ // waits for a person. The stream names a new thread on its thread_created line, and+ // --thread resumes it.+ mastracode: {+ bin: 'mastracode',+ outputFormat: 'mastracode-jsonl',+ promptVia: 'stdin',+ head: (sessionId) => [+ '--output',+ 'jsonl',+ '--permission-mode',+ 'auto',+ ...(sessionId ? ['--thread', sessionId] : []),+ ],+ tail: ['--prompt', '-'],+ },};export const PRESET_NAMES = Object.keys(PRESETS) as PresetName[];