@agentproto/adapter-mastra-agent 0.4.2 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-5C2H4JSD.mjs +2094 -0
- package/dist/chunk-5C2H4JSD.mjs.map +1 -0
- package/dist/cli.mjs +1 -1
- package/dist/index.d.ts +504 -114
- package/dist/index.mjs +15 -5
- package/dist/index.mjs.map +1 -1
- package/package.json +8 -5
- package/dist/chunk-ZVLJDGI4.mjs +0 -602
- package/dist/chunk-ZVLJDGI4.mjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/daemon-client.ts","../src/workspace-tools.ts","../src/daemon-tools.ts","../src/memory.ts","../src/model-resolver.ts","../src/signal-provider.ts","../src/state-signals.ts","../src/tool-categories.ts","../src/modes.ts","../src/default-agent.ts","../src/tool-call-map.ts","../src/acp-host.ts","../src/run.ts"],"names":["fs","resolvePath","join","tail","createTool","z","homedir","execFileAsync","promisify","execFile","resolve","config","errorMessage"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCO,IAAM,mBAAA,GAAN,cAAkC,KAAA,CAAM;AAAA,EAC7C,WAAA,CAAY,UAAU,oGAAA,EAAiG;AACrH,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,qBAAA;AAAA,EACd;AACF;AAGO,IAAM,eAAA,GAAN,cAA8B,KAAA,CAAM;AAAA,EACzC,WAAA,CACE,OAAA,EACgB,MAAA,EACA,IAAA,EAChB;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AAHG,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AACA,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AAGhB,IAAA,IAAA,CAAK,IAAA,GAAO,iBAAA;AAAA,EACd;AAAA,EALkB,MAAA;AAAA,EACA,IAAA;AAKpB;AAEA,SAAS,kBAAkB,GAAA,EAAsB;A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;AAC5B,EAAA,OAAO,KAAA,CAAM,IAAA,CAAK,KAAA,EAAO,CAAC,MAAM,CAAA,CAAE,QAAA,CAAS,EAAE,CAAA,CAAE,SAAS,CAAA,EAAG,GAAG,CAAC,CAAA,CAAE,KAAK,EAAE,CAAA;AAC1E;ACnvBO,SAAS,gBACd,eAAA,EACqB;AAErB,EAAA,MAAM,QAAA,GAAW,QAAA,CAAS,KAAA,CAAM,OAAA,CAAQ,MAAM,CAAA;AAC9C,EAAA,MAAM,aAAa,QAAA,CAAS,KAAA;AAAA,IAC1B,OAAA,CAAQ;AAAA,GACV;AACA,EAAA,MAAM,MAAA,GAAS,YAAA,CAAa,QAAA,EAAU,UAAU,CAAA;AAChD,EAAA,OAAO,IAAI,mBAAA;AAAA,IACT,CAAC,IAAA,KAAS,IAAI,cAAA,CAAe,MAAM,eAAe,CAAA;AAAA,IAClD;AAAA,GACF;AACF","file":"chunk-5C2H4JSD.mjs","sourcesContent":["/**\n * Zero-dependency HTTP client for the agentproto daemon.\n *\n * The adapter is spawned as an ACP child with `AGENTPROTO_SESSION_ID` /\n * `AGENTPROTO_PARENT_SESSION_ID` in its env, but no daemon URL/token — unlike\n * the CLI (`packages/cli/src/commands/_daemon-helpers.ts`, read as reference),\n * this package cannot import `@agentproto/runtime` or `@agentproto/cli`\n * (would pull the whole daemon runtime into an agent process). So this is a\n * deliberately smaller reimplementation of that discovery order:\n *\n * 1. `AGENTPROTO_DAEMON_URL` env (+ optional `AGENTPROTO_DAEMON_TOKEN`)\n * 2. `<cwd>/.agentproto/runtime.json`\n * 3. `~/.agentproto/runtime.json`\n * 4. central registry `~/.agentproto/daemons/*.json`, newest-mtime-first\n *\n * Unlike the CLI helper, this skips the `workspaces.json` walk (needs\n * `@agentproto/runtime`'s config loader) and the declared-port preference\n * in the central registry (needs `loadConfig()`). Good enough for an agent\n * process discovering the daemon that spawned it or one on the same host.\n *\n * A runtime.json / registry entry whose `pid` is dead (`process.kill(pid, 0)`\n * throwing anything but `EPERM`) is never trusted — same footgun the CLI\n * helper guards against (a crashed daemon's stale token 401ing a fresh one\n * on the same port).\n */\n\nimport { promises as fs } from \"node:fs\"\nimport { homedir } from \"node:os\"\nimport { join, resolve as resolvePath } from \"node:path\"\n\nexport interface DaemonEndpoint {\n url: string\n token?: string\n /** Path of the runtime.json / registry file the endpoint came from.\n * Undefined when the endpoint came from env vars. */\n sourcePath?: string\n}\n\n/** Thrown when no daemon endpoint can be discovered. */\nexport class DaemonNotFoundError extends Error {\n constructor(message = \"no agentproto daemon found — set AGENTPROTO_DAEMON_URL or run inside a daemon-spawned session\") {\n super(message)\n this.name = \"DaemonNotFoundError\"\n }\n}\n\n/** Thrown on a non-2xx daemon HTTP response. */\nexport class DaemonHttpError extends Error {\n constructor(\n message: string,\n public readonly status: number,\n public readonly body: string,\n ) {\n super(message)\n this.name = \"DaemonHttpError\"\n }\n}\n\nfunction defaultIsPidAlive(pid: number): boolean {\n try {\n // Signal 0 doesn't deliver — it just probes for the process' existence.\n process.kill(pid, 0)\n return true\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code\n return code === \"EPERM\" // exists, just not ours to signal\n }\n}\n\nasync function readJsonFile(path: string): Promise<Record<string, unknown> | undefined> {\n try {\n const raw = await fs.readFile(path, \"utf8\")\n return JSON.parse(raw) as Record<string, unknown>\n } catch {\n return undefined\n }\n}\n\n/** Parse a runtime.json-shaped file into a live endpoint, or undefined when\n * missing, malformed, or the recorded PID is dead. */\nasync function endpointFromRuntimeJson(\n path: string,\n isPidAlive: (pid: number) => boolean,\n): Promise<DaemonEndpoint | undefined> {\n const parsed = await readJsonFile(path)\n if (!parsed || typeof parsed.port !== \"number\") return undefined\n if (typeof parsed.pid === \"number\" && !isPidAlive(parsed.pid)) return undefined\n return {\n url: `http://${typeof parsed.bind === \"string\" ? parsed.bind : \"127.0.0.1\"}:${parsed.port}`,\n sourcePath: path,\n ...(typeof parsed.token === \"string\" ? { token: parsed.token } : {}),\n }\n}\n\nexport interface DiscoverDaemonOptions {\n cwd?: string\n env?: NodeJS.ProcessEnv\n /** Override `homedir()` for BOTH `~/.agentproto/runtime.json` and the\n * central registry dir (unless `registryDir` also overrides the latter\n * separately) — test hook, so discovery never has to touch a real\n * developer machine's `~/.agentproto`. */\n homeDir?: string\n /** Override the central registry directory — test hook. Wins over `homeDir`. */\n registryDir?: string\n /** Override the liveness check for a runtime.json / registry entry's\n * `pid` — test hook. Defaults to a real `process.kill(pid, 0)` probe. */\n isPidAlive?: (pid: number) => boolean\n}\n\n/**\n * Resolve the first live daemon endpoint, in the order documented above.\n * Returns undefined when nothing live is found.\n */\nexport async function discoverDaemonEndpoint(\n opts: DiscoverDaemonOptions = {},\n): Promise<DaemonEndpoint | undefined> {\n const env = opts.env ?? process.env\n const cwd = opts.cwd ?? process.cwd()\n const homeDir = opts.homeDir ?? homedir()\n const isPidAlive = opts.isPidAlive ?? defaultIsPidAlive\n\n if (env.AGENTPROTO_DAEMON_URL) {\n const url = env.AGENTPROTO_DAEMON_URL.replace(/\\/+$/, \"\")\n return { url, ...(env.AGENTPROTO_DAEMON_TOKEN ? { token: env.AGENTPROTO_DAEMON_TOKEN } : {}) }\n }\n\n const cwdRuntime = await endpointFromRuntimeJson(resolvePath(cwd, \".agentproto\", \"runtime.json\"), isPidAlive)\n if (cwdRuntime) return cwdRuntime\n\n const homeRuntime = await endpointFromRuntimeJson(resolvePath(homeDir, \".agentproto\", \"runtime.json\"), isPidAlive)\n if (homeRuntime) return homeRuntime\n\n const registryDir = opts.registryDir ?? resolvePath(homeDir, \".agentproto\", \"daemons\")\n let names: string[]\n try {\n names = await fs.readdir(registryDir)\n } catch {\n return undefined\n }\n const entries: Array<{ path: string; mtimeMs: number }> = []\n for (const name of names) {\n if (!name.endsWith(\".json\")) continue\n const path = join(registryDir, name)\n try {\n const st = await fs.stat(path)\n entries.push({ path, mtimeMs: st.mtimeMs })\n } catch {\n // skip unreadable entry\n }\n }\n entries.sort((a, b) => b.mtimeMs - a.mtimeMs) // newest-mtime-first\n for (const entry of entries) {\n const ep = await endpointFromRuntimeJson(entry.path, isPidAlive)\n if (ep) return ep\n }\n return undefined\n}\n\nexport interface StartAgentInput {\n adapter: string\n cwd?: string\n model?: string\n prompt?: string\n label?: string\n}\n\nexport interface PromptAgentOptions {\n /** Cancel the in-flight turn and deliver this prompt instead. Default false. */\n interrupt?: boolean\n /** `false` returns as soon as the prompt is queued/validated, without\n * waiting for the turn to drain. Default true (blocking). */\n wait?: boolean\n}\n\nexport interface ListSessionsOptions {\n includeArchived?: boolean\n kind?: string\n}\n\nexport interface ReadOutputOptions {\n format?: \"markdown\" | \"json\"\n}\n\nexport interface PollEventsOptions {\n /** Cursor from a prior call's `nextSeq`. Omit to start from the beginning. */\n since?: number\n /** Client-side filter on each record's `kind` field. Omit → all kinds. */\n types?: string[]\n limit?: number\n}\n\nexport interface PollEventsResult {\n sessionId: string\n events: Array<Record<string, unknown>>\n nextSeq: number\n complete: boolean\n}\n\nexport interface DaemonClientOptions {\n cwd?: string\n env?: NodeJS.ProcessEnv\n /** Injectable fetch — test hook. Defaults to the global `fetch`. */\n fetchImpl?: typeof fetch\n /** Pre-resolved endpoint — skips discovery, mainly a test hook. */\n endpoint?: DaemonEndpoint\n /** Test hooks forwarded to {@link discoverDaemonEndpoint}. */\n homeDir?: string\n registryDir?: string\n isPidAlive?: (pid: number) => boolean\n}\n\n/**\n * Thin HTTP client over the daemon's REST surface (`packages/runtime/src/http-server.ts`,\n * read-only reference — this package never imports it). Discovers the daemon\n * endpoint lazily on first call and caches it; a connection failure triggers\n * one re-discovery attempt (covers a daemon restart on the same well-known\n * runtime.json / registry path but a new port/token).\n */\nexport class DaemonClient {\n private readonly cwd: string\n private readonly env: NodeJS.ProcessEnv\n private readonly fetchImpl: typeof fetch\n private readonly homeDir: string | undefined\n private readonly registryDir: string | undefined\n private readonly isPidAlive: ((pid: number) => boolean) | undefined\n private cachedEndpoint: DaemonEndpoint | undefined\n\n constructor(opts: DaemonClientOptions = {}) {\n this.cwd = opts.cwd ?? process.cwd()\n this.env = opts.env ?? process.env\n if (!opts.fetchImpl && typeof fetch !== \"function\") {\n throw new Error(\"DaemonClient requires a global `fetch` (Node >=18) or an injected `fetchImpl`.\")\n }\n this.fetchImpl = opts.fetchImpl ?? fetch\n this.homeDir = opts.homeDir\n this.registryDir = opts.registryDir\n this.isPidAlive = opts.isPidAlive\n this.cachedEndpoint = opts.endpoint\n }\n\n private async resolveEndpoint(forceRediscover = false): Promise<DaemonEndpoint> {\n if (this.cachedEndpoint && !forceRediscover) return this.cachedEndpoint\n const found = await discoverDaemonEndpoint({\n cwd: this.cwd,\n env: this.env,\n ...(this.homeDir ? { homeDir: this.homeDir } : {}),\n ...(this.registryDir ? { registryDir: this.registryDir } : {}),\n ...(this.isPidAlive ? { isPidAlive: this.isPidAlive } : {}),\n })\n if (!found) throw new DaemonNotFoundError()\n this.cachedEndpoint = found\n return found\n }\n\n private async request<T>(\n method: string,\n path: string,\n opts: { body?: unknown; query?: Record<string, string | undefined> } = {},\n ): Promise<T> {\n const endpoint = await this.resolveEndpoint()\n const doFetch = async (ep: DaemonEndpoint) => {\n const url = new URL(path, ep.url)\n for (const [k, v] of Object.entries(opts.query ?? {})) {\n if (v !== undefined) url.searchParams.set(k, v)\n }\n const headers: Record<string, string> = {}\n if (ep.token) headers.authorization = `Bearer ${ep.token}`\n if (opts.body !== undefined) headers[\"content-type\"] = \"application/json\"\n return this.fetchImpl(url.toString(), {\n method,\n headers,\n ...(opts.body !== undefined ? { body: JSON.stringify(opts.body) } : {}),\n })\n }\n\n let res: Response\n try {\n res = await doFetch(endpoint)\n } catch (err) {\n // Likely connection refused (daemon restarted / moved port) — re-discover\n // once and retry before giving up.\n const rediscovered = await this.resolveEndpoint(true)\n try {\n res = await doFetch(rediscovered)\n } catch (retryErr) {\n throw retryErr instanceof Error ? retryErr : new Error(String(retryErr))\n }\n void err\n }\n const text = await res.text()\n if (!res.ok) {\n throw new DaemonHttpError(\n `daemon HTTP ${res.status} ${method} ${path}: ${text.slice(0, 200)}`,\n res.status,\n text,\n )\n }\n return text.length > 0 ? (JSON.parse(text) as T) : (undefined as T)\n }\n\n /**\n * Spawn a child session — `POST /sessions/agent`. `parentSessionId` is\n * derived from `AGENTPROTO_SESSION_ID` (set by the daemon on every\n * ACP-spawned adapter) when present, so session lineage is recorded\n * without the caller having to thread it through.\n */\n async startAgent(input: StartAgentInput): Promise<Record<string, unknown>> {\n const parentSessionId = this.env.AGENTPROTO_SESSION_ID\n return this.request(\"POST\", \"/sessions/agent\", {\n body: {\n ...input,\n ...(parentSessionId ? { parentSessionId } : {}),\n },\n })\n }\n\n /** Send a follow-up turn to a live session — `POST /sessions/:id/prompt`. */\n async promptAgent(\n sessionId: string,\n text: string,\n opts: PromptAgentOptions = {},\n ): Promise<Record<string, unknown>> {\n return this.request(\"POST\", `/sessions/${encodeURIComponent(sessionId)}/prompt`, {\n body: { prompt: text, ...(opts.interrupt ? { interrupt: true } : {}) },\n query: opts.wait === false ? { wait: \"false\" } : {},\n })\n }\n\n /** List sessions — `GET /sessions`. */\n async listSessions(opts: ListSessionsOptions = {}): Promise<{ sessions: Array<Record<string, unknown>> }> {\n return this.request(\"GET\", \"/sessions\", {\n query: {\n includeArchived: opts.includeArchived ? \"true\" : undefined,\n kind: opts.kind,\n },\n })\n }\n\n /**\n * Read a session's transcript — `GET /sessions/:id/export`. Chosen over\n * `/sessions/:id/conversation` (needs a provider-native store registered\n * for the adapter; not every adapter has one) and `/sessions/:id/preview`\n * (a raw ring-buffer snapshot, not a rendered transcript): `/export`\n * works for ANY agent-cli session, falling back to the daemon's own\n * `events.jsonl` capture when no provider-native reader is registered\n * (`source: \"auto\"`, see `transcript-export.ts`) — the one built for\n * programmatic reads of \"what did this session say\".\n */\n async readOutput(sessionId: string, opts: ReadOutputOptions = {}): Promise<Record<string, unknown>> {\n return this.request(\"GET\", `/sessions/${encodeURIComponent(sessionId)}/export`, {\n query: { format: opts.format ?? \"json\" },\n })\n }\n\n /**\n * Cursor-based poll of a session's structured event log —\n * `GET /sessions/:id/events`. NOT the same event source as the MCP\n * `session_events_poll` tool: that tool reads the daemon's in-memory,\n * cross-session `EventRing` (turn-end/awaiting-input/exited/... lifecycle\n * events, `packages/runtime/src/orchestration-tools.ts:528`), which has no\n * plain-HTTP equivalent — it's only reachable over the MCP JSON-RPC\n * transport, which this zero-dependency client doesn't speak. This route\n * is the per-SESSION structured `events.jsonl` transcript instead\n * (`packages/runtime/src/transcript-writer.ts`): cursor-based via\n * `since`/`nextSeq` same as the MCP tool, and its records DO carry many of\n * the same `kind`s (`turn-end`, `error`, `permission-resolved`, ...) — but\n * it has no `exited` / `session:spawned` records (those are registry\n * state changes, not transcript writes) and no cross-session fan-in\n * (`sessionIds` filter). `types` is therefore filtered client-side here\n * against each record's `kind`, not sent as a query param.\n *\n * WP-6 (`AgentprotoSignalProvider`, polling every 5s): this is a\n * non-blocking snapshot read, so it's a direct fit for a poll loop. If\n * WP-6 needs the actual cross-session lifecycle events (`exited`,\n * `session:spawned`, multi-session fan-in), it either needs its own\n * light MCP JSON-RPC client to call `session_events_poll` directly, or\n * per-session `GET /sessions/:id/wait?since=&event=` (a blocking\n * long-poll over the SAME EventRing `session_events_poll` reads, but\n * scoped to one session and one event name at a time — no `types` array).\n */\n async pollEvents(sessionId: string, opts: PollEventsOptions = {}): Promise<PollEventsResult> {\n const result = await this.request<PollEventsResult>(\n \"GET\",\n `/sessions/${encodeURIComponent(sessionId)}/events`,\n {\n query: {\n since: opts.since !== undefined ? String(opts.since) : undefined,\n limit: opts.limit !== undefined ? String(opts.limit) : undefined,\n },\n },\n )\n if (!opts.types || opts.types.length === 0) return result\n const wanted = new Set(opts.types)\n return {\n ...result,\n events: result.events.filter(e => typeof e.kind === \"string\" && wanted.has(e.kind as string)),\n }\n }\n}\n","/**\n * Workspace toolset — gives the Mastra agent the ability to inspect, edit, and\n * run commands inside its session working directory, like a coding agent.\n *\n * SAFETY: every file path is resolved against the session `cwd` and rejected if\n * it escapes (no `../` traversal, no absolute paths outside cwd). Command\n * execution runs with `cwd` and a timeout, and is gated by `allowExec` (the CLI\n * sets it from `AGENTPROTO_MASTRA_NO_EXEC`). The agent only ever touches the\n * directory the daemon spawned it in.\n *\n * ## Tool id vocabulary\n *\n * Two tool-id vocabularies exist in this codebase for the same operations:\n * this adapter's own coding-agent style (`list_dir`, `read_file`, `write_file`,\n * `run_command`, ...) and the daemon's MCP-filesystem-compatible style\n * (`directory_list`, `file_read`, `file_write`, `file_info`, `command_execute`,\n * matching `packages/runtime/src/fs-tools.ts` / `command-tools.ts`). Apps'\n * AGENT.md `tools:` lists have shipped with either vocabulary (see\n * `packages/apps/src/media-viewer/agents/cataloger.ts` mixing `list_dir` +\n * `file_info`), so both id sets resolve here — the daemon-style ids are\n * aliases over the same implementations, plus `file_info` and `command_execute`\n * which have no adapter-style equivalent.\n *\n * ## Fail-fast for unresolved tool refs\n *\n * `resolveTool` in `default-agent.ts` no longer silently drops an AGENT.md\n * tool ref that doesn't match anything here — see `makeUnwiredToolStub`. A\n * declared-but-unwired tool stays visible to the model and fails fast and\n * clearly instead of the model either never seeing it (silent drop) or\n * hallucinating a call the SDK can't resolve, which used to surface as an\n * opaque `NoSuchToolError` this adapter's ACP layer then dropped on the\n * floor (see `tool-call-map.ts`'s `tool-error` handling), leaving the turn\n * looking hung with zero recorded tool calls.\n *\n * ## Execution guard\n *\n * Every tool's `execute` is wrapped with a hard timeout (`execTimeoutMs`,\n * default 120s) so a stalled fs op or an unresponsive allowlist check can't\n * block a turn indefinitely — past the deadline the call rejects with a\n * clear timeout error (surfaced to the model as a normal tool failure) in\n * place of an unbounded hang.\n */\n\nimport { exec, execFile } from \"node:child_process\"\nimport { randomUUID } from \"node:crypto\"\nimport { promises as fs } from \"node:fs\"\nimport { tmpdir } from \"node:os\"\nimport { basename, isAbsolute, join, relative, resolve, sep } from \"node:path\"\nimport { promisify } from \"node:util\"\nimport { createTool } from \"@mastra/core/tools\"\nimport type { MastraToolLike } from \"@agentproto/mastra\"\nimport {\n interpreterExecWarning,\n isCommandAllowed,\n isInterpreterBasename,\n loadAllowlistEntries,\n} from \"@agentproto/runtime/command-allowlist\"\nimport { z } from \"zod\"\n\nconst execAsync = promisify(exec)\nconst execFileAsync = promisify(execFile)\n\n/** A Mastra tool (structural — avoids coupling to a @mastra/core type name). */\nexport interface WorkspaceTool {\n id: string\n}\n\n/** `command`'s argv0 must be one of these for `run_tests` — no arbitrary exec. */\nconst ALLOWED_TEST_ARGV0 = new Set([\"npm\", \"pnpm\", \"yarn\", \"node\", \"npx\"])\n\n/** Keep tool output bounded — return only the tail. */\nfunction tail(s: string, maxChars = 4000): string {\n return s.length > maxChars ? s.slice(-maxChars) : s\n}\n\n/** Pull the file paths a unified diff touches out of its `---`/`+++` headers. */\nfunction extractPatchPaths(patch: string): string[] {\n const paths = new Set<string>()\n for (const line of patch.split(\"\\n\")) {\n const m = /^(?:\\+\\+\\+|---) (?:a\\/|b\\/)?(.+?)(?:\\t.*)?$/.exec(line)\n if (!m) continue\n const p = m[1]!.trim()\n if (p === \"/dev/null\") continue\n paths.add(p)\n }\n return [...paths]\n}\n\n/**\n * Wrap a tool's `execute` so it can never block a turn past `timeoutMs` — a\n * stalled fs call, a hung subprocess, or an unresponsive allowlist read all\n * reject with a clear, tool-attributed timeout error instead of leaving the\n * model's tool call pending forever.\n */\nexport function withTimeoutGuard<Input, Output>(\n id: string,\n timeoutMs: number,\n execute: (input: Input) => Promise<Output>,\n): (input: Input) => Promise<Output> {\n return async (input: Input) => {\n let timer: ReturnType<typeof setTimeout> | undefined\n try {\n return await Promise.race([\n execute(input),\n new Promise<never>((_, reject) => {\n timer = setTimeout(() => {\n reject(\n new Error(\n `tool '${id}' timed out after ${timeoutMs}ms (adapter execution guard) — ` +\n `aborted so the turn can't hang indefinitely.`,\n ),\n )\n }, timeoutMs)\n }),\n ])\n } finally {\n clearTimeout(timer)\n }\n }\n}\n\nexport interface WorkspaceToolsOptions {\n /** Absolute path the agent is confined to (the spawn cwd). */\n cwd: string\n /** When false, `run_command` (and the other exec-gated tools) are omitted. Default true. */\n allowExec?: boolean\n /** Per-tool execution timeout (ms), enforced on every tool by `withTimeoutGuard`. Default 120_000. */\n execTimeoutMs?: number\n /**\n * Extra tools merged over the built-ins, keyed by id — lets an embedding\n * host add tools the built-in toolset doesn't cover. On id collision, an\n * extra tool wins over a built-in of the same id.\n */\n extraTools?: Record<string, MastraToolLike>\n}\n\n/** Resolve `p` against `cwd`, throwing if the result escapes the workspace. */\nexport function resolveInCwd(cwd: string, p: string): string {\n const base = resolve(cwd)\n const target = isAbsolute(p) ? resolve(p) : resolve(base, p)\n const rel = relative(base, target)\n if (rel === \"\" ) return target // the workspace root itself\n if (rel.startsWith(\"..\") || (isAbsolute(rel) && !target.startsWith(base + sep))) {\n throw new Error(\n `path '${p}' escapes the workspace (resolved to '${target}', outside '${base}').`,\n )\n }\n return target\n}\n\n/**\n * Stub tool for an AGENT.md-declared tool id this adapter has no executor\n * for. Resolving to THIS instead of dropping the ref keeps the id visible\n * in the model's function-calling schema — a call fails immediately with a\n * clear message, instead of the ref being silently dropped (model can't\n * even try) or an unresolved call surfacing as an opaque provider error\n * this adapter's ACP layer then loses (see `tool-call-map.ts`).\n */\nexport function makeUnwiredToolStub(id: string): ReturnType<typeof createTool> {\n return createTool({\n id,\n description:\n `NOT WIRED: '${id}' is declared in this agent's AGENT.md but this adapter has no executor ` +\n `for it. Calling it always fails immediately with an error — do not retry it.`,\n inputSchema: z.record(z.string(), z.unknown()),\n outputSchema: z.object({ error: z.string() }),\n execute: async () => {\n throw new Error(\n `tool '${id}' is declared in AGENT.md but not wired to any executor in this adapter ` +\n `(adapters/mastra-agent/src/workspace-tools.ts). This call cannot succeed — stop retrying it.`,\n )\n },\n })\n}\n\n/**\n * Build the workspace toolset, all confined to `cwd`. Returns a record keyed by\n * tool id (also the AGENT.md tool ref the resolver matches).\n */\nexport function makeWorkspaceTools(\n opts: WorkspaceToolsOptions,\n): Record<string, ReturnType<typeof createTool>> {\n const cwd = resolve(opts.cwd)\n const allowExec = opts.allowExec ?? true\n const execTimeoutMs = opts.execTimeoutMs ?? 120_000\n /**\n * Shared env for all exec calls — sets GIT_CEILING_DIRECTORIES to prevent\n * git from discovering repos above cwd (fixes #818: read_diff escaping the\n * workspace to operate on an enclosing repo).\n */\n const execEnv = { ...process.env, GIT_CEILING_DIRECTORIES: resolve(cwd, \"..\") }\n\n const guard = <Input, Output>(id: string, execute: (input: Input) => Promise<Output>) =>\n withTimeoutGuard(id, execTimeoutMs, execute)\n\n const doListDir = async (input: { path?: string }) => {\n const dir = resolveInCwd(cwd, input.path ?? \".\")\n const dirents = await fs.readdir(dir, { withFileTypes: true })\n return {\n entries: dirents.map((d) => (d.isDirectory() ? `${d.name}/` : d.name)).sort(),\n }\n }\n\n const doReadFile = async (input: { path: string }) => {\n const file = resolveInCwd(cwd, input.path)\n return { content: await fs.readFile(file, \"utf8\") }\n }\n\n const doWriteFile = async (input: { path: string; content: string }) => {\n const file = resolveInCwd(cwd, input.path)\n await fs.mkdir(resolve(file, \"..\"), { recursive: true })\n await fs.writeFile(file, input.content, \"utf8\")\n return { path: input.path, bytes: Buffer.byteLength(input.content, \"utf8\") }\n }\n\n const list_dir = createTool({\n id: \"list_dir\",\n description:\n \"List the entries of a directory in the workspace. Returns names with a trailing '/' for directories. Path is relative to the workspace root (default '.').\",\n inputSchema: z.object({\n path: z.string().default(\".\").describe(\"Directory path, relative to the workspace root.\"),\n }),\n outputSchema: z.object({ entries: z.array(z.string()) }),\n execute: guard(\"list_dir\", doListDir),\n })\n\n const directory_list = createTool({\n id: \"directory_list\",\n description: \"Alias of `list_dir` (daemon-vocabulary id) — list a workspace directory's entries.\",\n inputSchema: z.object({\n path: z.string().default(\".\").describe(\"Directory path, relative to the workspace root.\"),\n }),\n outputSchema: z.object({ entries: z.array(z.string()) }),\n execute: guard(\"directory_list\", doListDir),\n })\n\n const read_file = createTool({\n id: \"read_file\",\n description:\n \"Read a UTF-8 text file from the workspace. Path is relative to the workspace root.\",\n inputSchema: z.object({\n path: z.string().describe(\"File path, relative to the workspace root.\"),\n }),\n outputSchema: z.object({ content: z.string() }),\n execute: guard(\"read_file\", doReadFile),\n })\n\n const file_read = createTool({\n id: \"file_read\",\n description: \"Alias of `read_file` (daemon-vocabulary id) — read a UTF-8 text file from the workspace.\",\n inputSchema: z.object({\n path: z.string().describe(\"File path, relative to the workspace root.\"),\n }),\n outputSchema: z.object({ content: z.string() }),\n execute: guard(\"file_read\", doReadFile),\n })\n\n const write_file = createTool({\n id: \"write_file\",\n description:\n \"Write (creating or overwriting) a UTF-8 text file in the workspace. Creates parent directories as needed. Path is relative to the workspace root.\",\n inputSchema: z.object({\n path: z.string().describe(\"File path, relative to the workspace root.\"),\n content: z.string().describe(\"Full file contents to write.\"),\n }),\n outputSchema: z.object({ path: z.string(), bytes: z.number() }),\n execute: guard(\"write_file\", doWriteFile),\n })\n\n const file_write = createTool({\n id: \"file_write\",\n description: \"Alias of `write_file` (daemon-vocabulary id) — write a UTF-8 text file to the workspace.\",\n inputSchema: z.object({\n path: z.string().describe(\"File path, relative to the workspace root.\"),\n content: z.string().describe(\"Full file contents to write.\"),\n }),\n outputSchema: z.object({ path: z.string(), bytes: z.number() }),\n execute: guard(\"file_write\", doWriteFile),\n })\n\n const edit_file = createTool({\n id: \"edit_file\",\n description:\n \"Replace an exact substring in a workspace file. `old_string` must occur exactly once. Use for targeted edits instead of rewriting the whole file.\",\n inputSchema: z.object({\n path: z.string().describe(\"File path, relative to the workspace root.\"),\n old_string: z.string().describe(\"Exact text to replace (must be unique in the file).\"),\n new_string: z.string().describe(\"Replacement text.\"),\n }),\n outputSchema: z.object({ path: z.string(), replaced: z.boolean() }),\n execute: guard(\"edit_file\", async (input: { path: string; old_string: string; new_string: string }) => {\n const file = resolveInCwd(cwd, input.path)\n const current = await fs.readFile(file, \"utf8\")\n const count = current.split(input.old_string).length - 1\n if (count === 0) throw new Error(`old_string not found in '${input.path}'.`)\n if (count > 1) {\n throw new Error(`old_string occurs ${count}× in '${input.path}' — make it unique.`)\n }\n await fs.writeFile(file, current.replace(input.old_string, input.new_string), \"utf8\")\n return { path: input.path, replaced: true }\n }),\n })\n\n const file_info = createTool({\n id: \"file_info\",\n description:\n \"Stat a file or directory in the workspace — returns name, type, size (bytes), and modified/created timestamps.\",\n inputSchema: z.object({\n path: z.string().describe(\"File or directory path, relative to the workspace root.\"),\n }),\n outputSchema: z.object({\n name: z.string(),\n path: z.string(),\n type: z.enum([\"file\", \"directory\"]),\n size: z.number(),\n modified: z.string(),\n created: z.string(),\n }),\n execute: guard(\"file_info\", async (input: { path: string }) => {\n const abs = resolveInCwd(cwd, input.path)\n const info = await fs.stat(abs)\n return {\n name: abs.split(sep).pop() ?? input.path,\n path: input.path,\n type: info.isDirectory() ? (\"directory\" as const) : (\"file\" as const),\n size: info.size,\n modified: info.mtime.toISOString(),\n created: info.birthtime.toISOString(),\n }\n }),\n })\n\n const tools: Record<string, ReturnType<typeof createTool>> = {\n list_dir,\n directory_list,\n read_file,\n file_read,\n write_file,\n file_write,\n edit_file,\n file_info,\n }\n\n if (allowExec) {\n tools.run_command = createTool({\n id: \"run_command\",\n description:\n \"Run a shell command in the workspace directory and return its stdout/stderr/exit code. Runs with a timeout; use for builds, tests, git, etc.\",\n inputSchema: z.object({\n command: z.string().describe(\"The shell command to run (executed in the workspace root).\"),\n }),\n outputSchema: z.object({\n stdout: z.string(),\n stderr: z.string(),\n exitCode: z.number(),\n }),\n execute: guard(\"run_command\", async (input: { command: string }) => {\n try {\n const { stdout, stderr } = await execAsync(input.command, {\n cwd,\n timeout: execTimeoutMs,\n maxBuffer: 10 * 1024 * 1024,\n env: execEnv,\n })\n return { stdout, stderr, exitCode: 0 }\n } catch (err) {\n const e = err as { stdout?: string; stderr?: string; code?: number; message?: string }\n return {\n stdout: e.stdout ?? \"\",\n stderr: e.stderr ?? e.message ?? String(err),\n exitCode: typeof e.code === \"number\" ? e.code : 1,\n }\n }\n }),\n })\n\n tools.command_execute = createTool({\n id: \"command_execute\",\n description:\n \"Run an allowlisted command in the workspace directory. The command's basename must appear in \" +\n \"<workspace>/.agentproto/allowed-commands.json (default-deny — a missing or empty file means \" +\n \"nothing runs). Unlike `run_command`, args are passed as an argv array with no shell interpolation \" +\n \"(spawned with shell:false). Returns stdout/stderr/exitCode.\",\n inputSchema: z.object({\n command: z\n .string()\n .min(1)\n .describe(\"Executable name or path — checked against the allowlist by basename.\"),\n args: z\n .array(z.string())\n .optional()\n .describe(\"Argv array, passed verbatim (no shell expansion).\"),\n }),\n outputSchema: z.object({\n stdout: z.string(),\n stderr: z.string(),\n exitCode: z.number(),\n warning: z.string().optional(),\n }),\n execute: guard(\"command_execute\", async (input: { command: string; args?: string[] }) => {\n const allowlistEntries = await loadAllowlistEntries(cwd)\n const baseName = basename(input.command)\n if (!isCommandAllowed(allowlistEntries, baseName, input.args ?? [])) {\n const allowedBasenames =\n [...new Set(allowlistEntries.map((e) => e.command))].sort().join(\", \") || \"(empty)\"\n const basenameKnown = allowlistEntries.some((e) => e.command === baseName)\n throw new Error(\n basenameKnown\n ? `command_execute: '${baseName}' is allowlisted but its argv doesn't match any allowed ` +\n `pattern for it. Check the \"args\" constraints in .agentproto/allowed-commands.json.`\n : `command_execute: '${baseName}' is not in the workspace allowlist. Add it to ` +\n `.agentproto/allowed-commands.json under \"commands\": [...]. Currently allowed: ${allowedBasenames}.`,\n )\n }\n const warning = isInterpreterBasename(baseName) ? interpreterExecWarning(baseName) : undefined\n if (warning) console.error(`[command_execute] ⚠ ${warning}`)\n try {\n const { stdout, stderr } = await execFileAsync(input.command, input.args ?? [], {\n cwd,\n timeout: execTimeoutMs,\n maxBuffer: 10 * 1024 * 1024,\n env: execEnv,\n })\n return { stdout, stderr, exitCode: 0, ...(warning ? { warning } : {}) }\n } catch (err) {\n const e = err as { stdout?: string; stderr?: string; code?: number; message?: string }\n return {\n stdout: e.stdout ?? \"\",\n stderr: e.stderr ?? e.message ?? String(err),\n exitCode: typeof e.code === \"number\" ? e.code : 1,\n ...(warning ? { warning } : {}),\n }\n }\n }),\n })\n\n tools.read_diff = createTool({\n id: \"read_diff\",\n description:\n \"Show `git diff` for the workspace — staged and unstaged changes against HEAD (or against `base` if given), as unified diff text. Optionally scoped to `paths`.\",\n inputSchema: z.object({\n paths: z\n .array(z.string())\n .optional()\n .describe(\"Restrict the diff to these paths, relative to the workspace root.\"),\n base: z.string().optional().describe(\"Git ref to diff against. Defaults to HEAD.\"),\n }),\n outputSchema: z.object({ diff: z.string() }),\n execute: guard(\"read_diff\", async (input: { paths?: string[]; base?: string }) => {\n const relPaths = (input.paths ?? []).map((p) => {\n const abs = resolveInCwd(cwd, p)\n return relative(cwd, abs) || \".\"\n })\n const args = [\n \"diff\",\n input.base ?? \"HEAD\",\n ...(relPaths.length ? [\"--\", ...relPaths] : []),\n ]\n try {\n const { stdout } = await execFileAsync(\"git\", args, {\n cwd,\n timeout: execTimeoutMs,\n maxBuffer: 10 * 1024 * 1024,\n env: execEnv,\n })\n return { diff: stdout }\n } catch (err) {\n const e = err as { stderr?: string; message?: string }\n throw new Error(`git diff failed: ${e.stderr ?? e.message ?? String(err)}`)\n }\n }),\n })\n\n tools.apply_patch = createTool({\n id: \"apply_patch\",\n description:\n \"Apply a unified diff to files in the workspace (`git apply --whitespace=nowarn`). Paths in the patch that escape the workspace are rejected.\",\n inputSchema: z.object({\n patch: z.string().describe(\"Unified diff text to apply.\"),\n }),\n outputSchema: z.object({ applied: z.boolean(), output: z.string() }),\n execute: guard(\"apply_patch\", async (input: { patch: string }) => {\n for (const p of extractPatchPaths(input.patch)) {\n resolveInCwd(cwd, p) // throws if the patch touches a path outside cwd\n }\n const patchFile = join(tmpdir(), `mastra-agent-patch-${randomUUID()}.diff`)\n await fs.writeFile(patchFile, input.patch, \"utf8\")\n try {\n const { stdout, stderr } = await execFileAsync(\n \"git\",\n [\"apply\", \"--whitespace=nowarn\", patchFile],\n { cwd, timeout: execTimeoutMs, maxBuffer: 10 * 1024 * 1024, env: execEnv },\n )\n return { applied: true, output: stdout || stderr || \"\" }\n } catch (err) {\n const e = err as { stdout?: string; stderr?: string; message?: string }\n throw new Error(`git apply failed: ${e.stderr ?? e.stdout ?? e.message ?? String(err)}`)\n } finally {\n await fs.unlink(patchFile).catch(() => {})\n }\n }),\n })\n\n tools.run_tests = createTool({\n id: \"run_tests\",\n description:\n \"Run the workspace's test command (default `npm test`, overridable via `command` or the MASTRA_AGENT_TEST_CMD env) and return its exit code + output tail.\",\n inputSchema: z.object({\n command: z\n .string()\n .optional()\n .describe(\"Override the test command. Its argv0 must be one of npm, pnpm, yarn, node, npx.\"),\n }),\n outputSchema: z.object({ exitCode: z.number(), output: z.string() }),\n execute: guard(\"run_tests\", async (input: { command?: string }) => {\n const commandStr = input.command ?? process.env.MASTRA_AGENT_TEST_CMD ?? \"npm test\"\n const argv0 = commandStr.trim().split(/\\s+/)[0]\n if (!argv0 || !ALLOWED_TEST_ARGV0.has(argv0)) {\n throw new Error(\n `run_tests: command '${commandStr}' is not allowed — argv0 must be one of ${[...ALLOWED_TEST_ARGV0].join(\", \")}.`,\n )\n }\n try {\n const { stdout, stderr } = await execAsync(commandStr, {\n cwd,\n timeout: execTimeoutMs,\n maxBuffer: 10 * 1024 * 1024,\n env: execEnv,\n })\n return { exitCode: 0, output: tail(stdout + stderr) }\n } catch (err) {\n const e = err as { stdout?: string; stderr?: string; code?: number; message?: string }\n return {\n exitCode: typeof e.code === \"number\" ? e.code : 1,\n output: tail((e.stdout ?? \"\") + (e.stderr ?? e.message ?? String(err))),\n }\n }\n }),\n })\n }\n\n return {\n ...tools,\n ...(opts.extraTools as Record<string, ReturnType<typeof createTool>> | undefined),\n }\n}\n","/**\n * Daemon sub-agent-spawning tools — the Mastra-tool front for\n * {@link DaemonClient}. Lets the agent spawn/prompt/read/list sibling\n * sessions through the agentproto daemon (any adapter: claude-code, hermes,\n * another mastra-agent, ...), mirroring `workspace-tools.ts`'s style\n * (`createTool`, zod schemas, a bounded `tail` on large text output, a\n * per-call timeout guard).\n *\n * Every tool fails fast with a clear message when no daemon is discoverable\n * ({@link DaemonNotFoundError}'s message) instead of hanging — `DaemonClient`\n * throws that before any network call is attempted.\n */\n\nimport { createTool } from \"@mastra/core/tools\"\nimport { z } from \"zod\"\nimport { DaemonClient, type DaemonClientOptions } from \"./daemon-client.js\"\nimport { withTimeoutGuard } from \"./workspace-tools.js\"\n\n/** Keep large daemon-returned text bounded — same policy as workspace-tools. */\nfunction tail(s: string, maxChars = 4000): string {\n return s.length > maxChars ? s.slice(-maxChars) : s\n}\n\nexport interface DaemonToolsOptions {\n /** Reuse a pre-built client (mainly a test hook) — one is built otherwise. */\n client?: DaemonClient\n /** Forwarded to `new DaemonClient(...)` when no `client` is supplied. */\n clientOptions?: DaemonClientOptions\n /** Per-tool execution timeout (ms). Default 30_000 — network calls, not\n * local fs/exec, so a shorter default than workspace-tools' 120_000. */\n execTimeoutMs?: number\n}\n\n/**\n * Build the daemon sub-agent-spawning toolset: `agent_start`, `agent_prompt`,\n * `agent_output`, `session_list`. Tool ids match `tool-categories.ts`'s\n * `CATEGORY_BY_TOOL` entries exactly (all category `mcp`, default policy\n * `ask`).\n */\nexport function makeDaemonTools(\n opts: DaemonToolsOptions = {},\n): Record<string, ReturnType<typeof createTool>> {\n const client = opts.client ?? new DaemonClient(opts.clientOptions)\n const execTimeoutMs = opts.execTimeoutMs ?? 30_000\n const guard = <Input, Output>(id: string, execute: (input: Input) => Promise<Output>) =>\n withTimeoutGuard(id, execTimeoutMs, execute)\n\n const agent_start = createTool({\n id: \"agent_start\",\n description:\n \"Spawn a new agent session via the agentproto daemon (any adapter: claude-code, hermes, \" +\n \"mastra-agent, ...). The spawned session's lineage is recorded as a child of this session \" +\n \"when running under a daemon-spawned session. Returns the daemon's session descriptor \" +\n \"(includes the new session's id — pass it to `agent_prompt` / `agent_output`).\",\n inputSchema: z.object({\n adapter: z.string().describe(\"Adapter id to spawn, e.g. 'claude-code', 'hermes', 'mastra-agent'.\"),\n cwd: z.string().optional().describe(\"Working directory for the spawned session. Defaults to the daemon's workspace resolution.\"),\n model: z.string().optional().describe(\"Model id to spawn the session with, if the adapter supports selecting one.\"),\n prompt: z.string().optional().describe(\"Initial prompt to send once the session is up.\"),\n label: z.string().optional().describe(\"Human-readable label for the spawned session.\"),\n }),\n outputSchema: z.record(z.string(), z.unknown()),\n execute: guard(\"agent_start\", async (input: { adapter: string; cwd?: string; model?: string; prompt?: string; label?: string }) =>\n client.startAgent(input),\n ),\n })\n\n const agent_prompt = createTool({\n id: \"agent_prompt\",\n description:\n \"Send a follow-up message to a live session spawned via `agent_start` (or any other daemon \" +\n \"session id). Blocks until the turn drains by default; set `wait: false` to return as soon as \" +\n \"the prompt is queued.\",\n inputSchema: z.object({\n sessionId: z.string().describe(\"Target session id (from `agent_start`'s result or `session_list`).\"),\n text: z.string().describe(\"The message to send.\"),\n interrupt: z.boolean().optional().describe(\"Cancel the target session's in-flight turn and deliver this prompt instead. Default false.\"),\n wait: z.boolean().optional().describe(\"Wait for the turn to drain before returning. Default true.\"),\n }),\n outputSchema: z.record(z.string(), z.unknown()),\n execute: guard(\n \"agent_prompt\",\n async (input: { sessionId: string; text: string; interrupt?: boolean; wait?: boolean }) =>\n client.promptAgent(input.sessionId, input.text, {\n ...(input.interrupt !== undefined ? { interrupt: input.interrupt } : {}),\n ...(input.wait !== undefined ? { wait: input.wait } : {}),\n }),\n ),\n })\n\n const agent_output = createTool({\n id: \"agent_output\",\n description:\n \"Read a session's transcript (works for any agent-cli session, not just ones this agent \" +\n \"spawned). Output is tailed to the most recent text when it's large.\",\n inputSchema: z.object({\n sessionId: z.string().describe(\"Session id to read.\"),\n format: z.enum([\"markdown\", \"json\"]).optional().describe(\"Transcript rendering. Default 'json'.\"),\n }),\n outputSchema: z.object({\n adapter: z.string().optional(),\n content: z.string().optional(),\n }).catchall(z.unknown()),\n execute: guard(\"agent_output\", async (input: { sessionId: string; format?: \"markdown\" | \"json\" }) => {\n const result = await client.readOutput(input.sessionId, {\n ...(input.format ? { format: input.format } : {}),\n })\n return typeof result.content === \"string\" ? { ...result, content: tail(result.content) } : result\n }),\n })\n\n const session_list = createTool({\n id: \"session_list\",\n description: \"List sessions known to the daemon — spawned by this agent or any other client.\",\n inputSchema: z.object({\n includeArchived: z.boolean().optional().describe(\"Include archived sessions. Default false.\"),\n kind: z.string().optional().describe(\"Filter by session kind (e.g. 'agent-cli', 'command', 'all').\"),\n }),\n outputSchema: z.object({ sessions: z.array(z.record(z.string(), z.unknown())) }),\n execute: guard(\"session_list\", async (input: { includeArchived?: boolean; kind?: string }) =>\n client.listSessions(input),\n ),\n })\n\n return { agent_start, agent_prompt, agent_output, session_list }\n}\n","/**\n * SQLite-backed memory for the agent, via Mastra's LibSQL store.\n *\n * Each ACP session is a memory *thread* (see acp-host.ts), so the agent recalls\n * earlier turns within a session. The db is a single SQLite file (LibSQL is a\n * SQLite fork) under `~/.agentproto/mastra-agent/` by default — persistent\n * across spawns — overridable with `AGENTPROTO_MASTRA_MEMORY_DB`.\n */\n\nimport { mkdirSync } from \"node:fs\"\nimport { homedir } from \"node:os\"\nimport { join } from \"node:path\"\nimport { LibSQLStore } from \"@mastra/libsql\"\nimport { Memory } from \"@mastra/memory\"\nimport type { MemoryConfig } from \"@agentproto/agent\"\n\n/** A built Mastra memory — structural, matching `@agentproto/mastra`'s\n * `MastraMemoryLike` expectation without importing the exact type. */\nexport type MastraMemoryLike = Memory\n\n/** Resolve the SQLite file path, creating the parent dir. `AGENTPROTO_MASTRA_MEMORY_DB`\n * wins; otherwise `~/.agentproto/mastra-agent/memory.db`. */\nexport function resolveMemoryDbPath(\n env: Record<string, string | undefined> = process.env,\n): string {\n const override = env.AGENTPROTO_MASTRA_MEMORY_DB\n if (override) return override\n const dir = join(homedir(), \".agentproto\", \"mastra-agent\")\n mkdirSync(dir, { recursive: true })\n return join(dir, \"memory.db\")\n}\n\n/**\n * Build the LibSQL store backing the agent's memory. Exposed separately so the\n * `AgentController` can share the SAME store instance as its `storage` (thread\n * rows, per-thread settings) — two stores on one SQLite file would race each\n * other on writes.\n */\nexport function buildSqliteStore(\n env: Record<string, string | undefined> = process.env,\n): LibSQLStore {\n const dbPath = resolveMemoryDbPath(env)\n return new LibSQLStore({ id: \"mastra-agent-memory\", url: `file:${dbPath}` })\n}\n\n/**\n * Build a Mastra `Memory` from an AIP-42 `memory:` config. Returns `undefined`\n * when memory is disabled (`scope: \"none\"`) so `buildMastraAgent` attaches none.\n *\n * - `retention_turns` → `options.lastMessages` (how many recent messages to\n * replay into context). Defaults to 20.\n * - Semantic recall is left off (it needs an embedder + vector index) — this is\n * conversation-history memory, the SQLite ask.\n * - `store` lets the caller share one LibSQL store between this memory and the\n * AgentController's storage; omitted, a fresh store is built.\n */\nexport function buildSqliteMemory(\n config?: MemoryConfig,\n env: Record<string, string | undefined> = process.env,\n store?: LibSQLStore,\n): MastraMemoryLike | undefined {\n if (config?.scope === \"none\") return undefined\n const lastMessages =\n typeof config?.retention_turns === \"number\" && config.retention_turns > 0\n ? config.retention_turns\n : 20\n return new Memory({\n storage: store ?? buildSqliteStore(env),\n options: {\n lastMessages,\n semanticRecall: false,\n workingMemory: { enabled: false },\n },\n })\n}\n","/**\n * WP1 — AIP-42 `model:` ref -> a model Mastra's `Agent` can run.\n *\n * Mastra 1.x ships a model router (`models.dev` gateway) that accepts a bare\n * `provider/model` string (e.g. `anthropic/claude-opus-4-8`,\n * `openrouter/z-ai/glm-5.2`) and resolves it to a live ai-sdk model, reading\n * the provider's key from the environment. So the resolver is a thin,\n * *validated* pass-through: extract the ref string, sanity-check the shape,\n * surface a friendly error when the obvious provider key is missing, and hand\n * the string to Mastra.\n *\n * Exception: Anthropic OAuth Access Tokens (OATs, `sk-ant-oat*`) need\n * `Authorization: Bearer`, not `x-api-key`. Mastra's router always sends\n * `x-api-key`, so OATs bypass the string path — the resolver builds the\n * ai-sdk model directly via `createAnthropic({ authToken })`.\n */\n\nimport { createAnthropic } from \"@ai-sdk/anthropic\"\nimport type { LanguageModelV3 } from \"@ai-sdk/provider\"\nimport type { ModelRef } from \"@agentproto/agent\"\n\n/** Best-effort provider -> env var map, used only for a friendly preflight\n * error. Mastra's gateway is the source of truth; this list just turns the\n * common \"forgot the key\" case into a clear message instead of a deep ai-sdk\n * stack trace. Providers not listed here skip the preflight check. */\nconst PROVIDER_ENV: Record<string, string> = {\n openai: \"OPENAI_API_KEY\",\n anthropic: \"ANTHROPIC_API_KEY\",\n openrouter: \"OPENROUTER_API_KEY\",\n google: \"GOOGLE_GENERATIVE_AI_API_KEY\",\n groq: \"GROQ_API_KEY\",\n xai: \"XAI_API_KEY\",\n mistral: \"MISTRAL_API_KEY\",\n deepseek: \"DEEPSEEK_API_KEY\",\n}\n\n/** Pull the model id string out of an AIP-42 `ModelRef` (string | { ref }). */\nexport function modelRefToString(ref: ModelRef): string {\n if (typeof ref === \"string\") return ref.trim()\n if (ref && typeof ref === \"object\" && typeof ref.ref === \"string\") {\n return ref.ref.trim()\n }\n throw new Error(\n \"mastra-agent: AGENT.md `model` must be a `provider/model` string \" +\n \"(or { ref }); inline model objects are not supported by this adapter.\",\n )\n}\n\n/** The provider segment is everything before the first `/`. */\nexport function providerOf(modelId: string): string {\n const slash = modelId.indexOf(\"/\")\n return slash > 0 ? modelId.slice(0, slash) : modelId\n}\n\n/**\n * Infer the provider for a bare, unambiguous id so an AGENT.md stays\n * adapter-agnostic. `claude-sonnet-5` — what the claude-code / claude-sdk\n * adapters already accept bare — routes here as `anthropic/claude-sonnet-5`,\n * instead of being handed to Mastra's gateway with no provider (which fails\n * with \"could not resolve model configuration\"). Only Claude ids are\n * unambiguous today; every other provider still needs the explicit prefix.\n */\nexport function normalizeModelId(modelId: string): string {\n if (modelId.includes(\"/\")) return modelId\n if (/^claude[-.]/i.test(modelId)) return `anthropic/${modelId}`\n return modelId\n}\n\n/**\n * Resolve an AIP-42 model ref to the value Mastra's `Agent` constructor takes.\n *\n * For most providers this returns the `provider/model` string and Mastra's\n * internal router does the rest. For Anthropic OAuth Access Tokens (OATs) it\n * returns a pre-built ai-sdk `LanguageModel` with `authToken` so the token\n * is sent as `Authorization: Bearer` instead of `x-api-key`.\n *\n * `env` defaults to `process.env`; injectable for tests.\n */\nexport function resolveMastraModel(\n ref: ModelRef,\n env: Record<string, string | undefined> = process.env,\n): string | LanguageModelV3 {\n const modelId = normalizeModelId(modelRefToString(ref))\n if (!modelId) {\n throw new Error(\"mastra-agent: empty `model` ref.\")\n }\n const provider = providerOf(modelId)\n const envKey = PROVIDER_ENV[provider]\n if (envKey && !env[envKey]) {\n throw new Error(\n `mastra-agent: model '${modelId}' needs ${envKey} in the environment ` +\n `(provider '${provider}'). Set it on the spawn env or export it.`,\n )\n }\n\n if (provider === \"anthropic\") {\n const key = env[\"ANTHROPIC_API_KEY\"]\n if (key?.startsWith(\"sk-ant-oat\")) {\n const bareId = modelId.slice(modelId.indexOf(\"/\") + 1)\n return createAnthropic({ authToken: key })(bareId)\n }\n }\n\n return modelId\n}\n","/**\n * AgentprotoSignalProvider (WP-6) — a Mastra `SignalProvider` that watches\n * agentproto daemon sessions via {@link DaemonClient} and pushes their\n * lifecycle as notification signals into the native agent's thread.\n *\n * Two event sources per poll cycle (supervisor decision — no MCP JSON-RPC\n * client is built for this; the events route + a status diff is the design):\n *\n * 1. `GET /sessions/:id/events` (`client.pollEvents`) for the watched\n * kinds in {@link WATCHED_EVENT_KINDS} — `turn-end`, `error`, and the\n * permission pair (`agent-prompt` = the ask, `permission-resolved` =\n * the answer). Cursor-based via `since`/`nextSeq`.\n * 2. A status DIFF over `client.listSessions()` — the events route is the\n * per-session transcript and carries NO `exited` records (registry\n * state changes are not transcript writes; see `pollEvents`'s doc\n * comment). So each cycle lists sessions ONCE (`includeArchived: true`,\n * so a watched session that gets archived after death still reports its\n * terminal status) and compares every subscription's `status` against\n * the last seen one in subscription metadata; a transition into\n * `exited`/`killed`/`error` becomes an `exited` notification.\n *\n * Cursor + last-status live in the subscription's `metadata` — in-process\n * state only, NOT persisted across an adapter restart. A restart therefore\n * replays events from the start of the watched session's transcript; that\n * replay is harmless because every notification carries a deterministic\n * `dedupeKey` (`agentproto-daemon:<sessionId>:<eventSeq>`, `:exited` for the\n * status-diff exit) and the notifications storage coalesces on it\n * (`createNotification` → `findCoalescable`) instead of inserting duplicates.\n *\n * Poll errors never kill the loop: each subscription is polled inside its\n * own try/catch, and repeated identical failures warn once (per distinct\n * message), not once per 5s cycle.\n */\n\nimport { createTool } from \"@mastra/core/tools\"\nimport { SignalProvider } from \"@mastra/core/signals\"\nimport type { SignalProviderTarget, SignalSubscription } from \"@mastra/core/signals\"\nimport { z } from \"zod\"\nimport { DaemonClient, type DaemonClientOptions } from \"./daemon-client.js\"\nimport type { DaemonStateEmitter, StateSignalAgentLike } from \"./state-signals.js\"\n\n/** Transcript-event kinds a watch subscribes to (see the daemon's\n * `transcript-writer.ts` for the full kind set): turn boundaries, errors,\n * and the permission ask/answer pair. */\nexport const WATCHED_EVENT_KINDS = [\n \"turn-end\",\n \"error\",\n \"agent-prompt\",\n \"permission-resolved\",\n] as const\n\n/** Daemon `SessionStatus` values that mean the session is gone\n * (`packages/runtime/src/sessions.ts`'s `SessionStatus`, read as reference). */\nexport const EXIT_STATUSES = new Set([\"exited\", \"killed\", \"error\"])\n\n/** Upper bound on distinct warn-once messages kept for dedupe — a leaked-set\n * guard, not a behavior knob (hitting it just re-allows old warnings). */\nconst MAX_WARNED_MESSAGES = 200\n\nexport interface AgentprotoSignalProviderOptions {\n /** Reuse a pre-built client (the factory shares one across daemon tools and\n * this provider) — one is built from `clientOptions` otherwise. */\n client?: DaemonClient\n /** Forwarded to `new DaemonClient(...)` when no `client` is supplied. */\n clientOptions?: DaemonClientOptions\n /** Poll cadence in ms. Default 5_000. */\n pollInterval?: number\n /**\n * Daemon state-signal emitter (WP-7). When set, every poll cycle ALSO\n * pushes a daemon-state snapshot/delta signal to each thread that watches\n * at least one session — piggybacking on the same 5s cadence and the same\n * error isolation instead of running a second timer. Threads watching\n * nothing get no state signals (and cost no daemon calls), matching the\n * provider's dormant-when-unwatched behavior.\n */\n stateEmitter?: DaemonStateEmitter\n}\n\nexport class AgentprotoSignalProvider extends SignalProvider<\"agentproto-daemon\"> {\n readonly id = \"agentproto-daemon\" as const\n readonly pollInterval: number\n\n readonly #client: DaemonClient\n readonly #stateEmitter: DaemonStateEmitter | undefined\n readonly #warned = new Set<string>()\n\n constructor(opts: AgentprotoSignalProviderOptions = {}) {\n super()\n this.#client = opts.client ?? new DaemonClient(opts.clientOptions)\n this.#stateEmitter = opts.stateEmitter\n this.pollInterval = opts.pollInterval ?? 5_000\n }\n\n /**\n * Subscribe a thread to a daemon session's lifecycle. The public wrapper\n * around the base class's protected `subscribe` — `sessionId` is the daemon\n * session id (subscription `externalResourceId`). Optional `metadata.label`\n * feeds the notification summary.\n */\n watch(\n target: SignalProviderTarget,\n sessionId: string,\n metadata?: Record<string, unknown>,\n ): SignalSubscription {\n return this.subscribe(target, sessionId, metadata)\n }\n\n /** Undo a {@link watch}. Returns false when no such subscription existed. */\n unwatch(target: SignalProviderTarget, sessionId: string): boolean {\n return this.unsubscribe(target, sessionId)\n }\n\n /**\n * One poll cycle over all subscriptions. The base class only calls this\n * when at least one subscription exists, so an idle provider (nothing\n * watched) never touches the daemon — that's the \"dormant when no daemon\n * is discoverable\" behavior: discovery isn't even attempted until a watch\n * exists, and a failing first poll warns once instead of throwing.\n */\n async poll(subscriptions: SignalSubscription[]): Promise<void> {\n if (subscriptions.length === 0) return\n\n // One listSessions per cycle backs the exit status-diff for EVERY\n // subscription. A failure here (daemon gone, network) skips exit\n // detection this cycle but still lets per-subscription event polls run\n // (they'll fail and warn on their own if the daemon is truly gone).\n let sessionsById: Map<string, Record<string, unknown>> | undefined\n try {\n const { sessions } = await this.#client.listSessions({ includeArchived: true })\n sessionsById = new Map(\n sessions.filter((s) => typeof s.id === \"string\").map((s) => [s.id as string, s]),\n )\n } catch (err) {\n this.#warnOnce(`listSessions failed (exit detection skipped): ${errorMessage(err)}`)\n }\n\n for (const sub of subscriptions) {\n try {\n await this.#pollSubscription(sub, sessionsById)\n } catch (err) {\n this.#warnOnce(`session ${sub.externalResourceId}: ${errorMessage(err)}`)\n }\n }\n\n await this.#emitStateSignals(subscriptions)\n }\n\n /** WP-7: one daemon-state signal per watching thread per cycle (see\n * {@link AgentprotoSignalProviderOptions.stateEmitter}). Never throws. */\n async #emitStateSignals(subscriptions: SignalSubscription[]): Promise<void> {\n const emitter = this.#stateEmitter\n const agent = this.agent\n if (!emitter || !agent) return\n const byTarget = new Map<string, { threadId: string; resourceId: string; watched: string[] }>()\n for (const sub of subscriptions) {\n const key = `${sub.resourceId}:${sub.threadId}`\n const entry = byTarget.get(key) ?? {\n threadId: sub.threadId,\n resourceId: sub.resourceId,\n watched: [],\n }\n entry.watched.push(sub.externalResourceId)\n byTarget.set(key, entry)\n }\n for (const { threadId, resourceId, watched } of byTarget.values()) {\n try {\n await emitter.emit(agent as unknown as StateSignalAgentLike, { threadId, resourceId }, watched)\n } catch (err) {\n this.#warnOnce(`state signal for thread ${threadId}: ${errorMessage(err)}`)\n }\n }\n }\n\n async #pollSubscription(\n sub: SignalSubscription,\n sessionsById: Map<string, Record<string, unknown>> | undefined,\n ): Promise<void> {\n const sessionId = sub.externalResourceId\n const target: SignalProviderTarget = {\n threadId: sub.threadId,\n resourceId: sub.resourceId,\n ...(sub.metadata.ifIdle ? { ifIdle: sub.metadata.ifIdle as SignalProviderTarget[\"ifIdle\"] } : {}),\n }\n\n const cursor = typeof sub.metadata.cursor === \"number\" ? sub.metadata.cursor : undefined\n const result = await this.#client.pollEvents(sessionId, {\n ...(cursor !== undefined ? { since: cursor } : {}),\n types: [...WATCHED_EVENT_KINDS],\n })\n for (const [i, event] of result.events.entries()) {\n const kind = typeof event.kind === \"string\" ? event.kind : \"unknown\"\n const seq = typeof event.seq === \"number\" ? String(event.seq) : `i${i}`\n await this.notify(\n {\n source: this.id,\n kind,\n priority: kind === \"error\" ? \"high\" : \"medium\",\n summary: this.#summary(sessionId, sub, sessionsById, kind),\n payload: event,\n dedupeKey: `${this.id}:${sessionId}:${seq}`,\n },\n target,\n )\n }\n // Advance past everything the route returned, INCLUDING kinds the\n // client-side `types` filter dropped — `nextSeq` is the raw route\n // cursor, so filtered-out records are never re-fetched.\n sub.metadata.cursor = result.nextSeq\n\n // Status-diff exit detection (see module doc: the events route carries\n // no `exited` records). Watching an already-dead session notifies its\n // exit on the first cycle — deliberate: \"this session is already gone\"\n // is exactly what a fresh watcher needs to hear.\n const record = sessionsById?.get(sessionId)\n if (!record) return\n const status = typeof record.status === \"string\" ? record.status : undefined\n if (!status) return\n const lastStatus = typeof sub.metadata.lastStatus === \"string\" ? sub.metadata.lastStatus : undefined\n sub.metadata.lastStatus = status\n const alreadyNotified = lastStatus !== undefined && EXIT_STATUSES.has(lastStatus)\n if (!EXIT_STATUSES.has(status) || alreadyNotified) return\n\n const exitedWithError =\n status === \"error\" || (typeof record.exitCode === \"number\" && record.exitCode !== 0)\n await this.notify(\n {\n source: this.id,\n kind: \"exited\",\n priority: exitedWithError ? \"high\" : \"medium\",\n summary: `${this.#summary(sessionId, sub, sessionsById, \"exited\")} (status ${status})`,\n payload: record,\n dedupeKey: `${this.id}:${sessionId}:exited`,\n },\n target,\n )\n }\n\n /** `Session <id> (<label>): <kind>` — label from watch metadata, falling\n * back to the daemon's session record. */\n #summary(\n sessionId: string,\n sub: SignalSubscription,\n sessionsById: Map<string, Record<string, unknown>> | undefined,\n kind: string,\n ): string {\n const recordLabel = sessionsById?.get(sessionId)?.label\n const label =\n typeof sub.metadata.label === \"string\"\n ? sub.metadata.label\n : typeof recordLabel === \"string\"\n ? recordLabel\n : undefined\n return `Session ${sessionId}${label ? ` (${label})` : \"\"}: ${kind}`\n }\n\n #warnOnce(message: string): void {\n if (this.#warned.has(message)) return\n if (this.#warned.size >= MAX_WARNED_MESSAGES) this.#warned.clear()\n this.#warned.add(message)\n console.warn(`[@agentproto/adapter-mastra-agent] ${this.id}: ${message}`)\n }\n\n /**\n * Agent-callable subscription management. The target thread resolves from\n * the tool's own execution context (`context.agent.threadId`/`resourceId`,\n * populated by the agent tool-call step) — explicit `threadId`/`resourceId`\n * inputs override it for the rare host driving these outside a run.\n *\n * Subscriptions made here set `ifIdle: { behavior: \"persist\" }`: this\n * adapter fronts an ACP client that only streams during a prompt turn, so\n * WAKING an idle thread would run a hidden background turn nobody sees.\n * Persisting instead lands the notification in the thread history + inbox,\n * where the next real turn picks it up.\n */\n getTools(): Record<string, ReturnType<typeof createTool>> {\n const watch_session = createTool({\n id: \"watch_session\",\n description:\n \"Watch a daemon session: subscribe this conversation to its lifecycle (turn ends, errors, \" +\n \"permission asks, exit). Events arrive as notifications — check the notification inbox or \" +\n \"the conversation for them. Use session ids from `agent_start` / `session_list`.\",\n inputSchema: z.object({\n sessionId: z.string().describe(\"Daemon session id to watch.\"),\n label: z.string().optional().describe(\"Human-readable label used in notification summaries.\"),\n threadId: z.string().optional().describe(\"Explicit target thread id. Defaults to the current thread.\"),\n resourceId: z.string().optional().describe(\"Explicit target resource id. Defaults to the current resource.\"),\n }),\n outputSchema: z.object({ subscribed: z.boolean(), sessionId: z.string(), threadId: z.string() }),\n execute: async (input, context) => {\n const threadId = input.threadId ?? context.agent?.threadId\n const resourceId = input.resourceId ?? context.agent?.resourceId\n if (!threadId || !resourceId) {\n throw new Error(\n \"watch_session: no target thread — this call ran outside an agent thread, so pass \" +\n \"threadId and resourceId explicitly.\",\n )\n }\n this.watch({ threadId, resourceId, ifIdle: { behavior: \"persist\" } }, input.sessionId, {\n ...(input.label ? { label: input.label } : {}),\n ifIdle: { behavior: \"persist\" },\n })\n return { subscribed: true, sessionId: input.sessionId, threadId }\n },\n })\n\n const unwatch_session = createTool({\n id: \"unwatch_session\",\n description:\n \"Stop watching a daemon session previously subscribed with `watch_session`.\",\n inputSchema: z.object({\n sessionId: z.string().describe(\"Daemon session id to stop watching.\"),\n threadId: z.string().optional().describe(\"Explicit target thread id. Defaults to the current thread.\"),\n resourceId: z.string().optional().describe(\"Explicit target resource id. Defaults to the current resource.\"),\n }),\n outputSchema: z.object({ unsubscribed: z.boolean(), sessionId: z.string() }),\n execute: async (input, context) => {\n const threadId = input.threadId ?? context.agent?.threadId\n const resourceId = input.resourceId ?? context.agent?.resourceId\n if (!threadId || !resourceId) {\n throw new Error(\n \"unwatch_session: no target thread — this call ran outside an agent thread, so pass \" +\n \"threadId and resourceId explicitly.\",\n )\n }\n const unsubscribed = this.unwatch({ threadId, resourceId }, input.sessionId)\n return { unsubscribed, sessionId: input.sessionId }\n },\n })\n\n return { watch_session, unwatch_session }\n }\n}\n\nfunction errorMessage(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n","/**\n * Daemon state signals (WP-7) — a snapshot/delta emitter that keeps the\n * native agent's thread carrying a live picture of \"what's happening around\n * me\": the daemon session tree it cares about (its own children + explicitly\n * watched sessions) and the workspace git status (branch + dirty file count).\n *\n * Emission uses the FIRST-CLASS state-signal API — `agent.sendStateSignal`\n * exists in installed @mastra/core 1.57.0 (`dist/agent/agent.d.ts`,\n * experimental) with the full snapshot/delta + `cacheKey` machinery\n * (`dist/agent/state-signals.d.ts`): Mastra tracks the current cacheKey per\n * thread and skips an unchanged re-send (`{skipped: true, reason:\n * 'unchanged'}`). This emitter ALSO dedups locally (per-target last cacheKey)\n * so an unchanged state costs no `sendStateSignal` call at all — the\n * framework-side dedup is the safety net, not the hot path.\n *\n * Mode selection per the plan: the first emission for a target is a full\n * `snapshot`; later changed emissions are `delta`s describing what moved\n * (session added/removed/status change, git branch/dirty change). Local\n * per-target memory is in-process only — an adapter restart re-emits a full\n * snapshot, which is exactly the right recovery behavior.\n *\n * Targets always get `ifIdle: { behavior: \"persist\" }` — same rationale as\n * the notification watch path (signal-provider.ts): this adapter fronts an\n * ACP client with no surface for an unprompted background run, so state lands\n * in the thread history for the next real turn instead of waking one.\n *\n * Git status runs `git status --porcelain=v1 --branch` via `execFile` with\n * `GIT_CEILING_DIRECTORIES` set to the workspace's PARENT: the workspace dir\n * is expected to BE the repo root (or contain the repo), and the ceiling\n * stops git from wandering up into some unrelated enclosing repo when the\n * workspace isn't a repo at all. A workspace that is a deep subdir of a repo\n * therefore reports no git state — acceptable for this adapter, whose\n * workspace cwd is the checkout root.\n */\n\nimport { execFile } from \"node:child_process\"\nimport { dirname, resolve } from \"node:path\"\nimport { promisify } from \"node:util\"\nimport type { AgentStateSignalInput } from \"@mastra/core/agent\"\nimport type { DaemonClient } from \"./daemon-client.js\"\n\nconst execFileAsync = promisify(execFile)\n\n/** One daemon session row, reduced to the fields the state picture needs. */\nexport interface DaemonStateSession {\n id: string\n label?: string\n adapter?: string\n status?: string\n parentSessionId?: string\n}\n\nexport interface DaemonGitState {\n branch?: string\n dirtyFiles: number\n}\n\nexport interface DaemonStateSnapshot {\n /** Own children (`parentSessionId === AGENTPROTO_SESSION_ID`) + watched ids, sorted by id. */\n sessions: DaemonStateSession[]\n /** Undefined when the workspace isn't a git repo (or git isn't runnable). */\n git?: DaemonGitState\n}\n\n/** The single agent method this emitter calls, typed structurally so tests\n * (and the provider) don't need a full `Agent`. Matches\n * `Agent.sendStateSignal(state, target)` in @mastra/core 1.57.0. */\nexport interface StateSignalAgentLike {\n sendStateSignal(\n state: AgentStateSignalInput,\n target: {\n threadId: string\n resourceId: string\n ifIdle?: { behavior?: \"wake\" | \"persist\" | \"discard\" }\n },\n ): Promise<unknown>\n}\n\nexport interface DaemonStateEmitterOptions {\n client: DaemonClient\n /** Workspace dir the git status reads. Defaults to `process.cwd()`. */\n cwd?: string\n /** Env carrying `AGENTPROTO_SESSION_ID` (own-children filter). Defaults to `process.env`. */\n env?: NodeJS.ProcessEnv\n /** Injectable `git <args>` runner returning stdout — test hook. */\n runGit?: (args: string[], cwd: string) => Promise<string>\n}\n\n/** Stable id every emission shares — Mastra keys per-thread state tracking\n * (version, cacheKey, active copies) on it. */\nexport const DAEMON_STATE_SIGNAL_ID = \"agentproto-daemon-state\"\n\nexport type EmitResult = \"snapshot\" | \"delta\" | \"unchanged\"\n\nexport class DaemonStateEmitter {\n readonly #client: DaemonClient\n readonly #cwd: string\n readonly #env: NodeJS.ProcessEnv\n readonly #runGit: (args: string[], cwd: string) => Promise<string>\n readonly #lastByTarget = new Map<string, { cacheKey: string; snapshot: DaemonStateSnapshot }>()\n\n constructor(opts: DaemonStateEmitterOptions) {\n this.#client = opts.client\n this.#cwd = opts.cwd ?? process.cwd()\n this.#env = opts.env ?? process.env\n this.#runGit = opts.runGit ?? defaultRunGit\n }\n\n /**\n * Compute the current daemon-state snapshot: sessions that are either this\n * adapter's own daemon children or in `watchedSessionIds`, plus git status.\n * Either half failing degrades (empty sessions / no git) rather than throws\n * only for git; a daemon listSessions failure DOES throw — the caller (the\n * signal provider's poll loop) already isolates and warn-onces it.\n */\n async computeSnapshot(watchedSessionIds: readonly string[]): Promise<DaemonStateSnapshot> {\n const ownSessionId = this.#env.AGENTPROTO_SESSION_ID\n const watched = new Set(watchedSessionIds)\n const { sessions: rows } = await this.#client.listSessions({ includeArchived: true })\n const sessions = rows\n .filter((row): row is Record<string, unknown> & { id: string } => typeof row.id === \"string\")\n .filter(\n (row) =>\n watched.has(row.id) ||\n (ownSessionId !== undefined && row.parentSessionId === ownSessionId),\n )\n .map(\n (row): DaemonStateSession => ({\n id: row.id,\n ...(typeof row.label === \"string\" ? { label: row.label } : {}),\n ...(typeof row.adapter === \"string\" ? { adapter: row.adapter } : {}),\n ...(typeof row.status === \"string\" ? { status: row.status } : {}),\n ...(typeof row.parentSessionId === \"string\"\n ? { parentSessionId: row.parentSessionId }\n : {}),\n }),\n )\n .sort((a, b) => a.id.localeCompare(b.id))\n\n const git = await this.#gitState()\n return { sessions, ...(git ? { git } : {}) }\n }\n\n /**\n * Compute + send the state signal to one target thread. Returns what was\n * sent: a full `snapshot` (first emission for this target), a `delta`\n * (changed since last), or `unchanged` (nothing sent).\n */\n async emit(\n agent: StateSignalAgentLike,\n target: { threadId: string; resourceId: string },\n watchedSessionIds: readonly string[],\n ): Promise<EmitResult> {\n const snapshot = await this.computeSnapshot(watchedSessionIds)\n const cacheKey = snapshotCacheKey(snapshot)\n const targetKey = `${target.resourceId}:${target.threadId}`\n const prev = this.#lastByTarget.get(targetKey)\n if (prev?.cacheKey === cacheKey) return \"unchanged\"\n\n const mode: EmitResult = prev ? \"delta\" : \"snapshot\"\n const contents =\n mode === \"snapshot\" ? renderSnapshot(snapshot) : renderDelta(prev!.snapshot, snapshot)\n await agent.sendStateSignal(\n {\n id: DAEMON_STATE_SIGNAL_ID,\n cacheKey,\n mode,\n contents,\n value: snapshot,\n ...(mode === \"delta\" ? { delta: diffSnapshots(prev!.snapshot, snapshot) } : {}),\n },\n { ...target, ifIdle: { behavior: \"persist\" } },\n )\n this.#lastByTarget.set(targetKey, { cacheKey, snapshot })\n return mode\n }\n\n async #gitState(): Promise<DaemonGitState | undefined> {\n try {\n const out = await this.#runGit([\"status\", \"--porcelain=v1\", \"--branch\"], this.#cwd)\n const lines = out.split(\"\\n\").filter((line) => line.length > 0)\n const header = lines[0]?.startsWith(\"## \") ? lines[0].slice(3) : undefined\n // \"## main...origin/main [ahead 1]\" → \"main\"; \"## HEAD (no branch)\" kept whole.\n const branch = header?.split(\"...\")[0]\n const dirtyFiles = lines.filter((line) => !line.startsWith(\"## \")).length\n return { ...(branch ? { branch } : {}), dirtyFiles }\n } catch {\n return undefined\n }\n }\n}\n\nasync function defaultRunGit(args: string[], cwd: string): Promise<string> {\n const { stdout } = await execFileAsync(\"git\", args, {\n cwd,\n env: {\n ...process.env,\n // Stop repo discovery from walking above the workspace (see module doc).\n GIT_CEILING_DIRECTORIES: dirname(resolve(cwd)),\n },\n timeout: 10_000,\n })\n return stdout\n}\n\n/** Deterministic content key: identical state → identical key, any change →\n * a different key. The snapshot is built from sorted sessions and plain\n * fields, so JSON order is stable. */\nfunction snapshotCacheKey(snapshot: DaemonStateSnapshot): string {\n return JSON.stringify(snapshot)\n}\n\nfunction describeSession(s: DaemonStateSession): string {\n const label = s.label ? ` (${s.label})` : \"\"\n const adapter = s.adapter ? ` [${s.adapter}]` : \"\"\n return `${s.id}${label}${adapter}: ${s.status ?? \"unknown\"}`\n}\n\nfunction renderSnapshot(snapshot: DaemonStateSnapshot): string {\n const lines = [\"Daemon state snapshot:\"]\n if (snapshot.sessions.length === 0) {\n lines.push(\"- sessions: none (no children or watched sessions)\")\n } else {\n lines.push(\"- sessions:\")\n for (const s of snapshot.sessions) lines.push(` - ${describeSession(s)}`)\n }\n if (snapshot.git) {\n lines.push(\n `- workspace git: ${snapshot.git.branch ?? \"?\"}, ${snapshot.git.dirtyFiles} dirty file(s)`,\n )\n }\n return lines.join(\"\\n\")\n}\n\nexport interface DaemonStateDelta {\n addedSessions: DaemonStateSession[]\n removedSessions: DaemonStateSession[]\n statusChanges: Array<{ id: string; from?: string; to?: string }>\n git?: { from?: DaemonGitState; to?: DaemonGitState }\n}\n\nfunction diffSnapshots(prev: DaemonStateSnapshot, next: DaemonStateSnapshot): DaemonStateDelta {\n const prevById = new Map(prev.sessions.map((s) => [s.id, s]))\n const nextById = new Map(next.sessions.map((s) => [s.id, s]))\n const addedSessions = next.sessions.filter((s) => !prevById.has(s.id))\n const removedSessions = prev.sessions.filter((s) => !nextById.has(s.id))\n const statusChanges = next.sessions\n .filter((s) => prevById.has(s.id) && prevById.get(s.id)!.status !== s.status)\n .map((s) => {\n const from = prevById.get(s.id)!.status\n return { id: s.id, ...(from !== undefined ? { from } : {}), ...(s.status !== undefined ? { to: s.status } : {}) }\n })\n const gitChanged = JSON.stringify(prev.git) !== JSON.stringify(next.git)\n return {\n addedSessions,\n removedSessions,\n statusChanges,\n ...(gitChanged\n ? {\n git: {\n ...(prev.git ? { from: prev.git } : {}),\n ...(next.git ? { to: next.git } : {}),\n },\n }\n : {}),\n }\n}\n\nfunction renderDelta(prev: DaemonStateSnapshot, next: DaemonStateSnapshot): string {\n const delta = diffSnapshots(prev, next)\n const lines = [\"Daemon state changed:\"]\n for (const s of delta.addedSessions) lines.push(`- new session ${describeSession(s)}`)\n for (const s of delta.removedSessions) lines.push(`- session ${s.id} no longer listed`)\n for (const c of delta.statusChanges) {\n lines.push(`- session ${c.id}: ${c.from ?? \"unknown\"} → ${c.to ?? \"unknown\"}`)\n }\n if (delta.git) {\n const to = delta.git.to\n lines.push(\n to\n ? `- workspace git: ${to.branch ?? \"?\"}, ${to.dirtyFiles} dirty file(s)`\n : \"- workspace git state no longer readable\",\n )\n }\n return lines.join(\"\\n\")\n}\n","/**\n * Maps our workspace/daemon tool ids onto Mastra AgentController's\n * {@link ToolCategory}, and declares the default per-category approval\n * policy.\n *\n * `ToolCategory` (installed @mastra/core 1.57.0) is a closed union:\n * `'read' | 'edit' | 'execute' | 'mcp' | 'other'` — narrower than the plan's\n * read/write/execute/spawn shape. The mapping between the two:\n * - plan \"write\" → Mastra \"edit\"\n * - plan \"spawn\" → Mastra \"mcp\"\n * Any tool id this resolver doesn't recognize returns `null`, which the\n * controller treats as category `'other'`.\n */\n\nimport type { PermissionRules, ToolCategory } from \"@mastra/core/agent-controller\"\n\nconst CATEGORY_BY_TOOL: Record<string, ToolCategory> = {\n list_dir: \"read\",\n read_file: \"read\",\n read_diff: \"read\",\n write_file: \"edit\",\n edit_file: \"edit\",\n apply_patch: \"edit\",\n run_command: \"execute\",\n run_tests: \"execute\",\n // Daemon verbs (WP-5) — spawning/prompting/reading a sibling session is the\n // same \"reach outside this run\" shape as an MCP tool call, so it gets\n // Mastra's `mcp` category (default policy `ask`, see below).\n agent_start: \"mcp\",\n agent_prompt: \"mcp\",\n agent_output: \"mcp\",\n session_list: \"mcp\",\n // AgentController's built-in `subagent` spawner (WP-5) — spawning an\n // in-process reviewer is the same \"reach outside this run\" shape as the\n // daemon spawn verbs above, so it shares their `mcp` category and default\n // `ask` policy rather than `other`'s (also `ask` today, but a distinct\n // category keeps the two spawn surfaces — daemon vs. in-process — tunable\n // independently later without a behavior change now).\n subagent: \"mcp\",\n // Signal-provider subscription tools (WP-6) — deliberately NOT `mcp` like\n // the daemon verbs above: watching a session only registers an in-process\n // subscription whose polling reads session metadata and transcript events,\n // the same risk class as reading files. It can't spawn, prompt, or mutate\n // anything outside this process, so it auto-allows as `read` instead of\n // prompting on every watch.\n watch_session: \"read\",\n unwatch_session: \"read\",\n // Notification inbox (WP-7, Mastra's `createNotificationInboxTool`) —\n // `read`: its mutating actions (markSeen/dismiss/archive) only flip inbox\n // bookkeeping on the agent's OWN notifications, never workspace or daemon\n // state. Prompting for approval on every inbox check would defeat the\n // inbox (the agent is supposed to consult it freely each turn).\n \"notification-inbox\": \"read\",\n // `submit_plan` (WP-3) gates itself: calling it always suspends the run\n // for the user's approve/reject decision (see modes.ts's plan mode). It\n // has no \"other\"-category behavior worth asking about a second time before\n // that suspend even runs — see the per-tool \"allow\" override below.\n submit_plan: \"other\",\n}\n\n/** Resolve a tool id to its Mastra {@link ToolCategory}, or `null` if unmapped\n * (the controller then treats it as category `'other'`). Matches the\n * `AgentControllerConfig.toolCategoryResolver` signature. */\nexport function toolCategoryResolver(toolName: string): ToolCategory | null {\n return CATEGORY_BY_TOOL[toolName] ?? null\n}\n\n/**\n * Default approval policy: reads are auto-allowed, everything else asks —\n * except `submit_plan`, which is let through the generic tool-approval gate\n * so its own suspend-based plan-approval flow (see modes.ts) is the only\n * approval prompt the user sees for it, not a redundant \"run submit_plan?\"\n * ask in front of it.\n */\nexport const DEFAULT_PERMISSION_RULES: PermissionRules = {\n categories: {\n read: \"allow\",\n edit: \"ask\",\n execute: \"ask\",\n mcp: \"ask\",\n other: \"ask\",\n },\n tools: {\n submit_plan: \"allow\",\n },\n}\n","/**\n * Plan → build → review modes for the AgentController, plus a parser that\n * lets an AGENT.md override them with its own `## Modes` section.\n *\n * Mode shape is `AgentControllerMode` (installed @mastra/core 1.57.0):\n * `availableTools` is a visibility allowlist of FINAL exposed tool names —\n * `undefined` means no restriction (all tools visible), `[]` means none.\n * `transitionsTo` is the mode `submit_plan` approval switches to; unset\n * falls back to the controller's default mode.\n */\n\nimport type { AgentControllerMode } from \"@mastra/core/agent-controller\"\n\nexport const PLAN_MODE: AgentControllerMode = {\n id: \"plan\",\n name: \"Plan\",\n description: \"Investigate the task and get a plan approved before touching code.\",\n instructions:\n \"Investigate the task: read the relevant code and history, run read-only commands to understand \" +\n \"current behavior. Do not write or edit files in this mode. Once you have a plan, call `submit_plan` \" +\n \"with the path to the plan you've written for the user to review — do not paste the plan into chat. \" +\n \"Wait for approval before implementing.\",\n availableTools: [\"read_file\", \"list_dir\", \"read_diff\", \"run_command\", \"submit_plan\"],\n transitionsTo: \"build\",\n metadata: { default: true },\n}\n\nexport const BUILD_MODE: AgentControllerMode = {\n id: \"build\",\n name: \"Build\",\n description: \"Implement the approved plan.\",\n instructions:\n \"Implement the approved plan. Write and edit files and run commands as needed, keeping changes \" +\n \"scoped to what the plan described. When the implementation is done, move on to review.\",\n transitionsTo: \"review\",\n}\n\nexport const REVIEW_MODE: AgentControllerMode = {\n id: \"review\",\n name: \"Review\",\n description: \"Review the changes, run checks, and report.\",\n instructions:\n \"Review the changes made in build mode: read the diff, run type-checks and tests, and report the \" +\n \"result. If something is broken, describe what's wrong so planning can resume.\",\n availableTools: [\"read_file\", \"read_diff\", \"run_command\", \"run_tests\", \"list_dir\"],\n transitionsTo: \"plan\",\n}\n\n/** The built-in mode set, used when an AGENT.md carries no `## Modes` section. */\nexport const DEFAULT_MODES: readonly AgentControllerMode[] = [PLAN_MODE, BUILD_MODE, REVIEW_MODE]\n\n/** The built-in default mode id — matches `PLAN_MODE.metadata.default`. */\nexport const DEFAULT_MODE_ID = \"plan\"\n\nexport interface ParsedModes {\n modes: AgentControllerMode[]\n defaultModeId: string\n}\n\nconst MODES_HEADING_RE = /^##\\s+Modes\\s*$/i\nconst TOP_HEADING_RE = /^##\\s+/\nconst MODE_SUBHEADING_RE = /^###\\s+(.*)$/\n\n/** Title-case a kebab/snake-case mode id for a display `name` (`code-review` -> `Code Review`). */\nfunction titleCase(id: string): string {\n return id\n .replace(/[-_]+/g, \" \")\n .replace(/\\b\\w/g, (c) => c.toUpperCase())\n}\n\n/**\n * Parse an AGENT.md body's `## Modes` section, if present.\n *\n * Format — one `### <id>` subsection per mode:\n *\n * ```md\n * ## Modes\n *\n * ### plan\n * default: true\n * tools: read_file, list_dir, run_command, submit_plan\n * transitions_to: build\n *\n * Investigate the task and propose a plan. Call submit_plan when ready.\n *\n * ### build\n * transitions_to: review\n *\n * Implement the approved plan.\n * ```\n *\n * Recognized per-mode keys, one per line, at the top of the subsection (in any\n * order): `tools:` (comma-separated tool ids — omit for \"all tools visible\"),\n * `transitions_to:` (target mode id), `default: true` (marks the mode entered\n * when a thread has no persisted mode). Everything after the last recognized\n * key line, up to the next `### ` subsection, is the mode's `instructions`.\n *\n * The default mode is whichever mode is flagged `default: true`, or the first\n * subsection when none is flagged. At most one mode may be flagged default.\n *\n * Returns `undefined` when the body has no `## Modes` heading at all (callers\n * fall back to {@link DEFAULT_MODES}). Throws a descriptive `Error` for a\n * `## Modes` section that parses to zero modes, a `### ` subsection with no\n * id, a duplicate mode id, or more than one `default: true` flag — all signal\n * a typo'd AGENT.md rather than a shape this parser should silently paper\n * over.\n */\nexport function parseModesFromAgentMd(body: string): ParsedModes | undefined {\n const lines = body.split(/\\r?\\n/)\n\n let start = -1\n for (let i = 0; i < lines.length; i++) {\n if (MODES_HEADING_RE.test(lines[i]!)) {\n start = i + 1\n break\n }\n }\n if (start === -1) return undefined\n\n let end = lines.length\n for (let i = start; i < lines.length; i++) {\n if (TOP_HEADING_RE.test(lines[i]!)) {\n end = i\n break\n }\n }\n const sectionLines = lines.slice(start, end)\n\n const subsections: Array<{ id: string; lines: string[] }> = []\n let current: { id: string; lines: string[] } | undefined\n for (const line of sectionLines) {\n const heading = MODE_SUBHEADING_RE.exec(line)\n if (heading) {\n const id = heading[1]!.trim()\n if (!id) {\n throw new Error(\"AGENT.md '## Modes': a '### ' subsection has no mode id.\")\n }\n current = { id, lines: [] }\n subsections.push(current)\n } else if (current) {\n current.lines.push(line)\n }\n }\n if (subsections.length === 0) {\n throw new Error(\n \"AGENT.md declares a '## Modes' section but no '### <mode-id>' subsections were found — \" +\n \"each mode needs its own '### <id>' heading.\",\n )\n }\n\n const seenIds = new Set<string>()\n const modes: AgentControllerMode[] = []\n let explicitDefaultId: string | undefined\n\n for (const { id, lines: bodyLines } of subsections) {\n if (seenIds.has(id)) {\n throw new Error(`AGENT.md '## Modes': duplicate mode id '${id}'.`)\n }\n seenIds.add(id)\n\n let tools: string[] | undefined\n let transitionsTo: string | undefined\n let isDefault = false\n let bodyStart = 0\n\n for (; bodyStart < bodyLines.length; bodyStart++) {\n const line = bodyLines[bodyStart]!.trim()\n if (line === \"\") continue\n const toolsMatch = /^tools:\\s*(.*)$/i.exec(line)\n const transitionsMatch = /^transitions_to:\\s*(.*)$/i.exec(line)\n const defaultMatch = /^default:\\s*(true|false)\\s*$/i.exec(line)\n if (toolsMatch) {\n tools = toolsMatch[1]!\n .split(\",\")\n .map((t) => t.trim())\n .filter(Boolean)\n } else if (transitionsMatch) {\n transitionsTo = transitionsMatch[1]!.trim() || undefined\n } else if (defaultMatch) {\n isDefault = defaultMatch[1]!.toLowerCase() === \"true\"\n } else {\n break // first non-key line starts the instructions body\n }\n }\n const instructions = bodyLines.slice(bodyStart).join(\"\\n\").trim()\n\n if (isDefault) {\n if (explicitDefaultId) {\n throw new Error(\n `AGENT.md '## Modes': more than one mode flagged 'default: true' ` +\n `('${explicitDefaultId}', '${id}').`,\n )\n }\n explicitDefaultId = id\n }\n\n modes.push({\n id,\n name: titleCase(id),\n ...(instructions ? { instructions } : {}),\n ...(tools ? { availableTools: tools } : {}),\n ...(transitionsTo ? { transitionsTo } : {}),\n })\n }\n\n const defaultModeId = explicitDefaultId ?? modes[0]!.id\n const defaultMode = modes.find((m) => m.id === defaultModeId)!\n defaultMode.metadata = { ...defaultMode.metadata, default: true }\n\n return { modes, defaultModeId }\n}\n\n/**\n * Resolve the mode set for an AGENT.md body: its own `## Modes` section when\n * present, else {@link DEFAULT_MODES}.\n */\nexport function resolveModes(body: string): ParsedModes {\n return (\n parseModesFromAgentMd(body) ?? {\n modes: [...DEFAULT_MODES],\n defaultModeId: DEFAULT_MODE_ID,\n }\n )\n}\n","/**\n * Builds a runnable Mastra `AgentController` from an AIP-42 AGENT.md — either\n * a caller's file or a zero-config built-in default — wiring the model, the\n * markdown body as instructions, the SQLite memory/storage, and the workspace\n * toolset, then wrapping the built `Agent` as the controller's shared backing\n * agent. The ACP host drives controller sessions, not the raw agent stream.\n */\n\nimport { readFile } from \"node:fs/promises\"\nimport { agentFromManifest, parseAgentManifest } from \"@agentproto/agent\"\nimport { buildMastraAgent } from \"@agentproto/mastra\"\nimport type { MastraToolLike } from \"@agentproto/mastra\"\nimport { ProviderHistoryCompat } from \"@mastra/core/processors\"\nimport { AgentController } from \"@mastra/core/agent-controller\"\nimport type {\n AgentControllerConfig,\n AgentControllerSubagent,\n BuiltinToolId,\n PermissionRules,\n} from \"@mastra/core/agent-controller\"\nimport { Workspace } from \"@mastra/core/workspace\"\nimport type { Agent } from \"@mastra/core/agent\"\nimport { createNotificationInboxTool } from \"@mastra/core/notifications\"\nimport { DaemonClient } from \"./daemon-client.js\"\nimport { makeDaemonTools } from \"./daemon-tools.js\"\nimport { AgentprotoSignalProvider } from \"./signal-provider.js\"\nimport { DaemonStateEmitter } from \"./state-signals.js\"\nimport type { MastraMemoryLike } from \"./memory.js\"\nimport { buildSqliteMemory, buildSqliteStore } from \"./memory.js\"\nimport { resolveMastraModel } from \"./model-resolver.js\"\nimport { DEFAULT_PERMISSION_RULES, toolCategoryResolver } from \"./tool-categories.js\"\nimport { resolveModes } from \"./modes.js\"\nimport { makeUnwiredToolStub, makeWorkspaceTools } from \"./workspace-tools.js\"\n\n/** Cheap OpenRouter coder by default — this is the budget first-party arm,\n * same rationale as the hermes default. Override with --model / env. */\nexport const DEFAULT_MODEL = \"openrouter/z-ai/glm-5.2\"\n\n/** Tool ids the built-in default agent is granted (the workspace toolset). */\nexport const DEFAULT_TOOL_IDS = [\n \"list_dir\",\n \"read_file\",\n \"write_file\",\n \"edit_file\",\n \"run_command\",\n] as const\n\nexport interface AgentSourceOptions {\n /** Path to an AGENT.md. When omitted, the built-in default agent is used. */\n agentFile?: string\n /** Model id for the default agent (ignored when agentFile carries a model). */\n model?: string\n /** Workspace dir the tools are confined to. Defaults to `process.cwd()`. */\n cwd?: string\n /** When false, the `run_command` tool is withheld. Default true. */\n allowExec?: boolean\n /**\n * Extra tools merged over the built-in workspace toolset (extra wins on id\n * collision) — programmatic-only, for a host embedding this agent that\n * wants to grant tools the built-in toolset doesn't cover. No CLI flag.\n */\n extraTools?: Record<string, MastraToolLike>\n /**\n * `false` runs WP-1 parity: a single mode, no tool approvals, yolo\n * execution — exactly the old raw-stream behavior. Anything else (or\n * omitted) runs the plan/build/review modes with real tool approvals\n * (WP-3 default). The `AGENTPROTO_MASTRA_NO_MODES` env var is the\n * spawn-time equivalent of passing `false` here, for hosts that can't pass\n * this option directly (e.g. the CLI, which owns no `--no-modes` flag yet\n * — see this WP's report).\n */\n modes?: false | \"default\"\n}\n\n/** Truthy env-var check matching this adapter's existing `AGENTPROTO_MASTRA_NO_EXEC` convention. */\nfunction envFlag(value: string | undefined): boolean {\n return Boolean(value)\n}\n\n/** The built-in AGENT.md used when no file is supplied. */\nexport function defaultAgentManifest(model: string): string {\n return [\n \"---\",\n \"schema: agent/v1\",\n \"id: mastra-agent\",\n \"description: A first-party agentproto agent powered by Mastra.\",\n `model: ${model}`,\n \"version: 0.1.0\",\n \"tools:\",\n ...DEFAULT_TOOL_IDS.map((id) => ` - ${id}`),\n \"memory:\",\n \" scope: per-conversation\",\n \" retention_turns: 20\",\n \"---\",\n \"\",\n \"You are a capable, concise coding agent operating inside a workspace \",\n \"directory. You can list, read, write, and edit files and run shell \",\n \"commands there using your tools. Do exactly what the user asks — when \",\n \"asked to reply with an exact string, reply with only that string.\",\n \"\",\n ].join(\"\\n\")\n}\n\n/** Pull the id string out of an AIP-42 tool ref (string | { ref }). */\nfunction toolRefId(ref: unknown): string | undefined {\n if (typeof ref === \"string\") return ref\n if (ref && typeof ref === \"object\" && typeof (ref as { ref?: unknown }).ref === \"string\") {\n return (ref as { ref: string }).ref\n }\n return undefined\n}\n\n/** Resolve the AGENT.md source for these options (file or built-in default). */\nexport async function resolveAgentSource(\n opts: AgentSourceOptions = {},\n): Promise<string> {\n if (opts.agentFile) return readFile(opts.agentFile, \"utf8\")\n return defaultAgentManifest(opts.model ?? DEFAULT_MODEL)\n}\n\n/** Every AgentController built-in tool id — WP-1 parity mode disables them ALL\n * so the controller adds nothing the raw-stream agent didn't have. Modes-on\n * (the default, WP-3/WP-5) re-enables `submit_plan` and `subagent` — see\n * `makeAgentFactory`. */\nexport const DISABLED_BUILTIN_TOOL_IDS: readonly BuiltinToolId[] = [\n \"ask_user\",\n \"submit_plan\",\n \"task_write\",\n \"task_update\",\n \"task_complete\",\n \"task_check\",\n \"subagent\",\n] as const\n\n/** Built-in ids modes-on re-enables out of {@link DISABLED_BUILTIN_TOOL_IDS} —\n * `submit_plan` (WP-3's plan-approval gate) and `subagent` (WP-5's in-process\n * subagent spawner, backing {@link REVIEWER_SUBAGENT}). */\nconst REENABLED_BUILTIN_TOOL_IDS: readonly BuiltinToolId[] = [\"submit_plan\", \"subagent\"]\n\n/** Read-only tool ids granted to the reviewer subagent — a reviewer that\n * can only read code/diffs/tests and run the suite, never edit. `read_diff`\n * and `run_tests` only exist in the controller's `tools` set when\n * `allowExec` is true (see `makeWorkspaceTools`); AgentController silently\n * has nothing to grant for an id absent from `tools` when exec is off, so\n * the reviewer's toolset shrinks to `list_dir`/`read_file` in that case. */\nconst REVIEWER_ALLOWED_TOOL_IDS: readonly string[] = [\"read_file\", \"read_diff\", \"run_tests\", \"list_dir\"]\n\n/**\n * In-process code-review subagent (WP-5), spawned via the `subagent` built-in\n * tool. `forked: true` clones the parent thread onto the subagent run so the\n * reviewer sees the same conversation context (what was asked, what changed,\n * why) instead of reviewing a diff cold — the plan's own rationale for this\n * subagent. Forked runs require the controller's `memory` to be configured;\n * that's true for the built-in default agent (its manifest declares a\n * `memory:` section — see `defaultAgentManifest`) but is only as true as\n * whatever AGENT.md a caller supplies via `agentFile` — an AGENT.md with no\n * `memory:` section leaves `config.memory` unset (see `makeAgentFactory`)\n * and a forked reviewer run would then have nothing to fork.\n */\nconst REVIEWER_SUBAGENT: AgentControllerSubagent = {\n id: \"reviewer\",\n name: \"Code reviewer\",\n description: \"Reviews changes for correctness and reports findings.\",\n instructions:\n \"You are reviewing a change for correctness. Read the diff (`read_diff`) and the files it \" +\n \"touches, run the test suite (`run_tests`) if one exists, and report concrete findings: bugs, \" +\n \"missed edge cases, and test gaps. You cannot edit files — report findings back to the caller \" +\n \"instead of trying to fix them yourself.\",\n allowedControllerTools: [...REVIEWER_ALLOWED_TOOL_IDS],\n forked: true,\n}\n\n/** Session state the controller carries for us (see `initialState` below). */\ninterface AdapterControllerState {\n /** WP-1 parity mode only: skips tool approvals entirely. Unset when modes are on. */\n yolo?: boolean\n /** Modes-on default: seeded from {@link DEFAULT_PERMISSION_RULES}, read by `session.permissions`. */\n permissionRules?: PermissionRules\n}\n\n/**\n * A lazy factory: parses the AGENT.md, builds the Mastra agent with the model\n * resolver, SQLite memory, the markdown body as instructions, and the\n * workspace toolset (matched by tool id), then wraps it in an\n * `AgentController` the ACP host creates sessions on.\n */\nexport function makeAgentFactory(\n opts: AgentSourceOptions = {},\n): () => Promise<{ controller: AgentController<AdapterControllerState> }> {\n return async () => {\n const source = await resolveAgentSource(opts)\n const { frontmatter, body } = parseAgentManifest(source)\n const handle = agentFromManifest({ frontmatter, body })\n\n const cwd = opts.cwd ?? process.cwd()\n const workspaceTools = makeWorkspaceTools({\n cwd,\n allowExec: opts.allowExec,\n extraTools: opts.extraTools,\n })\n\n // One LibSQL store shared between the agent's Memory and the controller's\n // storage — two stores on one SQLite file would contend on writes.\n const store = buildSqliteStore()\n let memory: MastraMemoryLike | undefined\n\n const historyCompat = new ProviderHistoryCompat({\n additionalRules: [{\n name: \"strip-trailing-reasoning-from-assistant\",\n applyToPrompt({ prompt }) {\n let mutated = false\n const next = prompt.map((message) => {\n if (message.role !== \"assistant\" || !Array.isArray(message.content)) return message\n const content = message.content as Array<{ type: string }>\n const last = content[content.length - 1]\n if (!last || last.type !== \"reasoning\") return message\n const filtered = content.filter((p) => p.type !== \"reasoning\")\n mutated = true\n return { ...message, content: filtered.length > 0 ? filtered : [{ type: \"text\" as const, text: \"\" }] }\n })\n return mutated ? (next as typeof prompt) : undefined\n },\n }],\n })\n\n const { agent } = await buildMastraAgent(handle, {\n inputProcessors: [historyCompat],\n resolveModel: (ref) => resolveMastraModel(ref),\n // Match each declared tool ref against the workspace toolset by id. A\n // ref with no matching executor still resolves — to a stub that fails\n // fast and clearly on call — rather than being dropped: a dropped ref\n // leaves the model unable to see it at all, and (if the model still\n // tries the name from AGENT.md prose) surfaces as an opaque provider\n // NoSuchToolError this adapter's ACP layer silently swallows (see\n // tool-call-map.ts), which is how a declared-but-unwired tool used to\n // hang a turn with zero recorded tool calls instead of failing fast.\n resolveTool: (ref) => {\n const id = toolRefId(ref)\n if (!id) return undefined\n const tool = workspaceTools[id]\n if (tool) return { name: id, tool }\n console.warn(\n `[@agentproto/adapter-mastra-agent] agent '${handle.id}' declares tool '${id}' but no ` +\n `executor is wired for it in this adapter's workspace toolset — calls to it will fail ` +\n `immediately instead of hanging. Wire it in workspace-tools.ts or pass it via extraTools.`,\n )\n return { name: id, tool: makeUnwiredToolStub(id) }\n },\n buildMemory: (config) => (memory = buildSqliteMemory(config, process.env, store)),\n // The markdown body is the agent's primary system prompt (AIP-42).\n body,\n })\n\n // `false` (or the env var) selects WP-1 parity; anything else keeps the\n // WP-3 default of real plan/build/review modes with tool approvals.\n const modesEnabled = opts.modes !== false && !envFlag(process.env.AGENTPROTO_MASTRA_NO_MODES)\n const { modes, defaultModeId } = modesEnabled\n ? resolveModes(body)\n : { modes: [{ id: \"main\", metadata: { default: true } }], defaultModeId: \"main\" }\n\n // Daemon sub-agent-spawning tools (WP-5) and the daemon signal provider\n // (WP-6) are additive, modes-on only — parity mode stays exactly the\n // WP-1 raw-stream toolset. One `DaemonClient` is shared between them\n // (cheap to build: no network call happens until a tool executes or a\n // watch exists, and discovery runs lazily).\n let tools = workspaceTools\n if (modesEnabled) {\n const daemonClient = new DaemonClient({ cwd })\n tools = { ...workspaceTools, ...makeDaemonTools({ client: daemonClient }) }\n\n // WP-6: attach the AgentprotoSignalProvider MANUALLY. `buildMastraAgent`\n // owns the `new Agent(...)` call and has no `signals` passthrough, so we\n // replicate here exactly what `Agent`'s constructor does for\n // `config.signals` (see @mastra/core dist, agent ctor):\n // 1. `provider.connect(this)` — done below.\n // 2. `provider.startPolling()` — done below (a no-op timer until a\n // subscription exists; the base class skips poll() with zero subs,\n // so an unwatched provider never even attempts daemon discovery —\n // no daemon just means the first real poll warns once and the\n // provider stays dormant).\n // 3. `provider.start?.()` — our provider defines none.\n // 4. merge `getInputProcessors()`/`getOutputProcessors()` — our\n // provider exposes none, nothing to replicate.\n // 5. merge `getTools()` into the agent's toolset — replicated by\n // merging into the CONTROLLER `tools` below instead, which is the\n // surface controller sessions actually execute against (agent-level\n // and controller-level tools overlap onto the same executors here,\n // same as the workspace toolset).\n // One thing the constructor path would ALSO have done that we don't:\n // `agent.__registerMastra` forwards the Mastra instance to providers in\n // `config.signals`; a manually-connected provider never receives it.\n // Ours never reads `this.mastra`, so nothing is lost.\n //\n // WP-7: the provider also carries the daemon state-signal emitter —\n // each poll cycle pushes a session-tree + git-status snapshot/delta\n // (cacheKey-deduped) to every thread watching at least one session.\n const signalProvider = new AgentprotoSignalProvider({\n client: daemonClient,\n stateEmitter: new DaemonStateEmitter({ client: daemonClient, cwd }),\n })\n signalProvider.connect(agent as unknown as Agent)\n signalProvider.startPolling()\n tools = { ...tools, ...signalProvider.getTools() }\n\n // WP-7: notification inbox — lets the agent list/read/dismiss the\n // notifications the signal provider (and any future provider) files.\n // Backed by the SAME LibSQL store as memory + controller storage: its\n // `notifications` domain is what `agent.sendNotificationSignal` writes\n // through once `controller.init()` registers the agent on the internal\n // Mastra (`mastra.addAgent(agent)`), so the tool reads exactly what\n // `notify` wrote. `getStore` is a plain domain lookup (safe pre-init;\n // table creation happens in `controller.init()` → `storage.init()`).\n const notificationsStorage = await store.getStore(\"notifications\")\n if (notificationsStorage) {\n tools = {\n ...tools,\n \"notification-inbox\": createNotificationInboxTool({ storage: notificationsStorage }),\n }\n }\n }\n\n const config: AgentControllerConfig<AdapterControllerState> = {\n id: \"agentproto-native\",\n // The AGENT.md-built agent backs every mode; parity mode has exactly\n // one mode and layers no mode instructions, so runs behave as the raw\n // agent did.\n agent: agent as AgentControllerConfig[\"agent\"],\n modes,\n defaultModeId,\n // Thread rows + per-thread settings persist to the same SQLite file the\n // agent's Memory writes messages to.\n storage: store,\n // Our hardened workspace toolset (+ daemon tools, modes-on) stays the\n // tool surface. The backing agent already carries the AGENT.md-declared\n // subset; controller-level tools are an additive toolset, so ids\n // overlap onto the same executors.\n tools: tools as AgentControllerConfig[\"tools\"],\n // Parity mode disables every built-in controller tool and skips tool\n // approvals entirely (`yolo: true` keeps `requireToolApproval` off so\n // tools execute pass-through exactly as the raw stream did). Modes-on\n // re-enables `submit_plan` (the plan mode's approval gate) and\n // `subagent` (WP-5's in-process reviewer, see `REVIEWER_SUBAGENT`), and\n // seeds real per-category tool-approval policy instead.\n disableBuiltinTools: modesEnabled\n ? DISABLED_BUILTIN_TOOL_IDS.filter((id) => !REENABLED_BUILTIN_TOOL_IDS.includes(id))\n : [...DISABLED_BUILTIN_TOOL_IDS],\n toolCategoryResolver,\n initialState: modesEnabled ? { permissionRules: DEFAULT_PERMISSION_RULES } : { yolo: true },\n // `Session` construction hard-requires a `Workspace` instance\n // (`createSession` throws \"A session requires a valid workspace\n // instance\" without one) — but a *filesystem/sandbox*-backed Workspace\n // makes Mastra auto-inject its own `mastra_workspace_*` file/exec tools\n // into every run, duplicating our own hardened workspace toolset. A\n // skills-only Workspace (no filesystem, no sandbox) satisfies the\n // former without triggering the latter: `createWorkspaceTools` only\n // adds filesystem/sandbox tools, so this config contributes none.\n workspace: new Workspace({ skills: () => [] }),\n }\n if (memory) config.memory = memory\n if (modesEnabled) config.subagents = [REVIEWER_SUBAGENT]\n\n return { controller: new AgentController<AdapterControllerState>(config) }\n }\n}\n","/**\n * Pure mapping from Mastra `AgentController` session events to AIP-44 ACP\n * `session/update` payloads. Kept dependency-light (type-only imports) and\n * IO-free so it is straightforward to unit-test; the ACP host (acp-host.ts)\n * owns the wire and just forwards whatever this returns.\n *\n * A controller session (`session.subscribe`) emits `AgentControllerEvent`s.\n * We surface three kinds:\n * - `message_update` → ACP `agent_message_chunk` (assistant prose, as a delta)\n * - `tool_start` → ACP `tool_call` (a tool started, status in_progress)\n * - `tool_end` → ACP `tool_call_update` (that tool finished: completed/failed)\n * Everything else (message_start/end, tool_input_*, usage, display state,\n * agent_start/end, error, …) has no ACP surface here — `error` and `agent_end`\n * are read by the host to pick the turn's stop reason, not mapped to updates.\n *\n * `message_update` carries the FULL message accumulated so far (Mastra's run\n * engine re-emits the whole `MastraDBMessage` on every text delta), while ACP\n * `agent_message_chunk` is a delta wire. The mapper is therefore a stateful\n * factory: it remembers how much of each message's text it has already\n * relayed and emits only the new suffix. Create one mapper per prompt turn.\n *\n * `tool_end` covers BOTH a successful tool result and a failed one (a tool's\n * own `execute` throwing, or the SDK failing to resolve the call) — the old\n * raw-stream `tool-result`/`tool-error` split collapses into `isError`.\n * Dropping failures used to leave the matching `tool_call` stuck\n * \"in_progress\" forever on the ACP wire, so failed calls map to a `failed`\n * update carrying the error text.\n */\n\nimport type { SessionUpdate, ToolKind } from \"@agentclientprotocol/sdk\"\nimport type { AgentControllerEvent } from \"@mastra/core/agent-controller\"\n\n/** Map a workspace tool id to the ACP {@link ToolKind} that drives client\n * icon/UI treatment. Unknown ids fall back to \"other\". */\nexport function toolKindFor(toolName: string): ToolKind {\n switch (toolName) {\n case \"read_file\":\n case \"list_dir\":\n return \"read\"\n case \"write_file\":\n case \"edit_file\":\n return \"edit\"\n case \"run_command\":\n return \"execute\"\n default:\n return \"other\"\n }\n}\n\n/** A short, human-readable title for a tool call, e.g. `run_command: ls -la`\n * or `read_file: src/index.ts`. Falls back to the bare tool name. */\nexport function toolCallTitle(toolName: string, args: unknown): string {\n if (args && typeof args === \"object\") {\n const { command, path, file } = args as Record<string, unknown>\n const hint =\n (typeof command === \"string\" && command) ||\n (typeof path === \"string\" && path) ||\n (typeof file === \"string\" && file) ||\n \"\"\n if (hint) return `${toolName}: ${hint}`\n }\n return toolName\n}\n\n/** Render a failed tool result (an `Error`, a string, or an arbitrary\n * provider error shape) as a single human-readable line. */\nfunction errorMessage(error: unknown): string {\n if (error instanceof Error) return error.message\n if (typeof error === \"string\") return error\n try {\n return JSON.stringify(error)\n } catch {\n return String(error)\n }\n}\n\n/** Concatenate a message's plain-text parts (assistant prose; reasoning and\n * tool-invocation parts are not ACP message text). Also used by the host's\n * `session/load` replay to render prior thread messages. */\nexport function messageText(message: { content?: { parts?: unknown[] } }): string {\n const parts = message.content?.parts\n if (!Array.isArray(parts)) return \"\"\n let text = \"\"\n for (const part of parts) {\n if (\n part &&\n typeof part === \"object\" &&\n (part as { type?: unknown }).type === \"text\" &&\n typeof (part as { text?: unknown }).text === \"string\"\n ) {\n text += (part as { text: string }).text\n }\n }\n return text\n}\n\n/**\n * Create a stateful event mapper for one prompt turn: translates each\n * controller event into an ACP `session/update` payload, or `null` when the\n * event has no ACP surface (or carries no new text). The ACP host wraps each\n * result with the `sessionId`.\n */\nexport function createEventMapper(): (\n event: AgentControllerEvent,\n) => SessionUpdate | null {\n // message id → how many chars of its text we have already relayed.\n const relayed = new Map<string, number>()\n\n return (event) => {\n switch (event.type) {\n case \"message_update\": {\n if (event.message.role !== \"assistant\") return null\n const text = messageText(event.message)\n const seen = relayed.get(event.message.id) ?? 0\n if (text.length <= seen) return null\n relayed.set(event.message.id, text.length)\n return {\n sessionUpdate: \"agent_message_chunk\",\n content: { type: \"text\", text: text.slice(seen) },\n }\n }\n case \"tool_start\": {\n if (!event.toolCallId) return null\n const toolName = event.toolName || \"tool\"\n return {\n sessionUpdate: \"tool_call\",\n toolCallId: event.toolCallId,\n title: toolCallTitle(toolName, event.args),\n kind: toolKindFor(toolName),\n status: \"in_progress\",\n rawInput: event.args,\n }\n }\n case \"tool_end\": {\n if (!event.toolCallId) return null\n return {\n sessionUpdate: \"tool_call_update\",\n toolCallId: event.toolCallId,\n status: event.isError ? \"failed\" : \"completed\",\n rawOutput: event.isError\n ? { error: errorMessage(event.result) }\n : event.result,\n }\n }\n default:\n return null\n }\n }\n}\n","/**\n * WP2 — the agent side of AIP-44 ACP, backed by a Mastra `AgentController`.\n *\n * Implements the `@agentclientprotocol/sdk` `Agent` interface: handles the\n * session lifecycle and, on `session/prompt`, drives a controller `Session`'s\n * `sendMessage()` — relaying its subscription events as ACP `session/update`s\n * (text deltas as `agent_message_chunk`, tool activity as `tool_call` /\n * `tool_call_update`), exactly as an IDE/host expects from codex or\n * claude-code.\n *\n * Beyond the prompt loop, this file bridges the rest of the session surface:\n * - `session/load` — reconnect to the Mastra thread keyed by the ACP session\n * id and replay its text history as user/agent message chunks\n * - `tool_approval_required` / `tool_suspended` — parked controller runs\n * surface as `session/request_permission` round-trips\n * - `session/set_config_option` (model) and `session/set_mode` — applied via\n * `session.model.switch` / `session.mode.switch`, with `model_changed` /\n * `mode_changed` relayed back as config/mode session updates\n * - image / audio / embedded-resource prompt blocks — passed to\n * `sendMessage` as file attachments\n *\n * No Mastra-specific protocol knowledge leaks past this file; everything above\n * is the standard ACP wire, so the daemon spawns this like any other arm.\n */\n\nimport type {\n AgentSideConnection,\n Agent as AcpAgent,\n AuthenticateRequest,\n CancelNotification,\n InitializeRequest,\n InitializeResponse,\n LoadSessionRequest,\n LoadSessionResponse,\n NewSessionRequest,\n NewSessionResponse,\n PermissionOption,\n PromptRequest,\n PromptResponse,\n SessionConfigOption,\n SetSessionConfigOptionRequest,\n SetSessionConfigOptionResponse,\n SetSessionModeRequest,\n} from \"@agentclientprotocol/sdk\"\nimport { PROTOCOL_VERSION } from \"@agentclientprotocol/sdk\"\nimport type { AgentControllerEvent } from \"@mastra/core/agent-controller\"\nimport {\n createEventMapper,\n messageText,\n toolCallTitle,\n toolKindFor,\n} from \"./tool-call-map.js\"\n\n/** A prompt attachment in the shape `Session.sendMessage` accepts: text\n * attachments carry raw text, binary ones base64 (Mastra inlines `text/*` /\n * JSON as fenced code and forwards the rest as model file parts). */\nexport interface PromptFile {\n data: string\n mediaType: string\n filename?: string\n}\n\n/** The slice of a thread message that history replay reads (text parts). */\nexport interface ThreadMessageLike {\n role: string\n content?: { parts?: unknown[] }\n}\n\n/** The slice of a controller `Session` this host drives. Typed structurally so\n * tests can script one and we don't couple to a specific @mastra/core\n * version's `Session` generics. */\nexport interface ControllerSessionLike {\n subscribe(\n listener: (event: AgentControllerEvent) => void | Promise<void>,\n ): () => void\n sendMessage(input: { content: string; files?: PromptFile[] }): Promise<void>\n /** Abort the active run and send in one step — the interrupt semantics a\n * mid-turn prompt maps to. */\n steer(input: { content: string }): Promise<void>\n abort(): void\n respondToToolApproval(input: {\n decision: \"approve\" | \"decline\" | \"always_allow_category\"\n toolCallId?: string\n declineContext?: { reason?: string; message?: string }\n }): void\n respondToToolSuspension(input: {\n resumeData: unknown\n toolCallId?: string\n }): Promise<void>\n model: {\n /** The currently-selected model id ('' when none selected yet). */\n get(): string\n switch(input: { modelId: string }): Promise<void>\n }\n mode: {\n switch(input: { modeId: string }): Promise<void>\n }\n thread: {\n listMessages(input: {\n threadId: string\n limit?: number\n }): Promise<ThreadMessageLike[]>\n }\n}\n\n/** The slice of an `AgentController` this host drives (structural, as above).\n * `createSession` keys on (resourceId, scope) — one ACP session maps to one\n * controller session via a unique scope, with the thread pinned to the ACP\n * session id so memory recall is scoped exactly as before. */\nexport interface ControllerLike {\n init(): Promise<void>\n createSession(opts: {\n resourceId?: string\n scope?: string\n threadId?: string\n }): Promise<ControllerSessionLike>\n}\n\n/** Lazily builds the controller (so model/key/AGENT.md errors surface on the\n * first prompt with a clear message, not at process spawn or session/new). */\nexport type ControllerFactory = () => Promise<{ controller: ControllerLike }>\n\n/** The model catalog reported through the `model` session config option.\n * Mirrors `models.allowed` in the manifest (index.ts) — keep in sync. Any\n * Mastra-routable id is still accepted as a value; this is just what the\n * client's selector lists. */\nexport const DEFAULT_MODEL_CATALOG: ReadonlyArray<{ id: string; name?: string }> = [\n { id: \"openrouter/z-ai/glm-5.2\" },\n { id: \"openrouter/deepseek/deepseek-v4-pro\" },\n { id: \"openai/gpt-5\" },\n]\n\nconst APPROVAL_OPTIONS: PermissionOption[] = [\n { optionId: \"approve\", name: \"Approve\", kind: \"allow_once\" },\n {\n optionId: \"always_allow_category\",\n name: \"Always allow this category\",\n kind: \"allow_always\",\n },\n { optionId: \"decline\", name: \"Decline\", kind: \"reject_once\" },\n]\n\nconst SUSPENSION_OPTIONS: PermissionOption[] = [\n { optionId: \"approve\", name: \"Continue\", kind: \"allow_once\" },\n { optionId: \"decline\", name: \"Cancel\", kind: \"reject_once\" },\n]\n\n/** `_meta` keys used to carry Mastra suspension payloads over the ACP\n * permission round-trip (ACP has no first-class tool-suspension surface). */\nconst META_SUSPEND_PAYLOAD = \"mastra-agent/suspendPayload\"\nconst META_RESUME_SCHEMA = \"mastra-agent/resumeSchema\"\nconst META_RESUME_DATA = \"mastra-agent/resumeData\"\n\ninterface SessionState {\n /** The controller session, created lazily on the first prompt. */\n session: ControllerSessionLike | null\n /** The in-flight prompt turn, if any. Turn-scoped (not session-scoped) so a\n * superseding prompt cancelling this one can't clobber its own state. */\n turn: { cancelled: boolean } | null\n /** Model/mode chosen via ACP before the controller session exists (the\n * daemon applies config right after session/new); applied on creation. */\n pendingModelId: string | null\n pendingModeId: string | null\n /** Suspended tool calls with an ACP permission request in flight, so a\n * `tool_suspension_cancelled` can void the eventual client answer. */\n suspensions: Map<string, { cancelled: boolean }>\n}\n\nfunction emptySessionState(): SessionState {\n return {\n session: null,\n turn: null,\n pendingModelId: null,\n pendingModeId: null,\n suspensions: new Map(),\n }\n}\n\n/** Pull the user's text out of an ACP prompt (its `text` content blocks). */\nexport function promptText(params: PromptRequest): string {\n return promptContent(params).text\n}\n\n/** File name hint from a resource URI: its last path segment, if any. */\nfunction filenameOf(uri: unknown): string | undefined {\n if (typeof uri !== \"string\" || !uri) return undefined\n return uri.split(\"/\").pop() || undefined\n}\n\n/** Coerce an embedded *text* resource's mime type to one Mastra inlines as\n * fenced text (`text/*` or JSON) — its data is raw text, so letting e.g.\n * `application/x-typescript` through would ship raw text as a base64 file\n * part. */\nfunction textMediaType(mimeType: string | null | undefined): string {\n if (mimeType && (mimeType.startsWith(\"text/\") || mimeType === \"application/json\")) {\n return mimeType\n }\n return \"text/plain\"\n}\n\n/**\n * Split an ACP prompt into the user's text (its `text` blocks, exactly as\n * {@link promptText} always did) and file attachments: `image`/`audio` blocks\n * (base64 + mime type) and embedded `resource` blocks (text or blob contents).\n * `resource_link` blocks carry no contents to attach — hosts inline referenced\n * context as `resource` blocks when `embeddedContext` is on — so they are\n * skipped, as before.\n */\nexport function promptContent(params: PromptRequest): {\n text: string\n files: PromptFile[]\n} {\n const blocks = Array.isArray(params.prompt) ? params.prompt : []\n let text = \"\"\n const files: PromptFile[] = []\n for (const block of blocks) {\n if (!block || typeof block !== \"object\") continue\n switch (block.type) {\n case \"text\":\n if (typeof block.text === \"string\") text += block.text\n break\n case \"image\": {\n const filename = filenameOf(block.uri)\n files.push({\n data: block.data,\n mediaType: block.mimeType,\n ...(filename ? { filename } : {}),\n })\n break\n }\n case \"audio\":\n files.push({ data: block.data, mediaType: block.mimeType })\n break\n case \"resource\": {\n const resource = block.resource\n if (!resource || typeof resource !== \"object\") break\n const filename = filenameOf(resource.uri)\n if (\"text\" in resource && typeof resource.text === \"string\") {\n files.push({\n data: resource.text,\n mediaType: textMediaType(resource.mimeType),\n ...(filename ? { filename } : {}),\n })\n } else if (\"blob\" in resource && typeof resource.blob === \"string\") {\n files.push({\n data: resource.blob,\n mediaType: resource.mimeType || \"application/octet-stream\",\n ...(filename ? { filename } : {}),\n })\n }\n break\n }\n default:\n break\n }\n }\n return { text: text.trim(), files }\n}\n\n/** Extract a useful message from an error, digging into `.cause` when the\n * top-level message is generic (e.g. a bare `new Error()` wrapping a real\n * failure), and appending the first stack frames for traceability. */\nexport function describeError(err: unknown): string {\n if (!(err instanceof Error)) return String(err)\n const msg = err.message || undefined\n const causeMsg = err.cause instanceof Error ? err.cause.message : undefined\n const detail =\n msg && msg !== \"Error\" ? msg : causeMsg || msg || \"unknown error\"\n const frames = err.stack\n ?.split(\"\\n\")\n .slice(1, 3)\n .map((l) => l.trim())\n .filter(Boolean)\n return frames?.length ? `${detail} [${frames.join(\" ← \")}]` : detail\n}\n\nexport class MastraAcpAgent implements AcpAgent {\n readonly #conn: AgentSideConnection\n readonly #buildController: ControllerFactory\n readonly #resource: string\n readonly #models: ReadonlyArray<{ id: string; name?: string }>\n readonly #sessions = new Map<string, SessionState>()\n #controller: ControllerLike | null = null\n\n constructor(\n conn: AgentSideConnection,\n buildController: ControllerFactory,\n resource = \"mastra-agent\",\n models: ReadonlyArray<{ id: string; name?: string }> = DEFAULT_MODEL_CATALOG,\n ) {\n this.#conn = conn\n this.#buildController = buildController\n // `resource` groups a user's threads in Mastra memory; one per agent here.\n this.#resource = resource\n this.#models = models\n }\n\n async initialize(_params: InitializeRequest): Promise<InitializeResponse> {\n return {\n protocolVersion: PROTOCOL_VERSION,\n agentCapabilities: {\n // session/load reconnects the Mastra thread and replays its history.\n loadSession: true,\n promptCapabilities: {\n image: true,\n audio: true,\n embeddedContext: true,\n },\n },\n }\n }\n\n async authenticate(\n _params: AuthenticateRequest,\n ): Promise<Record<string, never>> {\n // The provider key is read from the spawn env by the model gateway — no\n // ACP-level auth handshake needed.\n return {}\n }\n\n async newSession(_params: NewSessionRequest): Promise<NewSessionResponse> {\n const sessionId = randomId()\n this.#sessions.set(sessionId, emptySessionState())\n return { sessionId }\n }\n\n /**\n * Resume an existing session: reconnect the controller session (scope +\n * thread keyed by the ACP session id — `createSession` resumes an existing\n * Mastra thread with full history) and replay the conversation to the\n * client, as the `session/load` contract requires, via `user_message_chunk`\n * / `agent_message_chunk` updates.\n *\n * Unlike `prompt`, this NEEDS the controller now (replay reads the thread),\n * so build errors surface as this request's JSON-RPC error rather than a\n * first-prompt error chunk.\n */\n async loadSession(params: LoadSessionRequest): Promise<LoadSessionResponse> {\n const sessionId = params.sessionId\n let state = this.#sessions.get(sessionId)\n if (!state) {\n state = emptySessionState()\n this.#sessions.set(sessionId, state)\n }\n const session = await this.#ensureSession(sessionId, state)\n const messages = await session.thread.listMessages({ threadId: sessionId })\n for (const message of messages) {\n // Only conversation text replays; tool traffic and system reminders have\n // no faithful ACP replay surface (chunks are the history wire).\n if (message.role !== \"user\" && message.role !== \"assistant\") continue\n const text = messageText(message)\n if (!text) continue\n await this.#conn.sessionUpdate({\n sessionId,\n update: {\n sessionUpdate:\n message.role === \"user\" ? \"user_message_chunk\" : \"agent_message_chunk\",\n content: { type: \"text\", text },\n },\n })\n }\n return { configOptions: this.#modelConfigOptions(this.#currentModelId(state)) }\n }\n\n async prompt(params: PromptRequest): Promise<PromptResponse> {\n const state = this.#sessions.get(params.sessionId)\n if (!state) throw new Error(`unknown session ${params.sessionId}`)\n\n // ACP carries no queue-vs-interrupt signal on session/prompt: a prompt\n // landing mid-turn IS the interrupt path. Mark the active turn cancelled\n // here; the actual abort happens via `steer` (abort + send in one step).\n const interrupted = state.turn\n if (interrupted) interrupted.cancelled = true\n const turn = { cancelled: false }\n state.turn = turn\n\n const { text, files } = promptContent(params)\n try {\n const session = await this.#ensureSession(params.sessionId, state)\n\n // One mapper per turn: it holds the per-message \"text already relayed\"\n // state that turns Mastra's full-message updates into ACP deltas.\n const map = createEventMapper()\n let endReason: string | undefined\n let lastError: Error | null = null\n // Updates must hit the wire in event order; the listener is synchronous\n // while sessionUpdate is not, so sends are chained.\n let relay: Promise<void> = Promise.resolve()\n\n // Mastra's Session.sendMessage may return before the run completes on\n // follow-up turns (its internal `wasActive` check can see stale stream\n // state). Track agent_end independently so we keep the subscription\n // alive until the run truly finishes.\n let resolveAgentEnd: (() => void) | undefined\n const agentEndPromise = new Promise<void>((r) => {\n resolveAgentEnd = r\n })\n\n const unsubscribe = session.subscribe((event) => {\n if (event.type === \"error\") {\n lastError = event.error\n return\n }\n if (event.type === \"agent_end\") {\n endReason = event.reason ?? \"complete\"\n resolveAgentEnd?.()\n return\n }\n if (event.type === \"tool_approval_required\") {\n // Sequence the permission request behind already-queued updates (so\n // the client has seen everything up to the gate), but don't block\n // later updates on the user's answer — the run itself is parked\n // until we respond, and `cancel` resolves it via abort().\n const tail = relay\n void tail\n .catch(() => {})\n .then(() => this.#bridgeApproval(params.sessionId, session, event))\n .catch(() => {})\n return\n }\n if (event.type === \"tool_suspended\") {\n const pending = { cancelled: false }\n state.suspensions.set(event.toolCallId, pending)\n const tail = relay\n void tail\n .catch(() => {})\n .then(() =>\n this.#bridgeSuspension(params.sessionId, session, state, event, pending),\n )\n .catch(() => {})\n return\n }\n if (event.type === \"tool_suspension_cancelled\") {\n // The SDK has no way to retract an in-flight outgoing request, so\n // the ACP permission request stays up; voiding the pending entry\n // makes its eventual answer a no-op instead.\n const pending = state.suspensions.get(event.toolCallId)\n if (pending) pending.cancelled = true\n state.suspensions.delete(event.toolCallId)\n return\n }\n const update = map(event)\n if (!update) return\n relay = relay.then(() =>\n this.#conn.sessionUpdate({ sessionId: params.sessionId, update }),\n )\n })\n try {\n // Awaits the whole run; events stream via the subscription above.\n if (interrupted) {\n if (files.length) {\n // `steer` can't carry attachments — unroll its abort+send.\n session.abort()\n await session.sendMessage({ content: text, files })\n } else {\n await session.steer({ content: text })\n }\n } else if (files.length) {\n await session.sendMessage({ content: text, files })\n } else {\n await session.sendMessage({ content: text })\n }\n // Mastra's sendMessage may resolve before agent_end on follow-up\n // turns (stale wasActive check). Keep the subscription alive until\n // the run actually finishes so we capture all events.\n if (!endReason && !lastError && !turn.cancelled) {\n await agentEndPromise\n }\n } finally {\n unsubscribe()\n // Flush queued updates; a dead connection shouldn't mask the turn's\n // real outcome (and there is nowhere left to report it anyway).\n await relay.catch(() => {})\n }\n\n if (turn.cancelled || endReason === \"aborted\") {\n return { stopReason: \"cancelled\" }\n }\n if (endReason === \"error\") {\n // `sendMessage` resolves even when the run dies (the engine reports\n // via `error` events + agent_end reason) — re-throw into the shared\n // error path so the failure surfaces exactly as before.\n throw lastError ?? new Error(\"the agent run ended with an error\")\n }\n return { stopReason: \"end_turn\" }\n } catch (err) {\n if (turn.cancelled) return { stopReason: \"cancelled\" }\n // Surface the failure to the client as a message chunk, then end the\n // turn — better UX than a bare JSON-RPC error the host may swallow.\n await this.#conn.sessionUpdate({\n sessionId: params.sessionId,\n update: {\n sessionUpdate: \"agent_message_chunk\",\n content: {\n type: \"text\",\n text: `\\n[mastra-agent error] ${describeError(err)}\\n`,\n },\n },\n })\n return { stopReason: \"refusal\" }\n } finally {\n if (state.turn === turn) state.turn = null\n }\n }\n\n async cancel(params: CancelNotification): Promise<void> {\n const state = this.#sessions.get(params.sessionId)\n if (!state) return\n if (state.turn) state.turn.cancelled = true\n // abort() also declines a parked approval gate and drops parked\n // suspensions, so a run waiting on a permission answer still finalizes.\n state.session?.abort()\n }\n\n /**\n * The host applies the operator's `model` as a `--model` spawn arg via the\n * manifest `bin_args_template`, then ALSO calls this ACP config hook (the\n * daemon's default \"config\" apply path). Runtime switches go through\n * `session.model.switch`; a choice made before the controller session\n * exists is remembered and applied on creation, preserving the invariant\n * that controller build errors surface on the first prompt.\n */\n async setSessionConfigOption(\n params: SetSessionConfigOptionRequest,\n ): Promise<SetSessionConfigOptionResponse> {\n const state = this.#sessions.get(params.sessionId)\n if (!state) throw new Error(`unknown session ${params.sessionId}`)\n if (params.configId === \"model\") {\n const modelId = String((params as { value?: unknown }).value ?? \"\")\n if (modelId) {\n if (state.session) await state.session.model.switch({ modelId })\n else state.pendingModelId = modelId\n }\n }\n // Unknown option ids are accepted and ignored; the full set reports back.\n return {\n configOptions: this.#modelConfigOptions(this.#currentModelId(state)),\n }\n }\n\n /** Switch the controller session's mode (the catalog itself is controller\n * config — WP-3). Mode-change confirmations reach the client via the\n * session-lifetime `mode_changed` → `current_mode_update` relay. */\n async setSessionMode(\n params: SetSessionModeRequest,\n ): Promise<Record<string, never>> {\n const state = this.#sessions.get(params.sessionId)\n if (!state) throw new Error(`unknown session ${params.sessionId}`)\n if (state.session) await state.session.mode.switch({ modeId: params.modeId })\n else state.pendingModeId = params.modeId\n return {}\n }\n\n /** The ACP `model` config option (a select), reflecting `currentValue`.\n * A free-form current id not in the catalog is appended so the reported\n * state stays coherent. */\n #modelConfigOptions(currentValue: string): SessionConfigOption[] {\n const options = this.#models.map((m) => ({ value: m.id, name: m.name ?? m.id }))\n if (currentValue && !options.some((o) => o.value === currentValue)) {\n options.push({ value: currentValue, name: currentValue })\n }\n return [\n {\n type: \"select\",\n id: \"model\",\n name: \"Model\",\n category: \"model\",\n description: \"Model id routed via Mastra's model gateway\",\n currentValue,\n options,\n },\n ]\n }\n\n #currentModelId(state: SessionState): string {\n const selected = state.session?.model.get() ?? \"\"\n return selected || state.pendingModelId || this.#models[0]?.id || \"\"\n }\n\n /** Relay a parked `tool_approval_required` gate as an ACP permission\n * request and feed the user's decision back to the controller session. */\n async #bridgeApproval(\n sessionId: string,\n session: ControllerSessionLike,\n event: Extract<AgentControllerEvent, { type: \"tool_approval_required\" }>,\n ): Promise<void> {\n const toolName = event.toolName || \"tool\"\n let decision: \"approve\" | \"decline\" | \"always_allow_category\" = \"decline\"\n try {\n const { outcome } = await this.#conn.requestPermission({\n sessionId,\n toolCall: {\n toolCallId: event.toolCallId,\n title: toolCallTitle(toolName, event.args),\n kind: toolKindFor(toolName),\n status: \"pending\",\n rawInput: event.args,\n },\n options: APPROVAL_OPTIONS,\n })\n if (outcome.outcome === \"selected\") {\n if (\n outcome.optionId === \"approve\" ||\n outcome.optionId === \"always_allow_category\"\n ) {\n decision = outcome.optionId\n }\n }\n // \"cancelled\": session.abort() (the cancel path) already declined the\n // parked gate; the decline below is then a no-op.\n } catch {\n // The client errored/refused the request — decline so the parked run\n // can finalize instead of hanging.\n }\n session.respondToToolApproval({ decision, toolCallId: event.toolCallId })\n }\n\n /**\n * Relay a `tool_suspended` run as an ACP permission request. ACP's answer is\n * an option pick, not free-form data, so the suspend payload and resume\n * schema ride out on the request's `_meta` and the resume data rides back on\n * the outcome's `_meta` (`mastra-agent/resumeData`) when the client supplies\n * it — else Continue/Cancel resume with `{ approved: true | false }` (the\n * shape the built-in `submit_plan` approval path consumes).\n */\n async #bridgeSuspension(\n sessionId: string,\n session: ControllerSessionLike,\n state: SessionState,\n event: Extract<AgentControllerEvent, { type: \"tool_suspended\" }>,\n pending: { cancelled: boolean },\n ): Promise<void> {\n const toolName = event.toolName || \"tool\"\n try {\n const { outcome } = await this.#conn.requestPermission({\n sessionId,\n toolCall: {\n toolCallId: event.toolCallId,\n title: toolCallTitle(toolName, event.args),\n kind: toolKindFor(toolName),\n status: \"in_progress\",\n rawInput: event.args,\n _meta: {\n [META_SUSPEND_PAYLOAD]: event.suspendPayload,\n ...(event.resumeSchema !== undefined\n ? { [META_RESUME_SCHEMA]: event.resumeSchema }\n : {}),\n },\n },\n options: SUSPENSION_OPTIONS,\n })\n if (pending.cancelled) return\n // \"cancelled\": abort() already dropped the parked suspension.\n if (outcome.outcome !== \"selected\") return\n const meta = outcome._meta as Record<string, unknown> | null | undefined\n const resumeData =\n meta && META_RESUME_DATA in meta\n ? meta[META_RESUME_DATA]\n : { approved: outcome.optionId === \"approve\" }\n await session.respondToToolSuspension({\n resumeData,\n toolCallId: event.toolCallId,\n })\n } catch {\n // Request failed at the client — resume as not-approved so the parked\n // run can finalize (unless the suspension was already cancelled).\n if (!pending.cancelled) {\n await session\n .respondToToolSuspension({\n resumeData: { approved: false },\n toolCallId: event.toolCallId,\n })\n .catch(() => {})\n }\n } finally {\n if (state.suspensions.get(event.toolCallId) === pending) {\n state.suspensions.delete(event.toolCallId)\n }\n }\n }\n\n /** Resolve this ACP session's controller session, creating it on first use.\n * Deferred to the first prompt (not session/new) on purpose: controller\n * construction parses the AGENT.md and resolves the model, and those\n * errors must keep surfacing as a first-prompt error chunk + \"refusal\",\n * never as a session/new JSON-RPC failure. (`session/load` opts into the\n * eager path — replay can't happen without the controller.) */\n async #ensureSession(\n acpSessionId: string,\n state: SessionState,\n ): Promise<ControllerSessionLike> {\n if (state.session) return state.session\n const controller = await this.#ensureController()\n // Thread = ACP session id, resource = the shared agent resource — the same\n // memory layout the raw-stream host used, so recall stays scoped to this\n // session's history. `scope` keeps concurrent ACP sessions on distinct\n // controller sessions despite the shared resourceId.\n const session = await controller.createSession({\n resourceId: this.#resource,\n scope: acpSessionId,\n threadId: acpSessionId,\n })\n // Mode/model changes can fire outside a prompt turn (idle switches, mode\n // transitions), so they relay on this session-lifetime subscription — the\n // per-turn mapper deliberately ignores them.\n session.subscribe((event) => {\n if (event.type === \"mode_changed\") {\n void this.#conn\n .sessionUpdate({\n sessionId: acpSessionId,\n update: {\n sessionUpdate: \"current_mode_update\",\n currentModeId: event.modeId,\n },\n })\n .catch(() => {})\n } else if (event.type === \"model_changed\") {\n void this.#conn\n .sessionUpdate({\n sessionId: acpSessionId,\n update: {\n sessionUpdate: \"config_option_update\",\n // Read the session's own selection: a `model_changed` scoped to\n // a non-active mode doesn't move the effective model.\n configOptions: this.#modelConfigOptions(\n session.model.get() || event.modelId,\n ),\n },\n })\n .catch(() => {})\n }\n })\n state.session = session\n // A mode/model chosen over ACP before the controller session existed\n // applies now — mode first, so an explicit model choice overrides the\n // incoming mode's per-mode model.\n if (state.pendingModeId) {\n const modeId = state.pendingModeId\n state.pendingModeId = null\n await session.mode.switch({ modeId })\n }\n if (state.pendingModelId) {\n const modelId = state.pendingModelId\n state.pendingModelId = null\n await session.model.switch({ modelId })\n }\n return session\n }\n\n async #ensureController(): Promise<ControllerLike> {\n // Memoize only on success so a transient failure retries on the next\n // prompt instead of pinning every future turn to the first error.\n if (this.#controller) return this.#controller\n const { controller } = await this.#buildController()\n await controller.init()\n this.#controller = controller\n return controller\n }\n}\n\n/** 16 random bytes as hex — matches the SDK example's session id shape. */\nfunction randomId(): string {\n const bytes = new Uint8Array(16)\n crypto.getRandomValues(bytes)\n return Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\")\n}\n","/**\n * Boots the ACP server over stdio — the standard wiring for a spawned ACP\n * agent (mirrors the @agentclientprotocol/sdk agent example): the agent writes\n * JSON-RPC to stdout and reads from stdin.\n */\n\nimport { Readable, Writable } from \"node:stream\"\nimport { AgentSideConnection, ndJsonStream } from \"@agentclientprotocol/sdk\"\nimport { MastraAcpAgent, type ControllerFactory } from \"./acp-host.js\"\n\nexport function runAcpOverStdio(\n buildController: ControllerFactory,\n): AgentSideConnection {\n // ndJsonStream(writable, readable): outgoing bytes -> stdout, incoming <- stdin.\n const toClient = Writable.toWeb(process.stdout) as WritableStream<Uint8Array>\n const fromClient = Readable.toWeb(\n process.stdin,\n ) as unknown as ReadableStream<Uint8Array>\n const stream = ndJsonStream(toClient, fromClient)\n return new AgentSideConnection(\n (conn) => new MastraAcpAgent(conn, buildController),\n stream,\n )\n}\n"]}
|
package/dist/cli.mjs
CHANGED