@mu-crew/mu 3.13.3 → 4.1.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.
Files changed (119) hide show
  1. package/AGENTS.md +73 -35
  2. package/README.md +71 -57
  3. package/dist/chunk-4ULY3ZKO.js +4482 -0
  4. package/dist/chunk-4ULY3ZKO.js.map +1 -0
  5. package/dist/chunk-7M634JMD.js +375 -0
  6. package/dist/chunk-7M634JMD.js.map +1 -0
  7. package/dist/{chunk-3BARPJLY.js → chunk-PZ5GOCWH.js} +16 -2
  8. package/dist/chunk-PZ5GOCWH.js.map +1 -0
  9. package/dist/chunk-SS7NQSSZ.js +3660 -0
  10. package/dist/chunk-SS7NQSSZ.js.map +1 -0
  11. package/dist/chunk-UCZPJX7K.js +14253 -0
  12. package/dist/chunk-UCZPJX7K.js.map +1 -0
  13. package/dist/{cli-CKOMHBXV.js → cli-TV3N47AZ.js} +7317 -4593
  14. package/dist/cli-TV3N47AZ.js.map +1 -0
  15. package/dist/cli.js +2 -3
  16. package/dist/cli.js.map +1 -1
  17. package/dist/errors-GRONKWFS.js +65 -0
  18. package/dist/extension/mu-pi.js +1632 -837
  19. package/dist/extension/mu-pi.js.map +1 -1
  20. package/dist/index.d.ts +4067 -2561
  21. package/dist/index.js +614 -297
  22. package/dist/index.js.map +1 -1
  23. package/dist/tui-FUBQ326D.js +1848 -0
  24. package/dist/tui-FUBQ326D.js.map +1 -0
  25. package/docs/ARCHITECTURE.md +118 -66
  26. package/docs/VOCABULARY.md +113 -49
  27. package/docs/guide/README.md +3 -3
  28. package/docs/guide/backends.md +8 -4
  29. package/docs/guide/cleanup.md +69 -33
  30. package/docs/guide/delegate.md +149 -66
  31. package/docs/guide/dispatch.md +148 -53
  32. package/docs/guide/getting-started.md +37 -44
  33. package/docs/guide/other-agent-clis.md +102 -0
  34. package/docs/guide/recovery.md +31 -50
  35. package/docs/guide/remote.md +122 -45
  36. package/docs/guide/sql.md +104 -24
  37. package/docs/guide/stop-a-worker.md +30 -37
  38. package/docs/guide/sync.md +11 -3
  39. package/docs/guide/upgrade.md +93 -43
  40. package/docs/reference/env.md +24 -32
  41. package/docs/reference/naming.md +14 -7
  42. package/docs/reference/surface-contract.md +153 -0
  43. package/package.json +33 -11
  44. package/prompts/mu-debug.md +3 -1
  45. package/prompts/mu-refute.md +2 -1
  46. package/prompts/mu-research.md +3 -1
  47. package/prompts/mu-review.md +2 -1
  48. package/prompts/mu-rules-audit.md +5 -4
  49. package/prompts/mu-sweep.md +2 -1
  50. package/prompts/mu-tournament.md +4 -2
  51. package/prompts/mu-until.md +3 -1
  52. package/prompts/ultrathink.md +1 -1
  53. package/skills/mu/SKILL.md +60 -291
  54. package/skills/mu/recipes/adversarial-review.md +12 -103
  55. package/skills/mu/recipes/brief.md +14 -61
  56. package/skills/mu/recipes/course-correct.md +23 -0
  57. package/skills/mu/recipes/findings.md +17 -111
  58. package/skills/mu/recipes/models.md +17 -92
  59. package/skills/mu/recipes/move.md +14 -0
  60. package/skills/mu/recipes/orchestrator-loop.md +20 -119
  61. package/skills/mu/recipes/recovery.md +8 -29
  62. package/skills/mu/recipes/remote-workers.md +17 -318
  63. package/skills/mu/recipes/tasks-or-calls.md +15 -78
  64. package/skills/mu/recipes/test-health.md +19 -77
  65. package/skills/mu/recipes/worker.md +17 -24
  66. package/dist/chunk-45KQLMEL.js +0 -2908
  67. package/dist/chunk-45KQLMEL.js.map +0 -1
  68. package/dist/chunk-G434JKV2.js +0 -641
  69. package/dist/chunk-G434JKV2.js.map +0 -1
  70. package/dist/chunk-KUGUFBWH.js +0 -12527
  71. package/dist/chunk-KUGUFBWH.js.map +0 -1
  72. package/dist/chunk-QITLNZEM.js +0 -87
  73. package/dist/chunk-QITLNZEM.js.map +0 -1
  74. package/dist/chunk-VIEYQMQA.js +0 -393
  75. package/dist/chunk-VIEYQMQA.js.map +0 -1
  76. package/dist/chunk-WI6AWCMK.js +0 -19
  77. package/dist/chunk-WI6AWCMK.js.map +0 -1
  78. package/dist/cli-CKOMHBXV.js.map +0 -1
  79. package/dist/devtools-LS4ZEPWM.js +0 -3772
  80. package/dist/devtools-LS4ZEPWM.js.map +0 -1
  81. package/dist/tui-LFJ5P4Y2.js +0 -40956
  82. package/dist/tui-LFJ5P4Y2.js.map +0 -1
  83. package/dist/tui-sync-worker.js +0 -17
  84. package/dist/tui-sync-worker.js.map +0 -1
  85. package/dist/yank-XDOONQSL.js +0 -13
  86. package/dist/yank-XDOONQSL.js.map +0 -1
  87. package/docs/ROADMAP.md +0 -123
  88. package/docs/VISION.md +0 -298
  89. package/docs/architecture/control-socket.md +0 -142
  90. package/docs/architecture/dag.md +0 -117
  91. package/docs/architecture/mux.md +0 -167
  92. package/docs/architecture/ops-log.md +0 -160
  93. package/docs/architecture/sdk.md +0 -187
  94. package/docs/architecture/sync.md +0 -159
  95. package/docs/architecture/tui.md +0 -165
  96. package/docs/guide/tui.md +0 -98
  97. package/docs/history/CHANGELOG-pre-3.md +0 -4866
  98. package/docs/img/tui-dashboard.png +0 -0
  99. package/docs/specs/2026-09-28-agent-state-from-murmur.md +0 -333
  100. package/docs/specs/2026-09-29-task-substates.md +0 -247
  101. package/docs/specs/2026-10-03-keep-driving-nudge.md +0 -163
  102. package/docs/specs/2026-10-21-fast-and-slow-gates.md +0 -229
  103. package/skills/mu/recipes/backlog-triage.md +0 -45
  104. package/skills/mu/recipes/codemode-driver.md +0 -118
  105. package/skills/mu/recipes/deep-research.md +0 -69
  106. package/skills/mu/recipes/drift-audit.md +0 -75
  107. package/skills/mu/recipes/fan-out.md +0 -42
  108. package/skills/mu/recipes/hypothesis-panel.md +0 -48
  109. package/skills/mu/recipes/long-run.md +0 -32
  110. package/skills/mu/recipes/loop-until-done.md +0 -45
  111. package/skills/mu/recipes/plan.md +0 -67
  112. package/skills/mu/recipes/refute.md +0 -55
  113. package/skills/mu/recipes/review-panel.md +0 -65
  114. package/skills/mu/recipes/rules-audit.md +0 -89
  115. package/skills/mu/recipes/tournament.md +0 -44
  116. package/skills/mu/recipes/ultrathink.md +0 -86
  117. package/skills/mu/recipes/watcher.md +0 -28
  118. package/skills/mu/recipes/waves.md +0 -21
  119. /package/dist/{chunk-3BARPJLY.js.map → errors-GRONKWFS.js.map} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../../extension/mu-pi.ts","../../src/ctl/protocol.ts","../../extension/delegate.ts","../../src/state-dir.ts","../../extension/nudge.ts"],"sourcesContent":["/**\n * mu pi extension: serves the per-agent control socket from inside the\n * agent's interactive pi, so mu gets exact send / status / wait without\n * replacing the TUI or scraping the pane.\n *\n * Inert unless `$MU_CTL_SOCK` is set (mu injects it at spawn). Imports\n * nothing from mu except the protocol, and nothing from pi: the pi API is\n * typed structurally below so pi stays a peer, not a dependency.\n */\nimport {\n chmodSync,\n existsSync,\n linkSync,\n mkdirSync,\n readdirSync,\n readFileSync,\n realpathSync,\n rmSync,\n statSync,\n} from \"node:fs\";\nimport { connect, createServer, type Server, type Socket } from \"node:net\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport {\n CTL_COMMANDS,\n CTL_OPS,\n CTL_PROTOCOL_VERSION,\n type CtlBlocked,\n type CtlCommandName,\n type CtlReply,\n type CtlState,\n encode,\n LineDecoder,\n UNKNOWN_OP_PREFIX,\n} from \"../src/ctl/protocol.js\";\nimport {\n type DelegateCtx,\n defaultRunner,\n type MuDelegateApi,\n type MuRunner,\n registerDelegate,\n} from \"./delegate.js\";\nimport {\n type MuNudgeApi,\n parallelSettle,\n registerCloseNudge,\n registerNudge,\n registerRefuteNudge,\n withQueuedInput,\n} from \"./nudge.js\";\n\n/** The mu package version, baked in by tsup's `define`; absent when run from source. */\ndeclare const __MU_VERSION__: string | undefined;\nconst EXT_VERSION = typeof __MU_VERSION__ === \"string\" ? __MU_VERSION__ : undefined;\n\n/** The slice of pi's ExtensionContext this extension uses. */\nexport interface MuPiContext extends DelegateCtx {\n /** pi's session manager; only the session file is read. */\n sessionManager?: { getSessionFile(): string | undefined };\n isIdle(): boolean;\n hasPendingMessages(): boolean;\n abort(): void;\n}\n\n/** The slice of pi's ReplacedSessionContext: bound to the NEW session. */\nexport interface MuPiReplacedContext extends MuPiContext {\n sendUserMessage(text: string): Promise<void>;\n}\n\n/** The slice of pi's ExtensionCommandContext (command handlers only). */\nexport interface MuPiCommandContext extends MuPiContext {\n newSession(options?: {\n withSession?: (ctx: MuPiReplacedContext) => Promise<void>;\n }): Promise<{ cancelled: boolean }>;\n reload(): Promise<void>;\n compact(options?: {\n customInstructions?: string;\n onComplete?: (result: unknown) => void;\n onError?: (error: Error) => void;\n }): void;\n}\n\n/** The slice of pi's ExtensionAPI this extension uses. */\nexport interface MuPiApi extends MuDelegateApi {\n on(\n event:\n | \"session_start\"\n | \"session_shutdown\"\n | \"session_before_compact\"\n | \"agent_start\"\n | \"agent_end\"\n | \"agent_settled\"\n | \"message_start\"\n | \"resources_discover\"\n | \"ui_prompt_start\"\n | \"ui_prompt_end\"\n | Parameters<MuNudgeApi[\"on\"]>[0],\n handler: (event: unknown, ctx: MuPiContext) => unknown,\n ): unknown;\n sendUserMessage(\n text: string,\n options?: { deliverAs?: \"steer\" | \"followUp\"; expandPromptTemplates?: boolean },\n ): void | Promise<void>;\n registerCommand(\n name: string,\n options: {\n description: string;\n handler: (args: string, ctx: MuPiCommandContext) => Promise<void>;\n },\n ): void;\n}\n\n/** Internal command behind the `fresh` op: new session + prompt, inside pi. */\nexport const FRESH_COMMAND = \"mu-fresh\";\n/** The extension's own bound on a fresh op that never reaches agent_start. */\nexport const FRESH_TIMEOUT_MS = 30_000;\n/** Internal command behind the `command` op, per session command: `mu-new`, ... */\nexport function commandName(name: CtlCommandName): string {\n return `mu-${name}`;\n}\n/** The extension's own bound on a `command` op that never completes. */\nexport const COMMAND_TIMEOUT_MS = 30_000;\n/** Cap on `lastText` in a wait reply, in UTF-8 bytes (before the marker). */\nexport const LAST_TEXT_MAX_BYTES = 64 * 1024;\nexport const LAST_TEXT_TRUNCATED = \"[truncated, see pane]\";\n/** How long session_start waits for another pi to answer on the socket path. */\nexport const LIVE_PROBE_MS = 500;\n\ntype Reply = CtlReply;\nconst V = CTL_PROTOCOL_VERSION;\n\nfunction fail(error: string): Reply {\n return { v: V, ok: false, error };\n}\n\n/** Best effort: the version of the pi package running this process. */\nfunction detectPiVersion(): string | undefined {\n try {\n const entry = process.argv[1];\n if (!entry) return undefined;\n let dir = dirname(realpathSync(entry));\n for (let i = 0; i < 6; i++) {\n const pkgPath = join(dir, \"package.json\");\n if (existsSync(pkgPath)) {\n const pkg: unknown = JSON.parse(readFileSync(pkgPath, \"utf8\"));\n if (typeof pkg === \"object\" && pkg !== null) {\n const { name, version } = pkg as { name?: unknown; version?: unknown };\n if (typeof name === \"string\" && /pi/.test(name) && typeof version === \"string\") {\n return version;\n }\n }\n }\n const up = dirname(dir);\n if (up === dir) break;\n dir = up;\n }\n } catch {\n // Unknown version is reported as absent, never as an error.\n }\n return undefined;\n}\n\nfunction str(o: Record<string, unknown>, k: string): string | undefined {\n const x = o[k];\n return typeof x === \"string\" ? x : undefined;\n}\n\nfunction num(o: Record<string, unknown>, k: string): number | undefined {\n const x = o[k];\n return typeof x === \"number\" && Number.isFinite(x) ? x : undefined;\n}\n\n/** A `fresh` op in flight: its prompt and the reply it is waiting to send. */\ntype PendingFresh = {\n text: string;\n /** Set once the new session exists, so its agent_start is the prompt's. */\n armed: boolean;\n settle: (r: Reply) => void;\n};\n\n/** A `command` op in flight: the session command and its pending reply. */\ntype PendingCommand = {\n name: CtlCommandName;\n instructions?: string;\n /** reload: set by the session_start (reason reload) the reload produced. */\n reloaded: boolean;\n settle: (r: Reply) => void;\n};\n\n/**\n * Process-global state, keyed by socket path. pi re-runs this factory\n * for every session (a /new or /mu-fresh replaces the extension runtime),\n * so the socket server, the run counters and an in-flight fresh must\n * outlive any one runtime. Each runtime refreshes `pi` and `handle`.\n */\ntype Shared = {\n server?: Server;\n /** Set by bind(): another pi serves the socket, so this pi is not the agent. */\n nested?: boolean;\n /** Inode of the socket file this process bound; the only file it may unlink. */\n ino?: number;\n conns: Set<Socket>;\n /** Held waits; called with \"settle\" on agent_settled, \"blocked\" on ui_prompt_start. */\n waiters: Set<(why: \"settle\" | \"blocked\") => void>;\n state: CtlState;\n since: number;\n runs: number;\n /** Final assistant text of the last settled run; served by `wait`. */\n lastText: string;\n /** Captured on agent_end, published to `lastText` on agent_settled. */\n endText?: string;\n /** Error that ended the last settled run, if any; served by `wait`. */\n lastError?: string;\n endError?: string;\n /** Session file of the last settled run; served by `wait`. */\n sessionFile?: string;\n ctx?: MuPiContext;\n pi: MuPiApi;\n handle: (req: Record<string, unknown>, conn: Socket) => Promise<Reply>;\n fresh?: PendingFresh;\n command?: PendingCommand;\n};\n\nconst SHARED = Symbol.for(\"mu.pi.ctl\");\ntype SharedMap = Map<string, Shared>;\n\nfunction sharedMap(): SharedMap {\n const g = globalThis as { [SHARED]?: SharedMap };\n g[SHARED] ??= new Map();\n return g[SHARED];\n}\n\n/**\n * Text of the last assistant message in an agent_end event's `messages`:\n * its text parts joined, no tool calls or thinking. \"\" when there is none.\n */\nexport function lastAssistantText(event: unknown): string {\n const msgs =\n typeof event === \"object\" && event !== null\n ? (event as { messages?: unknown }).messages\n : undefined;\n if (!Array.isArray(msgs)) return \"\";\n for (let i = msgs.length - 1; i >= 0; i--) {\n const m: unknown = msgs[i];\n if (typeof m !== \"object\" || m === null) continue;\n const { role, content } = m as { role?: unknown; content?: unknown };\n if (role !== \"assistant\") continue;\n if (typeof content === \"string\") return capText(content);\n if (!Array.isArray(content)) return \"\";\n const parts = content.flatMap((c: unknown) => {\n if (typeof c !== \"object\" || c === null) return [];\n const { type, text } = c as { type?: unknown; text?: unknown };\n return type === \"text\" && typeof text === \"string\" ? [text] : [];\n });\n return capText(parts.join(\"\"));\n }\n return \"\";\n}\n\n/** The final assistant message's error, when the run stopped on one\n * (pi's own retries exhausted: overloaded, connection, auth). */\nexport function lastAssistantError(event: unknown): string | undefined {\n const msgs =\n typeof event === \"object\" && event !== null\n ? (event as { messages?: unknown }).messages\n : undefined;\n if (!Array.isArray(msgs)) return undefined;\n for (let i = msgs.length - 1; i >= 0; i--) {\n const m: unknown = msgs[i];\n if (typeof m !== \"object\" || m === null) continue;\n const { role, stopReason, errorMessage } = m as {\n role?: unknown;\n stopReason?: unknown;\n errorMessage?: unknown;\n };\n if (role !== \"assistant\") continue;\n if (stopReason !== \"error\") return undefined;\n return typeof errorMessage === \"string\" && errorMessage !== \"\"\n ? capText(errorMessage)\n : \"unknown error\";\n }\n return undefined;\n}\n\nfunction capText(text: string): string {\n if (Buffer.byteLength(text, \"utf8\") <= LAST_TEXT_MAX_BYTES) return text;\n // Cut on bytes; drop a code point split by the cut.\n const cut = Buffer.from(text, \"utf8\").subarray(0, LAST_TEXT_MAX_BYTES).toString(\"utf8\");\n return `${cut.replace(/\\uFFFD$/, \"\")}\\n${LAST_TEXT_TRUNCATED}`;\n}\n\n/** Open extension dialogs, outermost first; process-global like Shared. */\ntype UiPrompts = { open: { kind: string; title?: string }[]; since: number };\nconst UI_PROMPTS = Symbol.for(\"mu.pi.uiPrompts\");\n\nfunction uiPrompts(): UiPrompts {\n const g = globalThis as { [UI_PROMPTS]?: UiPrompts };\n g[UI_PROMPTS] ??= { open: [], since: 0 };\n return g[UI_PROMPTS];\n}\n\n/** The open extension dialog pi is waiting on (innermost), or undefined. */\nexport function uiBlocked(): CtlBlocked | undefined {\n const u = uiPrompts();\n const top = u.open[u.open.length - 1];\n if (!top) return undefined;\n return {\n kind: top.kind,\n ...(top.title !== undefined ? { title: top.title } : {}),\n since: u.since,\n };\n}\n\n/** Whether pi is waiting on a blocking extension dialog right now. */\nexport function isUiBlocked(): boolean {\n return uiPrompts().open.length > 0;\n}\n\nfunction promptOf(event: unknown): { kind: string; title?: string } {\n const e = typeof event === \"object\" && event !== null ? (event as Record<string, unknown>) : {};\n const kind = typeof e.kind === \"string\" ? e.kind : \"custom\";\n const title = typeof e.title === \"string\" && e.title !== \"\" ? e.title : undefined;\n return { kind, ...(title !== undefined ? { title } : {}) };\n}\n\n/** Track ui_prompt_start / ui_prompt_end; `onStart` runs after each start. */\nfunction trackUiPrompts(pi: MuPiApi, onStart: () => void = () => {}): void {\n pi.on(\"ui_prompt_start\", (e) => {\n const u = uiPrompts();\n if (u.open.length === 0) u.since = Date.now();\n u.open.push(promptOf(e));\n onStart();\n });\n // A new runtime has no dialog open: drop any whose end a replaced\n // session never delivered.\n pi.on(\"session_start\", () => {\n uiPrompts().open.length = 0;\n });\n pi.on(\"ui_prompt_end\", (e) => {\n const u = uiPrompts();\n // Close the innermost dialog of this kind; prompts nest, so ends come LIFO.\n const { kind } = promptOf(e);\n let i = u.open.length - 1;\n while (i >= 0 && u.open[i]?.kind !== kind) i--;\n u.open.splice(i >= 0 ? i : u.open.length - 1, 1);\n });\n}\n\n/** Inode at `path`, or undefined when there is no file. */\nfunction inodeOf(path: string): number | undefined {\n try {\n return statSync(path).ino;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Whether some process is serving `path`. Refused / missing means a stale\n * file. A connect that neither succeeds nor fails in time counts as live:\n * never steal a socket on a guess.\n */\nfunction socketIsLive(path: string): Promise<boolean> {\n return new Promise((resolve) => {\n const c = connect(path);\n const done = (live: boolean) => {\n clearTimeout(timer);\n c.destroy();\n resolve(live);\n };\n const timer = setTimeout(() => done(true), LIVE_PROBE_MS);\n c.once(\"connect\", () => done(true));\n c.once(\"error\", (e: NodeJS.ErrnoException) =>\n done(e.code !== \"ENOENT\" && e.code !== \"ECONNREFUSED\"),\n );\n });\n}\n\n/** Per-process counter so a rebind never reuses a temp name a closing server owns. */\nlet bindSeq = 0;\n\nfunction reasonOf(event: unknown): string | undefined {\n const r =\n typeof event === \"object\" && event !== null\n ? (event as { reason?: unknown }).reason\n : undefined;\n return typeof r === \"string\" ? r : undefined;\n}\n\n/** The package's `prompts/` dir: two up from dist/extension/, one up from extension/. */\nexport function promptsDir(from: string = import.meta.url): string | undefined {\n let here: string;\n try {\n here = dirname(fileURLToPath(from));\n } catch {\n return undefined;\n }\n for (const up of [\"..\", \"../..\"]) {\n const d = join(here, up, \"prompts\");\n if (existsSync(join(d, \"ultrathink.md\"))) return d;\n }\n return undefined;\n}\n\n/** The recipe slash commands (`/ultrathink`, `/mu-review`, ...): prompt\n * templates shipped in the package, so they upgrade with mu. */\nfunction registerPrompts(pi: MuPiApi): void {\n pi.on(\"resources_discover\", () => {\n const d = promptsDir();\n if (!d) return {};\n const paths = readdirSync(d)\n .filter((f) => f.endsWith(\".md\"))\n .sort()\n .map((f) => join(d, f));\n return { promptPaths: paths };\n });\n}\n\nexport default function muPi(pi: MuPiApi, run: MuRunner = defaultRunner()): void {\n const delegates = registerDelegate(pi, run);\n registerPrompts(pi);\n // Identity follows the bind: a pi that finds MU_CTL_SOCK served by\n // another pi is nested and gets none of the agent's nudges.\n const nested = serveCtl(pi);\n // The three nudges' settle checks run in parallel, as one handler.\n // A delegate answer on its way resumes the agent itself; an open\n // dialog means nobody is driving. Either holds the nudges.\n const hold = withQueuedInput(() =>\n delegates.answerPending() ? \"answer\" : isUiBlocked() ? \"blocked\" : undefined,\n );\n const settle = parallelSettle(pi, hold);\n registerNudge(settle.api, run, undefined, nested, hold);\n registerCloseNudge(settle.api, run, process.env, nested, hold);\n registerRefuteNudge(settle.api, run, nested, hold);\n settle.flush();\n}\n\n/**\n * Child side: serve `$MU_CTL_SOCK` for the mu that spawned this pi.\n * Returns whether this pi is nested (another pi serves the socket), read\n * from the process-global state so a reloaded runtime sees the decision.\n */\nfunction serveCtl(pi: MuPiApi): () => boolean {\n const sock = process.env.MU_CTL_SOCK;\n if (!sock) {\n trackUiPrompts(pi);\n return () => false;\n }\n const sockPath: string = sock;\n const piVersion = detectPiVersion();\n\n const map = sharedMap();\n const existing = map.get(sockPath);\n const g: Shared = existing ?? {\n conns: new Set(),\n waiters: new Set(),\n state: \"idle\",\n since: Date.now(),\n runs: 0,\n lastText: \"\",\n pi,\n handle,\n };\n g.pi = pi;\n g.handle = handle;\n map.set(sockPath, g);\n\n const status = () => ({\n state: g.state,\n since: g.since,\n runs: g.runs,\n pending: g.ctx?.hasPendingMessages() ?? false,\n ...sessionFileOf(g.ctx),\n ...blockedField(),\n });\n\n const blockedField = (): { blocked?: CtlBlocked } => {\n const b = uiBlocked();\n return b ? { blocked: b } : {};\n };\n\n trackUiPrompts(pi, () => {\n for (const w of [...g.waiters]) w(\"blocked\");\n });\n\n const settleFresh = (r: Reply) => {\n const f = g.fresh;\n if (!f) return;\n g.fresh = undefined;\n f.settle(r);\n };\n\n const settleCommand = (r: Reply) => {\n const c = g.command;\n if (!c) return;\n g.command = undefined;\n c.settle(r);\n };\n\n pi.on(\"agent_start\", (_e, c) => {\n g.ctx = c;\n g.state = \"busy\";\n g.since = Date.now();\n // The new session's run started: the fresh prompt landed.\n if (g.fresh?.armed) settleFresh({ v: V, ok: true, ...status() });\n });\n\n // A settled run can span several low-level runs (retry, follow-up):\n // the last agent_end before the settle holds the final answer.\n pi.on(\"agent_end\", (e) => {\n g.endText = lastAssistantText(e);\n g.endError = lastAssistantError(e);\n });\n\n /** The session file of `c`, as a spreadable field; {} when unknown. */\n function sessionFileOf(c: MuPiContext | undefined): { sessionFile?: string } {\n try {\n const f = c?.sessionManager?.getSessionFile();\n return f ? { sessionFile: f } : {};\n } catch {\n return {}; // stale ctx: the pointer is a convenience\n }\n }\n\n pi.on(\"agent_settled\", (_e, c) => {\n g.ctx = c;\n g.state = \"idle\";\n g.since = Date.now();\n g.runs++;\n g.lastText = g.endText ?? \"\";\n g.endText = undefined;\n g.lastError = g.endError;\n g.endError = undefined;\n g.sessionFile = sessionFileOf(c).sessionFile;\n for (const w of [...g.waiters]) w(\"settle\");\n });\n\n pi.registerCommand(FRESH_COMMAND, {\n description: \"mu internal: new session + the prompt mu queued (run by mu agent send --fresh)\",\n handler: async (_args, ctx) => {\n const f = g.fresh;\n if (!f) return; // typed by hand: nothing queued\n try {\n const r = await ctx.newSession({\n withSession: async (c) => {\n g.ctx = c;\n f.armed = true;\n await c.sendUserMessage(f.text);\n },\n });\n if (r.cancelled) settleFresh(fail(\"new session was cancelled\"));\n } catch (e) {\n settleFresh(fail(e instanceof Error ? e.message : String(e)));\n }\n // The run finished without an agent_start we saw: still landed.\n settleFresh({ v: V, ok: true, ...status() });\n },\n });\n\n // A compaction we asked for has started: reply now, not after the\n // summary call. Errors before this point (e.g. \"Nothing to compact\")\n // reach the reply through compact's onError.\n pi.on(\"session_before_compact\", () => {\n if (g.command?.name === \"compact\") settleCommand({ v: V, ok: true, ...status() });\n });\n\n /** Run the queued session command `name` with pi's command context. */\n async function runCommand(name: CtlCommandName, ctx: MuPiCommandContext): Promise<void> {\n const c = g.command;\n if (c?.name !== name) return; // typed by hand: nothing queued\n const ok = () => settleCommand({ v: V, ok: true, ...status() });\n const failWith = (e: unknown) =>\n settleCommand(fail(e instanceof Error ? e.message : String(e)));\n try {\n if (name === \"new\") {\n const r = await ctx.newSession();\n if (r.cancelled) settleCommand(fail(\"new session was cancelled\"));\n else ok();\n } else if (name === \"reload\") {\n await ctx.reload();\n // pi's reload returns quietly when it refuses (streaming, compacting).\n if (c.reloaded) ok();\n else settleCommand(fail(\"pi did not reload (busy or compacting)\"));\n } else {\n ctx.compact({\n ...(c.instructions !== undefined ? { customInstructions: c.instructions } : {}),\n onComplete: ok,\n onError: failWith,\n });\n }\n } catch (e) {\n failWith(e);\n }\n }\n\n for (const name of CTL_COMMANDS) {\n pi.registerCommand(commandName(name), {\n description: `mu internal: /${name} requested over the control socket (mu agent send '/${name}')`,\n handler: (_args, ctx) => runCommand(name, ctx),\n });\n }\n\n function command(req: Record<string, unknown>): Promise<Reply> | Reply {\n const name = CTL_COMMANDS.find((n) => n === req.name);\n if (name === undefined) {\n return fail(`command must be one of ${CTL_COMMANDS.join(\", \")}`);\n }\n if (g.fresh || g.command) return fail(\"a fresh send or command is already in progress\");\n const busy = !(g.ctx?.isIdle() ?? g.state === \"idle\");\n if (busy && req.force !== true) return fail(\"busy\");\n const instructions = str(req, \"instructions\");\n return new Promise<Reply>((resolve) => {\n const timer = setTimeout(() => settleCommand(fail(`/${name} timed out`)), COMMAND_TIMEOUT_MS);\n g.command = {\n name,\n ...(instructions !== undefined ? { instructions } : {}),\n reloaded: false,\n settle: (r) => {\n clearTimeout(timer);\n resolve(r);\n },\n };\n Promise.resolve(\n g.pi.sendUserMessage(`/${commandName(name)}`, { expandPromptTemplates: true }),\n ).catch((e: unknown) => settleCommand(fail(e instanceof Error ? e.message : String(e))));\n });\n }\n\n function fresh(req: Record<string, unknown>): Promise<Reply> | Reply {\n const text = str(req, \"text\");\n if (text === undefined) return fail(\"fresh needs a string text\");\n if (g.fresh || g.command) return fail(\"a fresh send or command is already in progress\");\n const busy = !(g.ctx?.isIdle() ?? g.state === \"idle\");\n if (busy && req.force !== true) return fail(\"busy\");\n return new Promise<Reply>((resolve) => {\n const timer = setTimeout(() => settleFresh(fail(\"fresh timed out\")), FRESH_TIMEOUT_MS);\n g.fresh = {\n text,\n armed: false,\n settle: (r) => {\n clearTimeout(timer);\n resolve(r);\n },\n };\n // expandPromptTemplates dispatches extension commands, even mid-run.\n Promise.resolve(\n g.pi.sendUserMessage(`/${FRESH_COMMAND}`, { expandPromptTemplates: true }),\n ).catch((e: unknown) => settleFresh(fail(e instanceof Error ? e.message : String(e))));\n });\n }\n\n async function handle(req: Record<string, unknown>, conn: Socket): Promise<Reply> {\n switch (req.op) {\n case \"hello\":\n return {\n v: V,\n ok: true,\n agent: process.env.MU_AGENT_NAME,\n workstream: process.env.MU_WORKSTREAM,\n piVersion,\n ops: [...CTL_OPS],\n ...(EXT_VERSION !== undefined ? { extVersion: EXT_VERSION } : {}),\n };\n case \"status\":\n return { v: V, ok: true, ...status() };\n case \"send\": {\n const text = str(req, \"text\");\n if (text === undefined) return fail(\"send needs a string text\");\n const mode = req.mode === \"steer\" ? \"steer\" : \"followUp\";\n // Measured before dispatch: `runs` is the caller's wait baseline,\n // and a run this send starts may settle before the reply is read.\n const before = status();\n // A message sent while idle starts a run; options are only for a busy pi.\n if (g.ctx?.isIdle() ?? g.state === \"idle\") await g.pi.sendUserMessage(text);\n else await g.pi.sendUserMessage(text, { deliverAs: mode });\n return { v: V, ok: true, ...before };\n }\n case \"fresh\":\n return fresh(req);\n case \"command\":\n return command(req);\n case \"wait\":\n return wait(\n num(req, \"afterRuns\"),\n num(req, \"timeoutMs\"),\n conn,\n req.returnOnBlocked === true,\n );\n case \"abort\":\n if (!g.ctx) return fail(\"no pi context yet\");\n {\n // The run may have settled since the caller's status probe.\n const wasBusy = !g.ctx.isIdle();\n if (wasBusy) g.ctx.abort();\n return { v: V, ok: true, state: g.state, wasBusy };\n }\n case \"interrupt\":\n return interrupt(req, conn);\n default:\n return { ...fail(`${UNKNOWN_OP_PREFIX}${String(req.op)}`), ops: [...CTL_OPS] };\n }\n }\n\n /**\n * Abort a busy turn, wait for its settle, then send `text` as a new run.\n * The waiter is registered before the abort, so a settle that lands at\n * once is not missed. `runs` is read after that settle and before the\n * send: the caller's wait baseline for the new run, not the aborted one.\n */\n async function interrupt(req: Record<string, unknown>, conn: Socket): Promise<Reply> {\n const text = str(req, \"text\");\n if (text === undefined) return fail(\"interrupt needs a string text\");\n const wasBusy = !(g.ctx?.isIdle() ?? g.state === \"idle\");\n const { pending } = status();\n if (wasBusy) {\n if (!g.ctx) return fail(\"no pi context yet\");\n const settled = wait(g.runs, num(req, \"timeoutMs\"), conn);\n g.ctx.abort();\n const w = await settled;\n if (!w.ok) return w;\n }\n const before = status();\n await g.pi.sendUserMessage(text);\n return { v: V, ok: true, ...before, pending, wasBusy };\n }\n\n const settledRun = () => ({\n lastText: g.lastText,\n ...(g.lastError !== undefined ? { lastError: g.lastError } : {}),\n ...(g.sessionFile !== undefined ? { sessionFile: g.sessionFile } : {}),\n });\n\n /**\n * Resolve once a run past `afterRuns` has settled (any next settle when\n * omitted). With `onBlocked`, an open or opening dialog ends the wait\n * first: `ended: \"blocked\"`, no settled-run fields, runs unchanged.\n */\n function wait(\n afterRuns: number | undefined,\n timeoutMs: number | undefined,\n conn: Socket,\n onBlocked = false,\n ) {\n if (afterRuns !== undefined && g.runs > afterRuns && g.state === \"idle\") {\n return Promise.resolve<Reply>({\n v: V,\n ok: true,\n ...status(),\n ...settledRun(),\n ended: \"settled\",\n });\n }\n const blockedReply = (): Reply => ({ v: V, ok: true, ...status(), ended: \"blocked\" });\n if (onBlocked && isUiBlocked()) return Promise.resolve(blockedReply());\n return new Promise<Reply>((resolve) => {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const done = (r: Reply) => {\n g.waiters.delete(waiter);\n if (timer) clearTimeout(timer);\n conn.off(\"close\", onClose);\n resolve(r);\n };\n // A settle at or below `afterRuns` is not the run asked for: keep waiting.\n const waiter = (why: \"settle\" | \"blocked\") => {\n if (why === \"blocked\") {\n if (onBlocked) done(blockedReply());\n return;\n }\n if (afterRuns !== undefined && g.runs <= afterRuns) return;\n done({ v: V, ok: true, ...status(), ...settledRun(), ended: \"settled\" });\n };\n const onClose = () => done(fail(\"client closed\"));\n g.waiters.add(waiter);\n conn.on(\"close\", onClose);\n if (timeoutMs !== undefined) timer = setTimeout(() => done(fail(\"timeout\")), timeoutMs);\n });\n }\n\n /** Created once per process; dispatches to the newest runtime's handle. */\n function onConnection(conn: Socket): void {\n g.conns.add(conn);\n conn.setEncoding(\"utf8\");\n const dec = new LineDecoder();\n let seen = false;\n conn.on(\"close\", () => g.conns.delete(conn));\n conn.on(\"error\", () => {});\n conn.on(\"data\", (chunk: string) => {\n const line = dec.push(chunk)[0];\n if (line === undefined || seen) return;\n seen = true; // one request per connection\n let req: unknown;\n try {\n req = JSON.parse(line);\n } catch {\n conn.end(encode(fail(\"bad json\")));\n return;\n }\n if (typeof req !== \"object\" || req === null) {\n conn.end(encode(fail(\"request must be an object\")));\n return;\n }\n g.handle(req as Record<string, unknown>, conn).then(\n (r) => {\n if (!conn.destroyed) conn.end(encode(r));\n },\n (e: unknown) => {\n if (!conn.destroyed) conn.end(encode(fail(e instanceof Error ? e.message : String(e))));\n },\n );\n });\n }\n\n /**\n * Bind the socket unless another pi already serves it. A nested pi (a\n * probe or `pi -p` run inside an agent's pane) inherits MU_CTL_SOCK; it\n * must leave the agent's socket alone, not unlink and take it.\n */\n async function bind(): Promise<void> {\n mkdirSync(dirname(sockPath), { recursive: true, mode: 0o700 });\n if (await socketIsLive(sockPath)) {\n g.nested = true;\n process.stderr.write(\n `mu: control socket ${sockPath} is served by another pi; nested pi: mu agent features off\\n`,\n );\n return;\n }\n rmSync(sockPath, { force: true });\n // Listen on a private name, then hard-link it into place. libuv unlinks\n // the name a server listened on when it closes, so the public path must\n // never be that name: closing would delete whatever file sits there by\n // then. link() also fails on an existing path, so a racing pi keeps it.\n const tmp = join(dirname(sockPath), `.${process.pid.toString(36)}${(++bindSeq).toString(36)}`);\n rmSync(tmp, { force: true });\n const s = createServer(onConnection);\n await new Promise<void>((resolve, reject) => {\n s.once(\"error\", reject);\n s.listen(tmp, () => {\n s.off(\"error\", reject);\n resolve();\n });\n });\n chmodSync(tmp, 0o600);\n try {\n linkSync(tmp, sockPath);\n } catch (e) {\n s.close();\n if ((e as NodeJS.ErrnoException).code !== \"EEXIST\") throw e;\n g.nested = true;\n process.stderr.write(\n `mu: control socket ${sockPath} was taken by another pi; nested pi: mu agent features off\\n`,\n );\n return;\n } finally {\n rmSync(tmp, { force: true });\n }\n g.server = s;\n g.ino = inodeOf(sockPath);\n g.nested = false;\n }\n\n pi.on(\"session_start\", async (e, c) => {\n g.ctx = c;\n if (reasonOf(e) === \"reload\" && g.command?.name === \"reload\") g.command.reloaded = true;\n const s = g.server;\n if (s) {\n // A new/resumed session keeps the same socket, while the path is ours.\n if (g.ino !== undefined && inodeOf(sockPath) === g.ino) return;\n // Orphaned: the file was deleted or replaced under a live server.\n // Stop accepting on the dead inode (open connections finish) and rebind.\n g.server = undefined;\n g.ino = undefined;\n s.close();\n }\n await bind();\n });\n\n pi.on(\"session_shutdown\", async (e) => {\n // Session replacement (new / resume / fork / reload) keeps the socket\n // and its connections: an in-flight fresh is answered by the next\n // runtime. Only quit (or an unknown reason) tears the server down.\n const reason = reasonOf(e);\n if (reason === \"new\" || reason === \"resume\" || reason === \"fork\" || reason === \"reload\") {\n return;\n }\n const s = g.server;\n const ino = g.ino;\n g.server = undefined;\n g.ino = undefined;\n map.delete(sockPath);\n if (!s) return;\n g.waiters.clear();\n settleFresh(fail(\"pi is shutting down\"));\n settleCommand(fail(\"pi is shutting down\"));\n for (const c of g.conns) c.destroy();\n await new Promise<void>((resolve) => s.close(() => resolve()));\n // Unlink only the file this process bound: another pi may own the path now.\n if (ino !== undefined && inodeOf(sockPath) === ino) rmSync(sockPath, { force: true });\n });\n\n return () => g.nested === true;\n}\n","/**\n * mu control socket protocol: JSON lines over a unix socket, one request\n * per connection. Shared by mu's client and the mu pi extension, so this\n * file imports nothing from mu — the extension loads it standalone.\n */\n\nexport const CTL_PROTOCOL_VERSION = 1;\n\nexport type CtlState = \"busy\" | \"idle\";\n\n/**\n * pi is waiting on a blocking extension dialog (ui_prompt_start without\n * its ui_prompt_end): a confirm, select, input, editor or custom prompt.\n * `kind` and `title` are the innermost open dialog's; `since` is when the\n * first one opened (ms epoch).\n */\nexport type CtlBlocked = { kind: string; title?: string; since: number };\n\nexport type CtlRequest =\n | { op: \"hello\" }\n | { op: \"status\" }\n | { op: \"send\"; text: string; mode?: \"steer\" | \"followUp\" }\n /**\n * Resolve once a run past afterRuns settles. With returnOnBlocked, also\n * resolve (ended \"blocked\", runs unchanged) when a dialog is open or\n * opens. Older extensions ignore the flag and hold until the settle.\n */\n | { op: \"wait\"; afterRuns?: number; timeoutMs?: number; returnOnBlocked?: boolean }\n | { op: \"abort\" }\n /**\n * Make a busy pi act on `text` now: abort the running turn, wait for\n * agent_settled (up to timeoutMs), then send `text` as a new run. Idle:\n * just send. Replies `timeout` and sends nothing when pi does not settle.\n */\n | { op: \"interrupt\"; text: string; timeoutMs?: number }\n /** New session + prompt as one operation. Refused with error \"busy\" unless force. */\n | { op: \"fresh\"; text: string; force?: boolean }\n /**\n * Run one of pi's session commands inside pi (sendUserMessage cannot run\n * built-in slash commands). Refused with error \"busy\" unless force.\n */\n | { op: \"command\"; name: CtlCommandName; instructions?: string; force?: boolean };\n\n/** Session commands the `command` op runs: `/new`, `/reload`, `/compact`. */\nexport const CTL_COMMANDS = [\"new\", \"reload\", \"compact\"] as const;\nexport type CtlCommandName = (typeof CTL_COMMANDS)[number];\n\n/**\n * Every op this protocol defines. The extension reports the ops it serves\n * in its `hello` reply (and in an unknown-op error), so mu can tell an\n * extension loaded by an older pi process from a broken one.\n */\nexport const CTL_OPS = [\n \"hello\",\n \"status\",\n \"send\",\n \"wait\",\n \"abort\",\n \"interrupt\",\n \"fresh\",\n \"command\",\n] as const satisfies readonly CtlRequest[\"op\"][];\n\nexport type CtlStatus = {\n state: CtlState;\n since: number;\n runs: number;\n pending: boolean;\n /** The pi session file (where the transcript is written); absent for an ephemeral pi or an older extension. */\n sessionFile?: string;\n /** Set while pi waits on an extension dialog; absent from older extensions. */\n blocked?: CtlBlocked;\n};\n\nexport type CtlReply =\n | ({ v: 1; ok: true } & Partial<CtlStatus> & {\n agent?: string;\n workstream?: string;\n piVersion?: string;\n /** hello only: the ops this extension serves. Absent: predates reporting. */\n ops?: string[];\n /** hello only: the mu package version the extension was built from. */\n extVersion?: string;\n /** wait only: \"blocked\" when a dialog ended the wait before a settle (returnOnBlocked). */\n ended?: \"settled\" | \"blocked\";\n /** wait only: text of the settled run's final assistant message (\"\" when none). */\n lastText?: string;\n /** wait only: the error that ended the settled run (retries exhausted). */\n lastError?: string;\n /** wait only: the settled pi's session file, where its full transcript lives. */\n sessionFile?: string;\n /**\n * abort, interrupt: pi was busy, so a turn was aborted. For abort,\n * absent from older extensions (which always call abort).\n */\n wasBusy?: boolean;\n })\n | { v: 1; ok: false; error: string; ops?: string[] };\n\n/** Error text of a reply to an op the extension does not serve. */\nexport const UNKNOWN_OP_PREFIX = \"unknown op: \";\n\n/** One frame. JSON.stringify escapes \"\\n\" inside strings, so the frame is one line. */\nexport function encode(msg: object): string {\n return `${JSON.stringify(msg)}\\n`;\n}\n\n/** Splits a stream into lines on \"\\n\" only (never U+2028/U+2029). */\nexport class LineDecoder {\n private buf = \"\";\n\n push(chunk: string): string[] {\n this.buf += chunk;\n const parts = this.buf.split(\"\\n\");\n this.buf = parts.pop() ?? \"\";\n return parts;\n }\n}\n","/**\n * mu pi extension, parent side: the `mu_delegate` tool.\n *\n * A delegate is a scratch agent started for one task. The tool spawns it,\n * hands it the task, returns at once, and posts the answer back into this\n * conversation as a follow-up when the delegate's run settles.\n *\n * Everything is the `mu` CLI (spawn / send / wait --json / read / abort /\n * close): the tool only orders the calls and formats the result, so a\n * shell gets the same delegation (VISION § 1, rule 2). The one\n * thing only an extension can do is the callback into the parent\n * conversation, and that is presentation. No extension-only state: the\n * in-flight set below is the list of `mu agent wait` children this pi owns.\n *\n * Separate from the child side (the control-socket server in mu-pi.ts):\n * that one serves a pi mu spawned; this one runs in a pi that is not.\n */\nimport { execFile } from \"node:child_process\";\nimport { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from \"node:fs\";\nimport { delimiter, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { defaultCacheDir } from \"../src/state-dir.js\";\n\n/** The slice of pi's ExtensionAPI the delegate side uses. */\nexport interface MuDelegateApi {\n registerTool(tool: DelegateTool): void;\n sendMessage(\n message: { customType: string; content: string; display: boolean; details?: unknown },\n options?: { triggerTurn?: boolean; deliverAs?: \"steer\" | \"followUp\" | \"nextTurn\" },\n ): void | Promise<void>;\n on(\n event: \"session_shutdown\" | \"message_start\" | \"agent_settled\",\n handler: (event: unknown, ctx: DelegateCtx) => unknown,\n ): unknown;\n /** pi's in-process bus between extensions. */\n events: { emit(channel: string, data: unknown): void };\n}\n\n/** The slice of pi's ExtensionContext the delegate side uses. */\nexport interface DelegateCtx {\n hasUI?: boolean;\n cwd?: string;\n ui?: {\n notify(message: string, type?: \"info\" | \"warning\" | \"error\"): void;\n setStatus?(key: string, text: string | undefined): void;\n };\n}\n\ntype ToolResult = { content: { type: \"text\"; text: string }[]; details: unknown };\n\nexport interface DelegateTool {\n name: string;\n label: string;\n description: string;\n promptSnippet?: string;\n parameters: object;\n execute(\n id: string,\n params: Record<string, unknown>,\n signal?: AbortSignal,\n onUpdate?: unknown,\n ctx?: DelegateCtx,\n ): Promise<ToolResult>;\n}\n\nexport type MuResult = { code: number; stdout: string; stderr: string };\n/** Runs `mu <args>`. The test seam: tests inject a fake. */\nexport type MuRunner = (args: readonly string[], signal?: AbortSignal) => Promise<MuResult>;\n\nexport const DELEGATE_TOOL = \"mu_delegate\";\nexport const DELEGATE_CANCEL_TOOL = \"mu_delegate_cancel\";\nexport const DELEGATE_MESSAGE_TYPE = \"mu-delegate\";\nexport const DELEGATE_WORKSTREAM = \"scratch\";\n/** The footer status key (`ctx.ui.setStatus`), like goal / watchloop. */\nexport const DELEGATE_STATUS_KEY = \"mu-delegate\";\n/**\n * murmur's channel for outstanding background work, as\n * `{ source, count }`. murmur shows the count on this agent's card,\n * renders a stopped agent with work out as `waiting`, and holds back\n * `done` until it is zero: a parent that ended its turn to wait on\n * delegates has not finished. A string, not an import: neither side\n * depends on the other, and with no murmur loaded nobody listens.\n */\nexport const PENDING_CHANNEL = \"murmur:pending\";\n\n/** Footer text: delegates running (pane up), starting (no pane yet),\n * queued, failed, and finished whose answer has not reached this\n * conversation yet (pending); undefined clears the entry. */\nexport function delegateStatus(\n running: number,\n starting = 0,\n queued = 0,\n failed = 0,\n pending = 0,\n): string | undefined {\n const parts: string[] = [];\n if (running > 0) parts.push(`${running} delegate${running === 1 ? \"\" : \"s\"} running`);\n if (starting > 0) parts.push(`${starting} starting`);\n if (queued > 0) parts.push(`${queued} queued`);\n if (failed > 0) parts.push(`${failed} failed`);\n if (pending > 0) parts.push(`${pending} result${pending === 1 ? \"\" : \"s\"} pending`);\n return parts.length > 0 ? parts.join(\", \") : undefined;\n}\n/** Default `mu agent wait --timeout` for a delegate, in seconds. */\nexport const DELEGATE_TIMEOUT_S = 3600;\n/** Default cap on delegates in flight from one pi session. */\nexport const DELEGATE_MAX_DEFAULT = 16;\n/** The queue holds this many caps' worth of calls waiting for a slot. A\n * fan-out (refuters per finding, checkers per claim) issues several\n * caps' worth in one turn; past this, the model is refused. */\nexport const DELEGATE_QUEUE_FACTOR = 4;\n\n/** Minimum gap between the `mu agent list` calls that prune the footer's\n * failed-delegate count. */\nexport const PRUNE_FAILED_MS = 30_000;\n\n/** `MU_DELEGATE_MAX`: a positive integer, else the default. */\nexport function delegateMax(env: NodeJS.ProcessEnv = process.env): number {\n const n = Number(env.MU_DELEGATE_MAX);\n return Number.isInteger(n) && n > 0 ? n : DELEGATE_MAX_DEFAULT;\n}\nconst W = DELEGATE_WORKSTREAM;\n\n/** Registration guards: unmanaged pi, a mux in reach, not switched off. */\nexport function delegateEnabled(env: NodeJS.ProcessEnv = process.env): boolean {\n if (env.MU_MANAGED_AGENT) return false; // no helper-spawns-helper\n if (env.MU_DELEGATE === \"0\") return false;\n if (env.MU_MUX || env.HERDR_ENV === \"1\" || env.TMUX || env.TMUX_PANE) return true;\n return onPath(\"tmux\", env) || onPath(\"herdr\", env);\n}\n\nfunction isDir(p: string): boolean {\n try {\n return statSync(p).isDirectory();\n } catch {\n return false;\n }\n}\n\nfunction onPath(bin: string, env: NodeJS.ProcessEnv): boolean {\n return (env.PATH ?? \"\").split(delimiter).some((d) => d !== \"\" && existsSync(join(d, bin)));\n}\n\n/** The CLI this extension ships with (dist/cli.js next to dist/extension/), else `mu` on PATH. */\nexport function defaultRunner(): MuRunner {\n let cli: string | undefined;\n try {\n const p = fileURLToPath(new URL(\"../cli.js\", import.meta.url));\n if (existsSync(p)) cli = p;\n } catch {\n // not a file: URL; use PATH\n }\n return (args, signal) =>\n new Promise((resolve) => {\n const [cmd, argv] = cli ? [process.execPath, [cli, ...args]] : [\"mu\", [...args]];\n execFile(\n cmd,\n argv,\n { maxBuffer: 16 * 1024 * 1024, ...(signal ? { signal } : {}) },\n (err, stdout, stderr) => {\n const code = err ? (typeof err.code === \"number\" ? err.code : 1) : 0;\n resolve({ code, stdout: String(stdout), stderr: String(stderr || err?.message || \"\") });\n },\n );\n });\n}\n\n/** One agent row of `mu agent wait --json`, as far as the tool reads it. */\nexport type WaitAgent = {\n outcome?: string;\n lastText?: string;\n lastError?: string;\n /** The delegate's pi session file (mu ≥ 3.11.2 on the delegate side). */\n sessionFile?: string;\n /** outcome `blocked`: the extension dialog the delegate's pi waits on. */\n blocked?: { kind?: string; title?: string };\n /** The run baseline the wait counted from; a re-wait passes it as\n * `--after-runs` so a run that settles in between is not missed. */\n afterRuns?: number;\n};\n\n/** What happened to the pane after delivery, for the message. */\nexport type PaneFate = { closed: true } | { closed: false; why: string };\n\n/** Extras for the follow-up message; all optional. */\nexport type MessageExtras = {\n /** `mu agent read -n 50` for the outcomes without text. */\n tail?: string;\n attach?: string;\n timeoutS?: number;\n workspace?: string;\n /** How long the delegate ran, in ms. */\n elapsedMs?: number;\n /** The queue handle the caller was given (`queued-3`), if it was queued. */\n queuedAs?: string;\n /** The delegate's pi session file: the full transcript. */\n sessionFile?: string;\n /** A local copy of the delegate's last assistant text so far. */\n partial?: string;\n};\n\n/**\n * Text of the last assistant message in a pi session file (JSONL), or\n * undefined when there is none or the file cannot be read. A delegate\n * that timed out, died or was cancelled has no final answer, but what it\n * wrote so far is here.\n */\nexport function lastAssistantTextIn(sessionFile: string): string | undefined {\n let raw: string;\n try {\n raw = readFileSync(sessionFile, \"utf8\");\n } catch {\n return undefined;\n }\n const lines = raw.split(\"\\n\");\n for (let i = lines.length - 1; i >= 0; i--) {\n const line = lines[i];\n if (!line?.includes('\"assistant\"')) continue;\n try {\n const e = JSON.parse(line) as { message?: { role?: unknown; content?: unknown } };\n if (e.message?.role !== \"assistant\") continue;\n const c = e.message.content;\n const text =\n typeof c === \"string\"\n ? c\n : Array.isArray(c)\n ? c\n .map((p: unknown) => {\n const q = p as { type?: unknown; text?: unknown };\n return q.type === \"text\" && typeof q.text === \"string\" ? q.text : \"\";\n })\n .join(\"\")\n : \"\";\n if (text.trim()) return text;\n } catch {\n // a torn last line while pi writes: keep looking\n }\n }\n return undefined;\n}\n\n/** Where to look next for a delegate with no final answer: the copy of\n * its partial text and its session file, one line each. */\nfunction evidenceLines(x: { sessionFile?: string; partial?: string }): string[] {\n return [\n x.partial ? `Partial answer so far: ${x.partial}` : undefined,\n x.sessionFile ? `Session: ${x.sessionFile}` : undefined,\n ].filter((v) => v !== undefined);\n}\n\n/** `42s`, `3m 05s`, `1h 02m`. */\nexport function formatElapsed(ms: number): string {\n const t = Math.max(0, Math.round(ms / 1000));\n if (t < 60) return `${t}s`;\n const m = Math.floor(t / 60);\n if (m < 60) return `${m}m ${String(t % 60).padStart(2, \"0\")}s`;\n return `${Math.floor(m / 60)}h ${String(m % 60).padStart(2, \"0\")}m`;\n}\n\n/**\n * The follow-up message for one finished wait. Pure: the CLI already\n * classified the outcome (`mu agent wait --json` → `outcome`); this only\n * words it.\n */\nexport function delegateMessage(\n name: string,\n agent: WaitAgent | undefined,\n pane: PaneFate,\n x: MessageExtras = {},\n): string {\n const timeoutS = x.timeoutS ?? DELEGATE_TIMEOUT_S;\n const who = `Delegate ${W}/${name}${x.queuedAs ? ` (queued as ${x.queuedAs})` : \"\"}`;\n const took = x.elapsedMs !== undefined ? ` after ${formatElapsed(x.elapsedMs)}` : \"\";\n const fate = pane.closed ? \"Pane closed.\" : `Pane kept (${pane.why}).`;\n const look = [\n x.attach ? `Attach: ${x.attach}` : undefined,\n `Read: mu agent read ${name} -n 50 -w ${W}`,\n ].filter((v) => v !== undefined);\n const tailBlock = x.tail?.trim() ? `\\n\\nPane tail:\\n${x.tail.trimEnd()}` : \"\";\n const ws = x.workspace ? ` Workspace: ${x.workspace}` : \"\";\n const ev = evidenceLines(x);\n const evBlock = ev.length > 0 ? `\\n${ev.join(\"\\n\")}` : \"\";\n switch (agent?.outcome) {\n case \"done\":\n return `${who} finished${took}. ${fate}${ws}\\n\\n${agent.lastText ?? \"\"}`;\n case \"empty\":\n return `${who} finished${took} without a text answer. ${fate}${ws}${evBlock}${tailBlock}`;\n case \"error\":\n return [\n `${who} stopped on an API error${took}, after pi's own retries: ${(agent.lastError ?? \"unknown error\").replace(/[.\\s]+$/, \"\")}. ${fate}${ws}`,\n \"Decide: re-issue the call, or record the check as UNVERIFIED.\",\n ...ev,\n ...look,\n `Close: mu agent close ${name} -w ${W}`,\n ].join(\"\\n\");\n case \"died\":\n return `${who} died${took} before answering. ${fate}${ws}${evBlock}${tailBlock}`;\n case \"blocked\": {\n const b = agent.blocked;\n const dialog = `${b?.kind ?? \"dialog\"}${b?.title ? ` \"${b.title}\"` : \"\"}`;\n const lines = [\n `${who} is blocked on a ${dialog} dialog${took} and has NOT finished; stopped waiting, so its answer will not arrive here. ${fate}${ws}`,\n \"Answer the dialog in its pane (attach), then wait again; or close it and record the check as UNVERIFIED.\",\n ...ev,\n ...look,\n `Wait again: mu agent wait ${name} -w ${W} --json${agent.afterRuns !== undefined ? ` --after-runs ${agent.afterRuns}` : \"\"}`,\n `Close: mu agent close ${name} -w ${W}`,\n ];\n return `${lines.join(\"\\n\")}${tailBlock}`;\n }\n case \"timeout\":\n case \"pending\":\n return [\n `${who} is still running after ${timeoutS}s; stopped waiting, so its answer will not arrive here. ${fate}${ws}`,\n ...ev,\n ...look,\n `Wait again: mu agent wait ${name} -w ${W} --json${agent.afterRuns !== undefined ? ` --after-runs ${agent.afterRuns}` : \"\"}`,\n ].join(\"\\n\");\n default:\n return `${who}: mu agent wait gave no result. ${fate}${ws}${evBlock}${tailBlock}`;\n }\n}\n\n/** A finished delegate whose answer an aborted run dropped from pi's queue. */\nexport type DroppedAnswer = {\n name: string;\n outcome?: string;\n elapsedMs?: number;\n /** The local copy of the follow-up message, if writing it worked. */\n copy?: string;\n sessionFile?: string;\n};\n\n/** Where dropped answers are copied: `<mu cache dir>/delegate-answers`.\n * Cache, not state: the delegate's pi session file keeps the answer. */\nexport function droppedAnswersDir(): string {\n return join(defaultCacheDir(), \"delegate-answers\");\n}\n\n/**\n * The note left in the conversation when Escape drops queued answers:\n * one line per delegate, pointing at the local copy and the delegate's\n * own session file. Pure.\n */\nexport function droppedNote(dropped: readonly DroppedAnswer[]): string {\n const n = dropped.length;\n const lines = dropped.map((d) => {\n const how = [\n d.outcome ?? \"no result\",\n d.elapsedMs !== undefined ? formatElapsed(d.elapsedMs) : undefined,\n ]\n .filter((x) => x !== undefined)\n .join(\", \");\n const where = [\n d.copy ? `answer: ${d.copy}` : undefined,\n d.sessionFile ? `session: ${d.sessionFile}` : undefined,\n ].filter((x) => x !== undefined);\n if (where.length === 0) where.push(`read: mu agent read ${d.name} -n 50 -w ${W}`);\n return `- ${W}/${d.name} (${how}) ${where.join(\" · \")}`;\n });\n return [\n `The interrupt dropped ${n} delegate answer${n === 1 ? \"\" : \"s\"} before ${n === 1 ? \"it\" : \"they\"} arrived:`,\n ...lines,\n \"The answer file holds the message that would have arrived; in a session file the answer is the last assistant message.\",\n ].join(\"\\n\");\n}\n\n/** Where a delegate's answer is recorded: a task, resolved by `mu task show`. */\nexport type RecordTarget = { workstream: string; task: string };\n\n/** Cap on a recorded note, in chars. */\nexport const RECORD_NOTE_MAX = 4000;\n/** Without a VERDICT line, this much of the answer's end is recorded. */\nexport const RECORD_FALLBACK_TAIL = 1500;\n\nconst VERDICT_LINE = /^[\\s>*_`-]*VERDICT:/;\nconst EVIDENCE_LINE = /^[\\s>*_`-]*EVIDENCE:/;\n\n/**\n * The note a delegate's answer leaves on the task it judged. Pure. A done\n * answer keeps its last `VERDICT:` line and every `EVIDENCE:` line after\n * it (else its tail, marked NO VERDICT LINE); any other outcome records\n * the gap.\n */\nexport function recordNote(\n label: string,\n name: string,\n outcome: string | undefined,\n lastText: string | undefined,\n elapsedMs: number,\n): string {\n if (outcome !== \"done\" || !lastText?.trim())\n return `REFUTER ${label}: no verdict (${outcome === \"done\" ? \"empty\" : (outcome ?? \"no result\")})`;\n const lines = lastText.trimEnd().split(\"\\n\");\n let at = -1;\n for (let i = lines.length - 1; i >= 0 && at < 0; i--)\n if (VERDICT_LINE.test(lines[i] ?? \"\")) at = i;\n const body =\n at >= 0\n ? [lines[at] ?? \"\", ...lines.slice(at + 1).filter((l) => EVIDENCE_LINE.test(l))].join(\"\\n\")\n : `NO VERDICT LINE: ${lastText.trimEnd().slice(-RECORD_FALLBACK_TAIL)}`;\n const note = `REFUTER ${label} (${name}, ${formatElapsed(elapsedMs)}):\\n${body}`;\n const mark = \"\\n[truncated]\";\n return note.length <= RECORD_NOTE_MAX\n ? note\n : note.slice(0, RECORD_NOTE_MAX - mark.length) + mark;\n}\n\n/** A label → agent-name stem: lowercase, [a-z0-9-], ≤ 20 chars. */\nexport function labelStem(label: unknown): string | undefined {\n if (typeof label !== \"string\") return undefined;\n const stem = label\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .slice(0, 20)\n .replace(/-+$/, \"\");\n return stem || undefined;\n}\n\n/** Model values that need no shell quoting inside a `--command` string. */\nconst MODEL_BARE_RE = /^[A-Za-z0-9._:/@+=-]+$/;\n\n/**\n * Forgive the usual slips in a `model` value: surrounding quotes or\n * backticks, a pasted `--model ` / `--model=` prefix, stray whitespace.\n * Anything else (brackets as in `gpt-6.1-sol[1m]`, odd provider ids) is\n * kept and shell-quoted by `modelCommand`, so pi gets to judge the id.\n * Returns undefined for an empty value or one with inner whitespace,\n * which no model id has.\n */\nexport function normalizeModel(raw: unknown): string | undefined {\n if (typeof raw !== \"string\") return undefined;\n let m = raw.trim();\n for (let prev = \"\"; prev !== m; ) {\n prev = m;\n m = m\n .replace(/^--model(?:=|\\s+)/, \"\")\n .replace(/^([\"'`])(.*)\\1$/s, \"$2\")\n .trim();\n }\n return m && !/\\s/.test(m) ? m : undefined;\n}\n\nfunction shellArg(s: string): string {\n return MODEL_BARE_RE.test(s) ? s : `'${s.replace(/'/g, \"'\\\\''\")}'`;\n}\n\n/**\n * The command a delegate with `model` runs: the cli key's command\n * (`$MU_<KEY>_COMMAND`, else the key itself, as `resolveCliCommand` in\n * src/agents/spawn.ts does) plus `--model <model>`. Inlined: the extension\n * bundles standalone and spawn.ts pulls in the DB.\n */\nexport function modelCommand(\n cli: string,\n model: string,\n env: NodeJS.ProcessEnv = process.env,\n): string {\n const override = env[`MU_${cli.toUpperCase().replace(/-/g, \"_\")}_COMMAND`];\n const base = override && override.trim() !== \"\" ? override.trim() : cli;\n return `${base} --model ${shellArg(model)}`;\n}\n\n/**\n * One delegate this pi waits on. `cancelling` is set while a cancel's abort\n * is in flight: the abort itself settles the run, so a wait resolving then\n * is parked in `parked` instead of delivered, and delivered after all if\n * the abort fails.\n */\ntype Inflight = {\n abort: AbortController;\n /** The delegate's pi session file, reported by the spawn's send. */\n sessionFile?: string;\n record?: { target: RecordTarget; label: string };\n cancelling: boolean;\n parked?: () => Promise<void>;\n};\n\n/** A call past the cap, waiting for a slot. Its delegate name is picked\n * at spawn, so the queue hands out its own handle (`queued-3`). */\ntype Queued = {\n handle: string;\n params: Record<string, unknown>;\n ctx: DelegateCtx | undefined;\n record?: RecordTarget;\n};\n\n/** What the rest of the extension may ask the delegate side. */\nexport interface DelegateHandle {\n /** A delegate answer is being delivered or waits in pi's follow-up\n * queue: it will resume the agent itself. pi's hasPendingMessages()\n * does not count custom follow-ups, so this is the only signal. */\n answerPending(): boolean;\n}\n\nexport function registerDelegate(\n pi: MuDelegateApi,\n run: MuRunner = defaultRunner(),\n): DelegateHandle {\n if (!delegateEnabled()) return { answerPending: () => false };\n const inflight = new Map<string, Inflight>();\n /** Calls past the cap check whose delegate is not yet in `inflight`. */\n let starting = 0;\n /** Calls past the cap, FIFO, at most `DELEGATE_QUEUE_FACTOR * delegateMax()` long. */\n const queue: Queued[] = [];\n let queueSeq = 0;\n /** Delegates that settled on an error, pane kept: counted in the footer\n * until the model closes or re-issues them (no call to action). */\n const failed = new Set<string>();\n /** When pruneFailed last listed agents (0: never). */\n let lastPruneAt = 0;\n /** Delegates that finished whose follow-up has not entered the\n * conversation: being delivered, or queued behind a running turn.\n * Keyed by a per-delivery id carried in the message's details, and\n * cleared on that message's message_start. `queued` says whether\n * pi.sendMessage has returned, i.e. the message sits in pi's queue;\n * the rest is what an interrupt needs to point at the answer. */\n const arriving = new Map<\n number,\n { queued: boolean; name: string; content?: string } & Omit<DroppedAnswer, \"copy\">\n >();\n let deliverySeq = 0;\n // The ctx of the latest tool call: answers settle outside any call, so\n // the footer is refreshed through the last ctx pi handed us.\n let ui: DelegateCtx[\"ui\"];\n let lastPending = 0;\n /** Running, starting and queued: every delegate whose answer is still\n * to come back here. Failed panes have answered, so they do not count. */\n const reportPending = () => {\n const count = inflight.size + starting + queue.length;\n if (count === lastPending) return;\n lastPending = count;\n try {\n pi.events.emit(PENDING_CHANNEL, { source: DELEGATE_TOOL, count });\n } catch {\n // a listener's fault must not cost a delegate its answer\n }\n };\n // Every change to the counts already refreshes the footer, so the\n // report rides along rather than being a second set of call sites.\n const showStatus = () => {\n reportPending();\n try {\n ui?.setStatus?.(\n DELEGATE_STATUS_KEY,\n delegateStatus(inflight.size, starting, queue.length, failed.size, arriving.size),\n );\n } catch {\n // stale ctx after a session switch: the footer is decoration\n }\n };\n const track = (ctx: DelegateCtx | undefined) => {\n if (ctx?.hasUI !== false && ctx?.ui) ui = ctx.ui;\n };\n /** The follow-up for `delivery` is in pi's queue now. */\n const markQueued = (delivery: number) => {\n const a = arriving.get(delivery);\n if (a) a.queued = true;\n };\n /** Copy a dropped answer under the mu cache dir; undefined if that fails. */\n const saveCopy = (name: string, content: string, kind = \"\"): string | undefined => {\n try {\n const dir = droppedAnswersDir();\n mkdirSync(dir, { recursive: true });\n const stamp = new Date().toISOString().replace(/[:.]/g, \"-\");\n const path = join(dir, `${stamp}_${name}${kind}.md`);\n writeFileSync(path, `${content}\\n`);\n return path;\n } catch {\n return undefined;\n }\n };\n /** Copy a delegate's last assistant text so far (from its session\n * file) next to the dropped answers; undefined when it wrote none. */\n const partialCopy = (name: string, sessionFile: string): string | undefined => {\n const text = lastAssistantTextIn(sessionFile);\n return text ? saveCopy(name, text, \".partial\") : undefined;\n };\n /** Drop a delegate from the in-flight set, start the next queued call\n * into the freed slot, and refresh the footer. */\n const forget = (name: string) => {\n inflight.delete(name);\n drain();\n showStatus();\n };\n /** Start queued calls while there is a free slot. A queued call's tool\n * call has already returned, so a failed start becomes a follow-up. */\n function drain(): void {\n while (queue.length > 0 && inflight.size + starting < delegateMax()) {\n const q = queue.shift();\n if (!q) break;\n starting++; // held until start() takes over the slot\n void start(q.params, undefined, q.ctx, q.handle, q.record).then(\n () => {},\n (e: unknown) => {\n void Promise.resolve(\n pi.sendMessage(\n {\n customType: DELEGATE_MESSAGE_TYPE,\n content: `Queued delegate ${q.handle} could not start: ${e instanceof Error ? e.message : String(e)}`,\n display: true,\n details: { name: q.handle, workstream: W, outcome: null, closed: false },\n },\n { deliverAs: \"followUp\", triggerTurn: true },\n ),\n ).catch(() => {});\n },\n );\n }\n }\n\n const mu = run;\n const json = (r: MuResult): Record<string, unknown> | undefined => {\n try {\n const v: unknown = JSON.parse(r.stdout);\n return typeof v === \"object\" && v !== null ? (v as Record<string, unknown>) : undefined;\n } catch {\n return undefined;\n }\n };\n const failure = (what: string, r: MuResult) =>\n new Error(`${what} failed (exit ${r.code}): ${(r.stderr || r.stdout).trim()}`);\n\n /** A failed delegate whose pane is gone (closed from bash) leaves the\n * footer. Off the call's path: only a footer count rides on it. */\n function pruneFailed(): void {\n if (failed.size === 0) return;\n // Only the footer count depends on this listing (~150 ms of CPU per\n // `mu agent list`): refresh it at most once per PRUNE_FAILED_MS.\n const now = Date.now();\n if (now - lastPruneAt < PRUNE_FAILED_MS) return;\n lastPruneAt = now;\n void mu([\"agent\", \"list\", \"-w\", W, \"--json\"]).then((r) => {\n const agents = json(r)?.agents;\n if (!Array.isArray(agents)) return;\n const taken = new Set(agents.map((a: unknown) => (a as { name?: unknown }).name));\n for (const f of [...failed]) if (!taken.has(f)) failed.delete(f);\n showStatus();\n });\n }\n\n /**\n * Spawn the delegate and send it the task in ONE mu call (`spawn\n * --next-free --send`): mu picks the free name under its spawn lock, so\n * parallel calls get distinct names with no `agent list` first. Returns\n * the name and the send's `runs`, the exact wait baseline.\n */\n async function spawn(\n params: Record<string, unknown>,\n text: string,\n cwd: string | undefined,\n signal?: AbortSignal,\n ): Promise<{\n name: string;\n runs: number;\n attach?: string;\n workspace?: string;\n sessionFile?: string;\n }> {\n signal?.throwIfAborted();\n pruneFailed();\n const stem = labelStem(params.label);\n // A label names the delegate (delegate-review, then delegate-review-2);\n // without one it is numbered (delegate-1, delegate-2).\n const base = stem ? `delegate-${stem}` : \"delegate-1\";\n const args = [\"agent\", \"spawn\", base, \"-w\", W, \"--next-free\", \"--send\", text, \"--json\"];\n if (params.workspace === true) args.push(\"--workspace\");\n else if (cwd) args.push(\"--cwd\", cwd);\n const cli = typeof params.cli === \"string\" && params.cli ? params.cli : undefined;\n if (cli) args.push(\"--cli\", cli);\n if (typeof params.model === \"string\" && params.model)\n args.push(\"--command\", modelCommand(cli ?? \"pi\", params.model));\n const r = await mu(args);\n const out = json(r);\n const spawned = (out?.agent as { name?: unknown } | undefined)?.name;\n // No agent in the reply: the spawn itself failed, nothing is up.\n if (typeof spawned !== \"string\") throw failure(\"mu agent spawn\", r);\n const name = spawned;\n if (signal?.aborted) {\n // The user cancelled while the pane came up: take it down again.\n await mu([\"agent\", \"close\", name, \"-w\", W]);\n signal.throwIfAborted();\n }\n if (out?.ctl !== \"ok\") {\n throw new Error(\n `${W}/${name} spawned but its control socket is ${String(out?.ctl)}, so its answer cannot come back. Pane kept; close it with: mu agent close ${name} -w ${W}`,\n );\n }\n const sent = out.send as\n | { ok?: unknown; error?: unknown; runs?: unknown; message?: unknown; sessionFile?: unknown }\n | undefined;\n if (sent?.ok !== true && sent?.error === \"AgentSendIndeterminateError\") {\n // The prompt may already be running: keep the pane, never auto-retry.\n const why = typeof sent.message === \"string\" ? sent.message : \"no reply\";\n throw new Error(\n `mu agent send to ${W}/${name}: delivery unknown (${why}). Pane kept; do NOT resend blindly. Check with: mu agent read ${name} -w ${W} -n 20 (or attach), then close it with: mu agent close ${name} -w ${W}`,\n );\n }\n if (sent?.ok !== true) {\n // Nothing reached it: the pane is just an idle pi. Take it down.\n const c = await mu([\"agent\", \"close\", name, \"-w\", W]);\n const pane =\n c.code === 0 ? \"Pane closed.\" : `Pane kept; close it with: mu agent close ${name} -w ${W}`;\n const why = typeof sent?.message === \"string\" ? sent.message : (r.stderr || r.stdout).trim();\n throw new Error(`mu agent send to ${W}/${name} failed (exit ${r.code}): ${why}. ${pane}`);\n }\n const steps = Array.isArray(out.nextSteps) ? out.nextSteps : [];\n const attach = steps\n .map((s: unknown) => s as { intent?: unknown; command?: unknown })\n .find((s) => s.intent === \"Attach the pane\")?.command;\n const wsPath = (out.workspace as { path?: unknown } | null | undefined)?.path;\n return {\n name,\n // A pi just spawned has settled no run, so 0 is exact when an older\n // extension's reply carries no runs.\n runs: typeof sent.runs === \"number\" ? sent.runs : 0,\n ...(typeof attach === \"string\" ? { attach } : {}),\n ...(typeof wsPath === \"string\" ? { workspace: wsPath } : {}),\n ...(typeof sent.sessionFile === \"string\" ? { sessionFile: sent.sessionFile } : {}),\n };\n }\n\n /** The note label: the caller's label, else the delegate's name. */\n const recordLabel = (params: Record<string, unknown>, name: string) =>\n typeof params.label === \"string\" && params.label.trim() ? params.label.trim() : name;\n\n /** Check `record` names a real task, before anything spawns. */\n async function resolveRecord(raw: unknown): Promise<RecordTarget | undefined> {\n if (raw === undefined) return undefined;\n const r = raw as { task?: unknown; workstream?: unknown } | null;\n const task = typeof r?.task === \"string\" ? r.task.trim() : \"\";\n if (!task) throw new Error(\"mu_delegate: record.task must name a task\");\n const ws = typeof r?.workstream === \"string\" ? r.workstream.trim() : \"\";\n // Without a workstream, mu resolves it as any verb does (<ws>/<task>, $MU_SESSION, tmux).\n const shown = await mu([\"task\", \"show\", task, ...(ws ? [\"-w\", ws] : []), \"--json\"]);\n const out = json(shown);\n const t = out?.task as { name?: unknown; workstreamName?: unknown } | undefined;\n if (shown.code !== 0 || typeof t?.name !== \"string\" || typeof t.workstreamName !== \"string\") {\n const why =\n typeof out?.message === \"string\" ? out.message : (shown.stderr || shown.stdout).trim();\n throw new Error(\n `mu_delegate: record task ${ws ? `${ws}/` : \"\"}${task} not found (exit ${shown.code}): ${why}. Nothing spawned.`,\n );\n }\n return { workstream: t.workstreamName, task: t.name };\n }\n\n /** Write one note on the record task; the follow-up's line about it. */\n async function writeRecord(rec: RecordTarget, name: string, text: string): Promise<string> {\n const where = `${rec.workstream}/${rec.task}`;\n try {\n const r = await mu([\"task\", \"note\", rec.task, \"-w\", rec.workstream, \"--author\", name, text]);\n if (r.code === 0) return `Recorded on ${where} as a note.`;\n return `Recording on ${where} failed (exit ${r.code}): ${(r.stderr || r.stdout).trim()}. Record it yourself.`;\n } catch (e) {\n return `Recording on ${where} failed: ${e instanceof Error ? e.message : String(e)}. Record it yourself.`;\n }\n }\n\n async function deliver(\n name: string,\n wait: MuResult,\n keep: boolean,\n extras: MessageExtras,\n delivery: number,\n record?: { target: RecordTarget; label: string },\n ) {\n const agent = (json(wait)?.agents as WaitAgent[] | undefined)?.[0];\n const outcome = agent?.outcome;\n const tail =\n outcome === \"done\" || outcome === \"timeout\" || outcome === \"pending\" || outcome === \"error\"\n ? undefined\n : (await mu([\"agent\", \"read\", name, \"-n\", \"50\", \"-w\", W])).stdout;\n // Close only after a clean finish: a died or timed-out pane is evidence.\n let pane: PaneFate = { closed: false, why: \"keep: true\" };\n let closing: Promise<MuResult> | undefined;\n if (outcome === \"blocked\") pane = { closed: false, why: \"waiting on a dialog\" };\n else if (outcome !== \"done\" && outcome !== \"empty\")\n pane = { closed: false, why: \"kept as evidence\" };\n else if (!keep) closing = mu([\"agent\", \"close\", name, \"-w\", W]);\n // The note never depends on the close, so the two mu calls overlap.\n const recording = record\n ? writeRecord(\n record.target,\n name,\n recordNote(record.label, name, outcome, agent?.lastText, extras.elapsedMs ?? 0),\n )\n : undefined;\n const [closed, recorded] = await Promise.all([closing, recording]);\n if (closed)\n pane =\n closed.code === 0\n ? { closed: true }\n : { closed: false, why: `close refused: ${(closed.stderr || closed.stdout).trim()}` };\n if (outcome === \"error\" && !pane.closed) {\n failed.add(name);\n showStatus();\n }\n // No final answer: point at the transcript, and copy what it wrote so\n // far. A blocked run is mid-flight: no partial copy, which could read\n // as its answer.\n if (outcome !== \"done\") {\n const sessionFile = agent?.sessionFile ?? extras.sessionFile;\n const partial =\n sessionFile && outcome !== \"blocked\" ? partialCopy(name, sessionFile) : undefined;\n extras = {\n ...extras,\n ...(sessionFile ? { sessionFile } : {}),\n ...(partial ? { partial } : {}),\n };\n }\n const message = delegateMessage(name, agent, pane, { ...extras, ...(tail ? { tail } : {}) });\n const content = recorded ? `${message}\\n\\n${recorded}` : message;\n const a = arriving.get(delivery);\n if (a)\n Object.assign(a, {\n content,\n ...(outcome ? { outcome } : {}),\n ...(extras.elapsedMs !== undefined ? { elapsedMs: extras.elapsedMs } : {}),\n ...(agent?.sessionFile ? { sessionFile: agent.sessionFile } : {}),\n });\n await pi.sendMessage(\n {\n customType: DELEGATE_MESSAGE_TYPE,\n content,\n display: true,\n details: {\n name,\n workstream: W,\n outcome: outcome ?? null,\n closed: pane.closed,\n answer: outcome === \"done\" ? (agent?.lastText ?? null) : null,\n elapsedMs: extras.elapsedMs ?? null,\n workspace: extras.workspace ?? null,\n sessionFile: agent?.sessionFile ?? extras.sessionFile ?? null,\n partial: extras.partial ?? null,\n delivery,\n },\n },\n { deliverAs: \"followUp\", triggerTurn: true },\n );\n }\n\n /** Spawn, send, and watch one delegate. The caller holds one\n * `starting` slot; it is released once the delegate is in `inflight`\n * (or on failure). Returns the tool result text. */\n async function start(\n params: Record<string, unknown>,\n signal: AbortSignal | undefined,\n ctx: DelegateCtx | undefined,\n queuedAs?: string,\n record?: RecordTarget,\n ): Promise<ToolResult> {\n let slotHeld = true;\n const freeSlot = () => {\n if (slotHeld) {\n starting--;\n showStatus();\n }\n slotHeld = false;\n };\n showStatus(); // the footer moves at once, before the pane exists\n try {\n const task = typeof params.task === \"string\" ? params.task.trim() : \"\";\n const brief = typeof params.brief === \"string\" ? params.brief.trim() : \"\";\n const keep = params.keep === true;\n const t = params.timeout;\n if (t !== undefined && !(typeof t === \"number\" && Number.isFinite(t) && t > 0))\n throw new Error(\n `mu_delegate: timeout must be a positive number of seconds (got ${JSON.stringify(t)})`,\n );\n const timeoutS = typeof t === \"number\" ? Math.ceil(t) : DELEGATE_TIMEOUT_S;\n // Without --cwd the pane inherits the mux session's start dir (wherever\n // the FIRST scratch spawn ran), and a missing dir silently becomes\n // $HOME: pin it to the caller's and check it exists.\n let cwd: string | undefined;\n if (params.workspace !== true) {\n cwd =\n typeof params.cwd === \"string\" && params.cwd ? params.cwd : (ctx?.cwd ?? process.cwd());\n if (!isDir(cwd)) throw new Error(`mu_delegate: cwd ${cwd} is not a directory`);\n }\n const { name, runs, attach, workspace, sessionFile } = await spawn(\n params,\n brief ? `${brief}\\n\\n${task}` : task,\n cwd,\n signal,\n );\n const entry: Inflight = {\n abort: new AbortController(),\n cancelling: false,\n ...(sessionFile ? { sessionFile } : {}),\n ...(record ? { record: { target: record, label: recordLabel(params, name) } } : {}),\n };\n inflight.set(name, entry);\n freeSlot(); // now counted in inflight\n showStatus();\n const started = Date.now();\n // The send's `runs` is pi's count before this prompt: waiting past it\n // catches the run even if it settled before this wait started.\n const waiting = mu(\n [\n \"agent\",\n \"wait\",\n name,\n \"-w\",\n W,\n \"--json\",\n \"--timeout\",\n String(timeoutS),\n \"--after-runs\",\n String(runs),\n ],\n entry.abort.signal,\n );\n const settle = async (r: MuResult) => {\n const delivery = ++deliverySeq;\n arriving.set(delivery, { queued: false, name });\n forget(name);\n try {\n await deliver(\n name,\n r,\n keep,\n {\n timeoutS,\n elapsedMs: Date.now() - started,\n ...(queuedAs ? { queuedAs } : {}),\n ...(attach ? { attach } : {}),\n ...(workspace ? { workspace } : {}),\n ...(entry.sessionFile ? { sessionFile: entry.sessionFile } : {}),\n },\n delivery,\n entry.record,\n );\n markQueued(delivery);\n } catch (e) {\n // A throw here would be an unhandled rejection and a lost answer.\n const content = `Delegate ${W}/${name} settled, but delivering its answer failed: ${e instanceof Error ? e.message : String(e)}. Read it with: mu agent read ${name} -n 50 -w ${W}`;\n const a = arriving.get(delivery);\n if (a) a.content = content;\n await Promise.resolve(\n pi.sendMessage(\n {\n customType: DELEGATE_MESSAGE_TYPE,\n content,\n display: true,\n details: { name, workstream: W, outcome: null, closed: false, delivery },\n },\n { deliverAs: \"followUp\", triggerTurn: true },\n ),\n ).then(\n () => markQueued(delivery),\n () => {\n // Nothing will arrive: stop counting it.\n arriving.delete(delivery);\n showStatus();\n },\n );\n }\n };\n void waiting.then(async (r) => {\n if (inflight.get(name) !== entry) return; // cancelled or shut down\n if (entry.cancelling) entry.parked = () => settle(r);\n else await settle(r);\n });\n const lines = [\n `Delegated to ${W}/${name}. Its answer arrives as a follow-up message when it finishes; do not wait or poll.`,\n workspace ? `Workspace: ${workspace}` : undefined,\n attach ? `Attach: ${attach}` : undefined,\n `Cancel: ${DELEGATE_CANCEL_TOOL} { name: \"${name}\" }`,\n ].filter((x) => x !== undefined);\n return {\n content: [{ type: \"text\", text: lines.join(\"\\n\") }],\n details: {\n name,\n workstream: W,\n attach: attach ?? null,\n workspace: workspace ?? null,\n keep,\n },\n };\n } finally {\n // A start that threw frees its slot here, and a call queued while it\n // was starting must take that slot: drain whether queued or direct.\n freeSlot();\n drain();\n }\n }\n\n pi.registerTool({\n name: DELEGATE_TOOL,\n label: \"mu delegate\",\n description: `Subagent: run one self-contained task in a fresh pi agent (its own mux pane in mu's ${W} workstream) while you keep working. Use it whenever you would reach for a subagent: research, a review, a draft, an investigation, or a refuter of a claim, plan or fix before you act on it; call it several times to fan out in parallel (at most ${delegateMax()} run at once; up to ${DELEGATE_QUEUE_FACTOR * delegateMax()} more are queued and start as slots free). The subagent starts with no context, in your working directory: put everything it needs in task. The call returns at once and the answer arrives later as a follow-up message: carry on with other work, or end your turn if your next step needs the answer (the follow-up resumes you). The pane closes after a clean finish; keep: true leaves it open. When the check judges a mu task, set record so its verdict lands on that task; leave it out when there is no task.`,\n promptSnippet:\n \"Subagent: delegate a self-contained task to a background pi agent; its answer arrives later as a follow-up\",\n parameters: {\n type: \"object\",\n properties: {\n task: { type: \"string\", description: \"The complete task, with all context it needs\" },\n label: {\n type: \"string\",\n description:\n \"Short label naming the delegate, e.g. 'review' → delegate-review. Use one per subtask when fanning out.\",\n },\n brief: {\n type: \"string\",\n description:\n \"Optional standing role or rules, sent before the task, e.g. 'You are a reviewer; read only.' The rules are instructions, not enforced. The job itself goes in task.\",\n },\n cwd: {\n type: \"string\",\n description:\n \"Working directory for the delegate (default: yours; ignored with workspace)\",\n },\n timeout: {\n type: \"number\",\n exclusiveMinimum: 0,\n description: `Seconds to wait for the answer (default ${DELEGATE_TIMEOUT_S}). On timeout you get a \"still running\" follow-up instead of the answer, and the answer will not arrive later; the subagent keeps running in its pane.`,\n },\n workspace: {\n type: \"boolean\",\n description:\n \"For tasks that edit files: its own VCS checkout (jj workspace / git worktree / sl share) branched from the current commit. The result and follow-up name the path; changes stay there until you merge them. This isolates repository edits only: the subagent runs as you, with your files, environment and network.\",\n },\n cli: {\n type: \"string\",\n description:\n \"Agent CLI key (default pi). Only keys with $MU_<KEY>_COMMAND set in pi's environment exist; to pick a model, use model instead.\",\n },\n model: {\n type: \"string\",\n description:\n \"Model for the subagent, passed to pi as --model (e.g. 'sonnet', '<provider>/<model>:high' copied from `pi --list-models`); appended to the cli's command. Default: the cli's own model. Use it to vary models across a review panel.\",\n },\n keep: {\n type: \"boolean\",\n description: \"Keep the pane after it finishes, to talk to it again\",\n },\n record: {\n type: \"object\",\n description:\n \"When the answer arrives, write its VERDICT/EVIDENCE onto this task as a note (for a check that judges a mu task; omit with no task); task may be <ws>/<task>.\",\n properties: {\n task: { type: \"string\" },\n workstream: { type: \"string\" },\n },\n required: [\"task\"],\n additionalProperties: false,\n },\n },\n required: [\"task\"],\n additionalProperties: false,\n },\n async execute(_id, params, signal, _onUpdate, ctx) {\n track(ctx);\n const task = typeof params.task === \"string\" ? params.task.trim() : \"\";\n if (!task) throw new Error(\"mu_delegate needs a non-empty task\");\n const t = params.timeout;\n if (t !== undefined && !(typeof t === \"number\" && Number.isFinite(t) && t > 0))\n throw new Error(\n `mu_delegate: timeout must be a positive number of seconds (got ${JSON.stringify(t)})`,\n );\n if (params.workspace !== true) {\n const cwd =\n typeof params.cwd === \"string\" && params.cwd ? params.cwd : (ctx?.cwd ?? process.cwd());\n if (!isDir(cwd)) throw new Error(`mu_delegate: cwd ${cwd} is not a directory`);\n }\n if (params.model !== undefined && params.model !== \"\") {\n const m = normalizeModel(params.model);\n if (!m)\n throw new Error(\n `mu_delegate: model must be one pi model id like 'provider/id:thinking', as listed by \\`pi --list-models\\` (got ${JSON.stringify(params.model)}); omit it for the cli's default`,\n );\n params = { ...params, model: m };\n }\n const record = await resolveRecord(params.record);\n // Count slots synchronously, before any await: parallel calls in one\n // turn all run this line before the first spawn returns.\n const max = delegateMax();\n if (inflight.size + starting < max) {\n starting++;\n return start(params, signal, ctx, undefined, record);\n }\n // Full: queue up to DELEGATE_QUEUE_FACTOR caps' worth; past that, refuse.\n if (queue.length >= DELEGATE_QUEUE_FACTOR * max)\n throw new Error(\n `mu_delegate: ${inflight.size + starting} running and ${queue.length} queued (MU_DELEGATE_MAX=${max}). End your turn; issue the rest as answers arrive (each answer resumes you).`,\n );\n const handle = `queued-${++queueSeq}`;\n queue.push({\n handle,\n params: {\n ...params,\n cwd:\n typeof params.cwd === \"string\" && params.cwd ? params.cwd : (ctx?.cwd ?? process.cwd()),\n },\n ctx,\n ...(record ? { record } : {}),\n });\n showStatus();\n return {\n content: [\n {\n type: \"text\",\n text: `Queued as ${handle} (#${queue.length}; ${inflight.size + starting} running, MU_DELEGATE_MAX=${max}). It starts when a slot frees, and its answer arrives as a follow-up message like any delegate's; do not wait or poll. Cancel: ${DELEGATE_CANCEL_TOOL} { name: \"${handle}\" }`,\n },\n ],\n details: { name: handle, workstream: W, queued: true, position: queue.length },\n };\n },\n });\n\n pi.registerTool({\n name: DELEGATE_CANCEL_TOOL,\n label: \"mu delegate cancel\",\n description: `Stop a delegate started by ${DELEGATE_TOOL}: abort its turn and close its pane (keep: true leaves the pane open). No follow-up message is sent for it afterwards.`,\n parameters: {\n type: \"object\",\n properties: {\n name: { type: \"string\", description: \"Delegate name, e.g. delegate-1\" },\n keep: { type: \"boolean\", description: \"Leave the pane open after aborting\" },\n },\n required: [\"name\"],\n additionalProperties: false,\n },\n async execute(_id, params, _signal, _onUpdate, ctx) {\n track(ctx);\n const name = typeof params.name === \"string\" ? params.name : \"\";\n if (!name) throw new Error(\"mu_delegate_cancel needs a name\");\n const qi = queue.findIndex((q) => q.handle === name);\n if (qi >= 0) {\n const [q] = queue.splice(qi, 1);\n showStatus();\n const recorded = q?.record\n ? ` ${await writeRecord(q.record, name, recordNote(recordLabel(q.params, name), name, \"cancelled\", undefined, 0))}`\n : \"\";\n return {\n content: [\n { type: \"text\", text: `Dropped ${name} from the queue; it never started.${recorded}` },\n ],\n details: { name, workstream: W },\n };\n }\n const entry = inflight.get(name);\n if (entry) entry.cancelling = true;\n const ab = await mu([\"agent\", \"abort\", name, \"-w\", W]);\n if (ab.code !== 0) {\n // Not cancelled after all: keep waiting, or deliver what settled meanwhile.\n if (entry) {\n entry.cancelling = false;\n const parked = entry.parked;\n entry.parked = undefined;\n if (parked) void parked();\n }\n throw failure(`mu agent abort ${W}/${name}`, ab);\n }\n if (entry) {\n entry.abort.abort();\n forget(name);\n }\n failed.delete(name);\n let text = `Aborted ${W}/${name}.`;\n // What it wrote before the abort, and its transcript.\n const sessionFile = entry?.sessionFile;\n const partial = sessionFile ? partialCopy(name, sessionFile) : undefined;\n const evidence = evidenceLines({\n ...(sessionFile ? { sessionFile } : {}),\n ...(partial ? { partial } : {}),\n });\n if (entry?.record)\n text += ` ${await writeRecord(entry.record.target, name, recordNote(entry.record.label, name, \"cancelled\", undefined, 0))}`;\n if (params.keep === true) text += \" Pane kept.\";\n else {\n const c = await mu([\"agent\", \"close\", name, \"-w\", W]);\n text +=\n c.code === 0\n ? \" Pane closed.\"\n : ` Pane kept: close refused: ${(c.stderr || c.stdout).trim()}`;\n }\n if (evidence.length > 0) text += `\\n${evidence.join(\"\\n\")}`;\n return { content: [{ type: \"text\", text }], details: { name, workstream: W } };\n },\n });\n\n // A follow-up enters the conversation at its message_start: at once\n // when pi is idle, or when the running turn drains its follow-ups.\n pi.on(\"message_start\", (e) => {\n const m = (e as { message?: { role?: unknown; customType?: unknown; details?: unknown } })\n .message;\n if (m?.role !== \"custom\" || m.customType !== DELEGATE_MESSAGE_TYPE) return;\n const id = (m.details as { delivery?: unknown } | undefined)?.delivery;\n if (typeof id === \"number\" && arriving.delete(id)) showStatus();\n });\n\n // Escape clears pi's follow-up queue along with the run: answers that\n // were queued in it never arrive. Stop counting them, copy each to the\n // mu cache dir, and leave one line per answer in the conversation (no\n // turn: the model sees it with the user's next prompt). An answer\n // still being delivered is not in the queue yet and arrives as usual.\n pi.on(\"agent_settled\", (e) => {\n if ((e as { aborted?: unknown }).aborted !== true) return;\n const dropped: DroppedAnswer[] = [];\n for (const [id, a] of arriving) {\n if (!a.queued) continue;\n arriving.delete(id);\n dropped.push({\n name: a.name,\n ...(a.outcome ? { outcome: a.outcome } : {}),\n ...(a.elapsedMs !== undefined ? { elapsedMs: a.elapsedMs } : {}),\n ...(a.sessionFile ? { sessionFile: a.sessionFile } : {}),\n ...(a.content ? { copy: saveCopy(a.name, a.content) } : {}),\n });\n }\n if (dropped.length === 0) return;\n showStatus();\n void Promise.resolve(\n pi.sendMessage(\n {\n customType: DELEGATE_MESSAGE_TYPE,\n content: droppedNote(dropped),\n display: true,\n details: { dropped },\n },\n { triggerTurn: false },\n ),\n ).catch(() => {});\n });\n\n // The watchers die with this runtime (/reload, /new, quit): say which\n // delegates lose their callback, so none is lost silently. The names\n // are also in the tool results, and `mu agent wait` recovers them.\n pi.on(\"session_shutdown\", (_e, ctx) => {\n if (arriving.size > 0) {\n // Answers still being delivered or queued die with this runtime.\n arriving.clear();\n showStatus();\n }\n if (inflight.size === 0 && queue.length === 0) return;\n const names = [...inflight.keys()];\n const sessions = [...inflight].flatMap(([n, e]) =>\n e.sessionFile ? [`${n}: ${e.sessionFile}`] : [],\n );\n const never = queue.splice(0).map((q) => q.handle);\n for (const e of inflight.values()) e.abort.abort();\n inflight.clear();\n showStatus();\n ui = undefined;\n const parts: string[] = [];\n if (names.length > 0)\n parts.push(\n `${names.length} delegate${names.length === 1 ? \"\" : \"s\"} still running: ${names.join(\", \")}. Their answers will not come back here; use mu agent wait <name> -w ${W} --json.`,\n );\n if (sessions.length > 0) parts.push(`Sessions: ${sessions.join(\"; \")}.`);\n if (never.length > 0)\n parts.push(`${never.length} queued, never started: ${never.join(\", \")}. Re-issue them.`);\n const msg = parts.join(\" \");\n if (ctx?.hasUI && ctx.ui) ctx.ui.notify(msg, \"warning\");\n else process.stderr.write(`mu: ${msg}\\n`);\n });\n\n return { answerPending: () => arriving.size > 0 };\n}\n","// The mu state directory, resolved from builtins only so the CLI\n// bootstrap (src/main.ts) can locate its compile cache before it loads\n// any of the CLI graph. db.ts re-exports defaultStateDir.\n\nimport { homedir } from \"node:os\";\nimport { isAbsolute, join } from \"node:path\";\n\n/**\n * Resolve the canonical mu state directory:\n * MU_STATE_DIR > $XDG_STATE_HOME/mu (absolute only) > ~/.local/state/mu\n */\nexport function defaultStateDir(): string {\n if (process.env.MU_STATE_DIR) return process.env.MU_STATE_DIR;\n return join(xdgStateHome(homedir()), \"mu\");\n}\n\n/**\n * The mu cache directory, `$XDG_CACHE_HOME/mu` (absolute only) else\n * `~/.cache/mu`: files mu can lose at any time, such as copies of data\n * that lives elsewhere too.\n */\nexport function defaultCacheDir(): string {\n const xdg = process.env.XDG_CACHE_HOME;\n return join(xdg !== undefined && isAbsolute(xdg) ? xdg : join(homedir(), \".cache\"), \"mu\");\n}\n\n/** `$XDG_STATE_HOME`, or `<home>/.local/state` when it is unset, empty,\n * or relative: the XDG spec says such a value must be ignored, and a\n * relative one would scatter state across every cwd mu runs in. */\nexport function xdgStateHome(home: string): string {\n const xdg = process.env.XDG_STATE_HOME;\n return xdg !== undefined && isAbsolute(xdg) ? xdg : join(home, \".local\", \"state\");\n}\n","/**\n * mu pi extension: the keep-driving nudge (docs/specs/2026-10-03-keep-driving-nudge.md).\n *\n * An orchestrator that dispatched mu work and then ends its turn while\n * that work is still IN_PROGRESS gets ONE visible message quoting the\n * skill's keep-driving rule, and one continuation. If it stops again,\n * that stop stands. Not a goal loop: no re-check, no counter.\n *\n * Its only read is `mu task list --status IN_PROGRESS --json`, its only write `mu log --kind\n * nudge`; the armed set and fired flag are per-prompt scratch. The rule\n * text lives in skills/mu/SKILL.md between the keep-driving markers.\n *\n * The refute nudge: `mu task claim <id> --for` on a task whose notes\n * carry no line starting `REFUTER `, `VERDICT:` or `REFUTE-EXEMPT:`\n * (read with `mu task notes --json`) gets ONE visible message per prompt\n * listing those tasks. It informs, never continues; `review_*` tasks\n * are exempt (their brief is the fixed reviewer template).\n *\n * Its worker-side twin, the close nudge: a mu-spawned pi worker\n * ($MU_AGENT_NAME + $MU_WORKSTREAM) that settles while it still owns an\n * IN_PROGRESS task is told once to close it or say why not. Same\n * once-per-prompt rule and `MU_NUDGE=0` opt-out.\n *\n * None fire in a nested pi (mu-pi.ts decides at bind); close and refute\n * also skip a pi with no UI (`pi -p`, json), where nobody can answer.\n * None fire while a delegate answer is on its way (it resumes the agent\n * with the answer), and keep-driving and close skip an open dialog. A\n * held settle does not count as the prompt's one nudge.\n */\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { defaultRunner, type MuRunner } from \"./delegate.js\";\n\nexport const NUDGE_MESSAGE_TYPE = \"mu-keep-driving\";\nexport const NUDGE_LOG_KIND = \"nudge\";\nexport const CLOSE_NUDGE_MESSAGE_TYPE = \"mu-close-task\";\nexport const REFUTE_NUDGE_MESSAGE_TYPE = \"mu-refute-brief\";\nconst MARK_START = \"<!-- mu:keep-driving -->\";\nconst MARK_END = \"<!-- /mu:keep-driving -->\";\n/** Tasks named in the wait hint; the rest are counted, not listed. */\nconst WAIT_HINT_MAX = 8;\n\n/** The slice of pi's ExtensionContext the nudge reads. */\nexport type MuNudgeCtx = { mode?: string; hasUI?: boolean; hasPendingMessages?: () => boolean };\n\n/** The slice of pi's ExtensionAPI the nudge uses. */\nexport interface MuNudgeApi {\n on(\n event: \"tool_call\" | \"agent_before_settle\" | \"input\",\n handler: (event: unknown, ctx: MuNudgeCtx) => unknown,\n ): unknown;\n}\n\n/**\n * True while this pi is nested: it inherited a MU_CTL_SOCK another pi\n * serves (a `pi -p` run inside an agent's pane). Read at settle time,\n * since the bind decision lands in session_start, after registration.\n */\nexport type NestedCheck = () => boolean;\nconst notNested: NestedCheck = () => false;\n\n/**\n * Why this settle must not be nudged, read at settle time and again\n * after every awaited read: \"answer\" while a delegate answer is queued\n * or being delivered (it resumes the agent itself, and a continuation\n * would run before it; pi's hasPendingMessages() does not count custom\n * follow-ups), \"blocked\" while an extension dialog is open. undefined\n * when nothing holds the settle.\n */\nexport type SettleHold = (ctx?: MuNudgeCtx) => \"answer\" | \"blocked\" | undefined;\nconst noHold: SettleHold = () => undefined;\n\n/** A queued user message (pi's own count) or a held settle: either way the\n * next turn is already coming, so a continuation would run ahead of it. */\nexport function withQueuedInput(hold: SettleHold): SettleHold {\n return (ctx) => (ctx?.hasPendingMessages?.() ? \"answer\" : hold(ctx));\n}\n\n/** No one can answer a nudge: print or json mode. */\nfunction noUI(ctx: MuNudgeCtx | undefined): boolean {\n return ctx?.hasUI === false;\n}\n\n/** `MU_NUDGE=0` turns the nudge off. */\nexport function nudgeEnabled(env: NodeJS.ProcessEnv = process.env): boolean {\n return env.MU_NUDGE !== \"0\";\n}\n\n/** The keep-driving paragraph from SKILL.md, or undefined without the markers. */\nexport function keepDrivingRule(skillMd: string): string | undefined {\n const i = skillMd.indexOf(MARK_START);\n const j = skillMd.indexOf(MARK_END);\n if (i < 0 || j < i) return undefined;\n const text = skillMd.slice(i + MARK_START.length, j).trim();\n return text === \"\" ? undefined : text;\n}\n\n/** SKILL.md next to this file in either layout (source or dist/extension). */\nfunction readSkill(): string | undefined {\n for (const up of [\"..\", \"../..\"]) {\n const p = join(import.meta.dirname ?? \"\", up, \"skills\", \"mu\", \"SKILL.md\");\n if (existsSync(p)) return readFileSync(p, \"utf8\");\n }\n return undefined;\n}\n\n/** Leading `NAME=value` words: env assignments before the command. */\nconst ENV_ASSIGN = /^[A-Za-z_][A-Za-z0-9_]*=/;\n\n/** The args after `mu` when this segment runs mu (after any env\n * assignments), or undefined when it runs something else. */\nfunction muArgs(words: string[]): string[] | undefined {\n let at = 0;\n while (at < words.length && ENV_ASSIGN.test(words[at] ?? \"\")) at++;\n const cmd = words[at];\n if (cmd !== \"mu\" && !cmd?.endsWith(\"/mu\")) return undefined;\n return words.slice(at + 1);\n}\n\n/**\n * The workstreams a bash command dispatches mu work into, or undefined\n * when it dispatches nothing. Dispatch = `mu agent send|spawn`, or\n * `mu task claim <id> --for` (parsed by claimOf, as the refute nudge\n * does). `\"\"` stands for the default workstream (resolved by mu\n * itself: $MU_SESSION, then tmux).\n */\nexport function dispatchedWorkstreams(command: string): string[] | undefined {\n const found = new Set<string>();\n // One mu invocation per shell segment.\n for (const words of shellSegments(command)) {\n const args = muArgs(words);\n if (args === undefined) continue;\n const claim = claimOf(args);\n if (claim !== undefined) {\n if (claim.ws !== \"scratch\") found.add(claim.ws);\n continue;\n }\n if (args[0] !== \"agent\" || (args[1] !== \"send\" && args[1] !== \"spawn\")) continue;\n let ws = \"\";\n for (let k = 2; k < args.length; k++) {\n const w = args[k] ?? \"\";\n if (w === \"-w\" || w === \"--workstream\") ws = args[k + 1] ?? \"\";\n else if (w.startsWith(\"--workstream=\")) ws = w.slice(\"--workstream=\".length);\n }\n if (ws !== \"scratch\") found.add(ws);\n }\n return found.size > 0 ? [...found] : undefined;\n}\n\n/** Claim options that take a value; the task id is the first other positional. */\nconst CLAIM_VALUE_OPTS = new Set([\"--for\", \"-f\", \"-w\", \"--workstream\", \"--evidence\", \"--actor\"]);\n\n/** A heredoc body to skip: lines up to `delim` (leading tabs stripped with `<<-`). */\ntype Heredoc = { delim: string; strip: boolean };\n\n/**\n * The words of each shell segment. Quotes group words and are dropped;\n * `&&`, `||`, `;`, `|` and newlines split segments only outside\n * quotes, so a quoted `--evidence 'a | b'` stays one word. A\n * backslash-newline joins lines, and heredoc bodies are skipped: they\n * are data, not commands. A `<<<` here-string and a `<<` shift inside\n * `(( ))` arithmetic do not start a heredoc. As in bash, `((` is\n * arithmetic only when its matching close is `))`; otherwise it is\n * nested subshells, where `<<` is a heredoc. A `#` that starts a word\n * comments out the rest of the line.\n */\nexport function shellSegments(command: string): string[][] {\n const segs: string[][] = [];\n let words: string[] = [];\n let word: string | undefined;\n const heredocs: Heredoc[] = [];\n /** Index of the closing `)` of the current `(( ))` arithmetic, where `<<` is a shift. */\n let arithEnd = -1;\n const endWord = () => {\n if (word !== undefined) words.push(word);\n word = undefined;\n };\n const endSeg = () => {\n endWord();\n if (words.length > 0) segs.push(words);\n words = [];\n };\n /** Skip the pending heredoc bodies that start after the newline at `i`;\n * returns the index of the last newline consumed. */\n const skipHeredocs = (i: number): number => {\n for (const h of heredocs.splice(0)) {\n while (i < command.length) {\n const eol = command.indexOf(\"\\n\", i + 1);\n const end = eol < 0 ? command.length : eol;\n const line = command.slice(i + 1, end);\n i = end;\n if ((h.strip ? line.replace(/^\\t+/, \"\") : line) === h.delim) break;\n }\n }\n return i;\n };\n for (let i = 0; i < command.length; i++) {\n const c = command[i] ?? \"\";\n if (c === \"'\" || c === '\"') {\n const close = command.indexOf(c, i + 1);\n const end = close < 0 ? command.length : close;\n word = (word ?? \"\") + command.slice(i + 1, end);\n i = end;\n } else if (c === \"\\\\\" && command[i + 1] === \"\\n\") {\n i++; // line continuation: neither a word nor a segment break\n } else if (c === \"\\\\\" && i + 1 < command.length) {\n word = (word ?? \"\") + command[++i];\n } else if (c === \"#\" && word === undefined) {\n const eol = command.indexOf(\"\\n\", i);\n i = (eol < 0 ? command.length : eol) - 1; // a comment: the newline still ends the segment\n } else if (c === \"(\" && command[i + 1] === \"(\" && i > arithEnd) {\n arithEnd = arithmeticEnd(command, i);\n word = `${word ?? \"\"}((`;\n i++;\n } else if (command.startsWith(\"<<<\", i)) {\n endWord(); // a here-string: its word is data on the same line\n i += 2;\n } else if (c === \"<\" && command[i + 1] === \"<\" && i > arithEnd) {\n // `<<[-] DELIM`: the delimiter may be quoted; its body starts on the next line.\n endWord();\n const m = /^<<(-?)[ \\t]*('([^']*)'|\"([^\"]*)\"|[^\\s;&|<>()]+)/.exec(command.slice(i));\n if (!m) {\n i++;\n continue;\n }\n const delim = m[3] ?? m[4] ?? (m[2] ?? \"\").replace(/\\\\/g, \"\");\n heredocs.push({ delim, strip: m[1] === \"-\" });\n i += m[0].length - 1;\n } else if (c === \";\" || c === \"|\" || c === \"\\n\" || (c === \"&\" && command[i + 1] === \"&\")) {\n if (c !== \";\" && c !== \"\\n\" && command[i + 1] === c) i++;\n endSeg();\n if (c === \"\\n\" && heredocs.length > 0) i = skipHeredocs(i);\n } else if (/\\s/.test(c)) {\n endWord();\n } else {\n word = (word ?? \"\") + c;\n }\n }\n endSeg();\n return segs;\n}\n\n/**\n * For the `((` at `open`: the index of the `)` that closes it when the\n * matching close is a `))` pair (arithmetic), else -1 (nested\n * subshells, or unclosed). Bash decides `((` the same way.\n */\nfunction arithmeticEnd(command: string, open: number): number {\n let depth = 0;\n for (let i = open + 2; i < command.length; i++) {\n const c = command[i];\n if (c === \"'\" || c === '\"') {\n const close = command.indexOf(c, i + 1);\n if (close < 0) return -1;\n i = close;\n } else if (c === \"\\\\\") {\n i++;\n } else if (c === \"(\") {\n depth++;\n } else if (c === \")\") {\n if (depth > 0) depth--;\n else return command[i + 1] === \")\" ? i + 1 : -1;\n }\n }\n return -1;\n}\n\n/** The task a `mu task claim <id> --for` dispatches, from the args after\n * `mu`, as `{ ws, id }`; undefined for any other mu command. */\nfunction claimOf(args: string[]): { ws: string; id: string } | undefined {\n if (args[0] !== \"task\" || args[1] !== \"claim\") return undefined;\n let ws = \"\";\n let id: string | undefined;\n let isFor = false;\n for (let k = 2; k < args.length; k++) {\n const w = args[k] ?? \"\";\n const [opt, eq] = w.startsWith(\"--\") && w.includes(\"=\") ? w.split(\"=\", 2) : [w, undefined];\n if (opt === \"--for\" || opt === \"-f\") isFor = true;\n if (opt === \"-w\" || opt === \"--workstream\") ws = eq ?? args[k + 1] ?? \"\";\n if (CLAIM_VALUE_OPTS.has(opt ?? \"\")) {\n if (eq === undefined) k++;\n } else if (id === undefined && !w.startsWith(\"-\")) id = w;\n }\n if (!isFor || id === undefined) return undefined;\n const slash = id.indexOf(\"/\");\n if (slash >= 0) {\n if (ws === \"\") ws = id.slice(0, slash);\n id = id.slice(slash + 1);\n }\n return { ws, id };\n}\n\n/**\n * The tasks a bash command dispatches with `mu task claim <id> --for`,\n * as `{ ws, id }`. `ws` is `\"\"` for the default workstream; a qualified\n * `<ws>/<id>` splits. `scratch` is skipped, like dispatchedWorkstreams.\n */\nexport function dispatchedTasks(command: string): { ws: string; id: string }[] {\n const out: { ws: string; id: string }[] = [];\n for (const words of shellSegments(command)) {\n const args = muArgs(words);\n const claim = args === undefined ? undefined : claimOf(args);\n if (claim !== undefined && claim.ws !== \"scratch\") out.push(claim);\n }\n return out;\n}\n\ntype ListJson = { items?: { name?: string; workstreamName?: string }[] };\n\n/**\n * IN_PROGRESS task refs, one `mu task list --status IN_PROGRESS --json`\n * per workstream (newest first, as `mu state` listed them), all in flight at once. (`mu state` also lists tmux\n * panes and builds orphans and workspaces; this read needs none of it.\n * `task list` does not reap dead owners, so a task a ghost agent still\n * owns shows until the next `mu state` or `mu task wait` reaps it.)\n * A workstream named \"\" is the default one: no `-w`.\n */\nasync function inProgress(run: MuRunner, workstreams: string[]): Promise<string[] | undefined> {\n const results = await Promise.all(\n workstreams.map(async (w) => {\n const r = await run([\n \"task\",\n \"list\",\n \"--status\",\n \"IN_PROGRESS\",\n \"--json\",\n \"--sort\",\n \"recency\",\n ...(w ? [\"-w\", w] : []),\n ]);\n if (r.code !== 0) return undefined;\n try {\n const items = (JSON.parse(r.stdout) as ListJson).items ?? [];\n return items.flatMap((t) => (t.name ? [`${t.workstreamName ?? w}/${t.name}`] : []));\n } catch {\n return undefined;\n }\n }),\n );\n if (results.some((r) => r === undefined)) return undefined;\n // The default workstream (\"\") and an explicit name can be the same one:\n // dedupe by qualified ref, keeping first (most recent) position.\n return [...new Set(results.flatMap((r) => r ?? []))];\n}\n\n/** The nudge text: the rule verbatim, then the live count and the wait. */\nexport function nudgeText(rule: string, refs: string[]): string {\n const shown = refs.slice(0, WAIT_HINT_MAX).join(\" \");\n const more = refs.length > WAIT_HINT_MAX ? ` (+${refs.length - WAIT_HINT_MAX} more)` : \"\";\n return [\n `[mu] ${rule}`,\n \"\",\n `${refs.length} task(s) IN_PROGRESS. Next: mu task wait ${shown} --first --on-stall exit --json${more}`,\n ].join(\"\\n\");\n}\n\n/** Write a `mu log` breadcrumb without holding the settle for it: the\n * nudge's message does not depend on the log line. */\nfunction breadcrumb(run: MuRunner, args: string[]): void {\n void run(args).catch(() => {});\n}\n\n/** A nudge's settle result. `yielded` undoes the nudge's once-per-prompt\n * bookkeeping when the merge drops the result for a late hold. */\ntype SettleResult = { entries?: unknown[]; continue?: boolean; yielded?: () => void } | undefined;\ntype SettleHandler = (event: unknown, ctx: MuNudgeCtx) => unknown;\n\n/**\n * A view of `pi` whose `agent_before_settle` handlers run in PARALLEL\n * behind one real handler. pi awaits boundary handlers one after the\n * other, and each nudge awaits a mu subprocess, so three nudges held the\n * settle (and every `mu agent wait` on it) for the sum of their calls.\n * The merged result appends every handler's entries to the event's\n * (pi replaces `entries` with each handler's return, so separate\n * handlers dropped all but the last nudge) and continues when any asks.\n * A nudge that throws still reaches pi's extension-error path: after the\n * merged handler, one reporter handler per nudge rethrows that nudge's\n * error, so pi reports each failure (as it did when every nudge was its\n * own handler) while the other nudges' entries are still delivered.\n * The merge reads `hold` once more after the slowest nudge: a fast nudge\n * checked it long before, so an answer that queued meanwhile drops every\n * result (\"answer\") or the continuing ones (\"blocked\"), and each dropped\n * nudge may fire on a later settle.\n * Call `flush()` after registering the nudges.\n */\nexport function parallelSettle(\n pi: MuNudgeApi,\n hold: SettleHold = noHold,\n): { api: MuNudgeApi; flush(): void } {\n const handlers: SettleHandler[] = [];\n const api: MuNudgeApi = {\n on(event, handler) {\n if (event === \"agent_before_settle\") handlers.push(handler);\n else pi.on(event, handler);\n },\n };\n // Errors of the last settle, by handler index; each reporter takes its own.\n let errors: (unknown[] | undefined)[] = [];\n return {\n api,\n flush() {\n if (handlers.length === 0) return;\n pi.on(\"agent_before_settle\", async (event, ctx) => {\n errors = handlers.map(() => undefined);\n const results = await Promise.all(\n handlers.map(async (h, i) => {\n try {\n return (await h(event, ctx)) as SettleResult;\n } catch (err) {\n errors[i] = [err]; // reported by reporter i, after the merge\n return undefined;\n }\n }),\n );\n const late = hold(ctx);\n const fired = results.flatMap((r) => {\n if (r === undefined) return [];\n if (late === \"answer\" || (late === \"blocked\" && r.continue === true)) {\n r.yielded?.();\n return [];\n }\n return [r];\n });\n if (fired.length === 0) return undefined;\n const prior = (event as { entries?: unknown[] } | null)?.entries ?? [];\n return {\n entries: [...prior, ...fired.flatMap((r) => r.entries ?? [])],\n ...(fired.some((r) => r.continue === true) ? { continue: true } : {}),\n };\n });\n handlers.forEach((_, i) => {\n pi.on(\"agent_before_settle\", () => {\n const err = errors[i];\n errors[i] = undefined;\n if (err !== undefined) throw err[0];\n return undefined;\n });\n });\n },\n };\n}\n\nfunction outcomeOf(event: unknown): unknown {\n return typeof event === \"object\" && event !== null\n ? (event as { outcome?: unknown }).outcome\n : undefined;\n}\n\nfunction bashCommand(event: unknown): string | undefined {\n if (typeof event !== \"object\" || event === null) return undefined;\n const e = event as { toolName?: unknown; input?: { command?: unknown } };\n return e.toolName === \"bash\" && typeof e.input?.command === \"string\"\n ? e.input.command\n : undefined;\n}\n\nexport function registerNudge(\n pi: MuNudgeApi,\n run: MuRunner = defaultRunner(),\n skillMd: string | undefined = readSkill(),\n nested: NestedCheck = notNested,\n hold: SettleHold = noHold,\n): void {\n if (!nudgeEnabled()) return;\n const rule = skillMd === undefined ? undefined : keepDrivingRule(skillMd);\n if (rule === undefined) return; // no markers: nothing true to quote\n\n const armed = new Set<string>();\n let fired = false;\n\n pi.on(\"input\", () => {\n armed.clear();\n fired = false;\n });\n\n pi.on(\"tool_call\", (event) => {\n const cmd = bashCommand(event);\n if (cmd === undefined) return;\n for (const ws of dispatchedWorkstreams(cmd) ?? []) armed.add(ws);\n });\n\n pi.on(\"agent_before_settle\", async (event, ctx) => {\n if (fired || armed.size === 0 || nested() || hold(ctx)) return;\n if (outcomeOf(event) !== \"completed\") return; // Esc or an error: stop\n fired = true; // once per prompt, even if the check below fails\n const refs = await inProgress(run, [...armed]);\n if (refs === undefined || refs.length === 0) return;\n if (hold(ctx)) {\n fired = false; // the answer's turn settles again; nudge then if still due\n return;\n }\n const text = nudgeText(rule, refs);\n const logWs = [...armed].find((w) => w !== \"\");\n breadcrumb(run, [\n \"log\",\n ...(logWs ? [\"-w\", logWs] : []),\n \"--kind\",\n NUDGE_LOG_KIND,\n `keep-driving: ${refs.length} in progress`,\n ]);\n return {\n entries: [\n { type: \"custom_message\", customType: NUDGE_MESSAGE_TYPE, content: text, display: true },\n ],\n continue: true,\n yielded: () => {\n fired = false;\n },\n };\n });\n}\n\n/** The mu-spawned worker this pi runs as, or undefined outside mu. */\nexport function workerIdentity(\n env: NodeJS.ProcessEnv = process.env,\n): { agent: string; workstream: string } | undefined {\n const agent = env.MU_AGENT_NAME;\n const workstream = env.MU_WORKSTREAM;\n if (!agent || !workstream || workstream === \"scratch\") return undefined;\n return { agent, workstream };\n}\n\n/** IN_PROGRESS task names owned by `agent`, from `mu task owned-by --json`. */\nasync function ownedInProgress(\n run: MuRunner,\n agent: string,\n workstream: string,\n): Promise<string[] | undefined> {\n const r = await run([\"task\", \"owned-by\", agent, \"-w\", workstream, \"--json\"]);\n if (r.code !== 0) return undefined;\n try {\n const json = JSON.parse(r.stdout) as { items?: { name?: string; status?: string }[] };\n return (json.items ?? []).flatMap((t) =>\n t.status === \"IN_PROGRESS\" && t.name ? [t.name] : [],\n );\n } catch {\n return undefined;\n }\n}\n\n/** The close-nudge text: name each task and the two ways out. */\nexport function closeNudgeText(workstream: string, names: string[]): string {\n const close = names\n .map((n) => `mu task close ${n} -w ${workstream} --evidence \"<what you verified>\"`)\n .join(\"\\n \");\n return [\n `[mu] You are stopping while you still own ${names.map((n) => `${workstream}/${n}`).join(\", \")} (IN_PROGRESS).`,\n \"If the work is done and verified, close it now:\",\n ` ${close}`,\n \"If you are blocked or need an answer, say so in one line and stop; the orchestrator will read your pane.\",\n ].join(\"\\n\");\n}\n\nexport function registerCloseNudge(\n pi: MuNudgeApi,\n run: MuRunner = defaultRunner(),\n env: NodeJS.ProcessEnv = process.env,\n nested: NestedCheck = notNested,\n hold: SettleHold = noHold,\n): void {\n if (!nudgeEnabled(env)) return;\n const me = workerIdentity(env);\n if (me === undefined) return;\n let fired = false;\n\n pi.on(\"input\", () => {\n fired = false;\n });\n\n pi.on(\"agent_before_settle\", async (event, ctx) => {\n if (fired || nested() || noUI(ctx) || hold(ctx)) return; // nested: workerIdentity is the parent's\n if (outcomeOf(event) !== \"completed\") return;\n fired = true;\n const names = await ownedInProgress(run, me.agent, me.workstream);\n if (names === undefined || names.length === 0) return;\n if (hold(ctx)) {\n fired = false;\n return;\n }\n breadcrumb(run, [\n \"log\",\n \"-w\",\n me.workstream,\n \"--kind\",\n NUDGE_LOG_KIND,\n `close: ${me.agent} settled owning ${names.join(\", \")}`,\n ]);\n return {\n entries: [\n {\n type: \"custom_message\",\n customType: CLOSE_NUDGE_MESSAGE_TYPE,\n content: closeNudgeText(me.workstream, names),\n display: true,\n },\n ],\n continue: true,\n yielded: () => {\n fired = false;\n },\n };\n });\n}\n\n/** A note counts as a refute decision only when a line starts with a marker. */\nconst REFUTE_MARK = /^(REFUTER |VERDICT:|REFUTE-EXEMPT:)/m;\n\n/** True when the task's notes hold a refute decision; undefined if unreadable. */\nasync function briefRefuted(run: MuRunner, ws: string, id: string): Promise<boolean | undefined> {\n const r = await run([\"task\", \"notes\", id, ...(ws ? [\"-w\", ws] : []), \"--json\"]);\n if (r.code !== 0) return undefined;\n try {\n const json = JSON.parse(r.stdout) as { items?: { content?: string }[] };\n return (json.items ?? []).some((n) => REFUTE_MARK.test(n.content ?? \"\"));\n } catch {\n return undefined;\n }\n}\n\n/** The refute-nudge text: name each task and the two ways out. */\nexport function refuteNudgeText(refs: string[]): string {\n return `[mu] dispatched ${refs.join(\", \")} with an unrefuted brief: refute it (delegate, record) or note REFUTE-EXEMPT: <why>`;\n}\n\nexport function registerRefuteNudge(\n pi: MuNudgeApi,\n run: MuRunner = defaultRunner(),\n nested: NestedCheck = notNested,\n hold: SettleHold = noHold,\n): void {\n if (!nudgeEnabled()) return;\n // It only informs, so an open dialog does not hold it; an answer on its\n // way does, since its turn settles again and the notice can wait for it.\n const answerDue = (ctx?: MuNudgeCtx) => hold(ctx) === \"answer\";\n const armed = new Map<string, { ws: string; id: string }>();\n let fired = false;\n\n pi.on(\"input\", () => {\n armed.clear();\n fired = false;\n });\n\n pi.on(\"tool_call\", (event) => {\n const cmd = bashCommand(event);\n if (cmd === undefined) return;\n for (const t of dispatchedTasks(cmd)) {\n if (!t.id.startsWith(\"review_\")) armed.set(`${t.ws}/${t.id}`, t);\n }\n });\n\n pi.on(\"agent_before_settle\", async (event, ctx) => {\n if (fired || armed.size === 0 || nested() || noUI(ctx) || answerDue(ctx)) return;\n if (outcomeOf(event) !== \"completed\") return;\n fired = true;\n // One read per armed task, all at once: the settle waits for the slowest.\n const tasks = [...armed];\n const refuted = await Promise.all(tasks.map(([, t]) => briefRefuted(run, t.ws, t.id)));\n const refs = tasks.flatMap(([ref], i) => (refuted[i] === false ? [ref] : []));\n if (refs.length === 0) return;\n if (answerDue(ctx)) {\n fired = false;\n return;\n }\n const logWs = [...armed.values()].find((t) => t.ws !== \"\")?.ws;\n breadcrumb(run, [\n \"log\",\n ...(logWs ? [\"-w\", logWs] : []),\n \"--kind\",\n NUDGE_LOG_KIND,\n `refute: ${refs.join(\", \")}`,\n ]);\n return {\n entries: [\n {\n type: \"custom_message\",\n customType: REFUTE_NUDGE_MESSAGE_TYPE,\n content: refuteNudgeText(refs),\n display: true,\n },\n ],\n yielded: () => {\n fired = false;\n },\n };\n });\n}\n"],"mappings":";AASA;AAAA,EACE;AAAA,EACA,cAAAA;AAAA,EACA;AAAA,EACA,aAAAC;AAAA,EACA;AAAA,EACA,gBAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA,YAAAC;AAAA,OACK;AACP,SAAS,SAAS,oBAA8C;AAChE,SAAS,SAAS,QAAAC,aAAY;AAC9B,SAAS,iBAAAC,sBAAqB;;;AChBvB,IAAM,uBAAuB;AAsC7B,IAAM,eAAe,CAAC,OAAO,UAAU,SAAS;AAQhD,IAAM,UAAU;AAAA,EACrB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAuCO,IAAM,oBAAoB;AAG1B,SAAS,OAAO,KAAqB;AAC1C,SAAO,GAAG,KAAK,UAAU,GAAG,CAAC;AAAA;AAC/B;AAGO,IAAM,cAAN,MAAkB;AAAA,EACf,MAAM;AAAA,EAEd,KAAK,OAAyB;AAC5B,SAAK,OAAO;AACZ,UAAM,QAAQ,KAAK,IAAI,MAAM,IAAI;AACjC,SAAK,MAAM,M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O,QAAQ;AACnB,QAAI,CAAC,EAAG;AACR,MAAE,QAAQ,MAAM;AAChB,gBAAY,KAAK,qBAAqB,CAAC;AACvC,kBAAc,KAAK,qBAAqB,CAAC;AACzC,eAAW,KAAK,EAAE,MAAO,GAAE,QAAQ;AACnC,UAAM,IAAI,QAAc,CAAC,YAAY,EAAE,MAAM,MAAM,QAAQ,CAAC,CAAC;AAE7D,QAAI,QAAQ,UAAa,QAAQ,QAAQ,MAAM,IAAK,QAAO,UAAU,EAAE,OAAO,KAAK,CAAC;AAAA,EACtF,CAAC;AAED,SAAO,MAAM,EAAE,WAAW;AAC5B;","names":["existsSync","mkdirSync","readFileSync","statSync","join","fileURLToPath","join","join","existsSync","readFileSync","join","join","existsSync","readFileSync","join","existsSync","readFileSync","statSync","fileURLToPath","mkdirSync"]}
1
+ {"version":3,"sources":["../../extension/mu-pi.ts","../../src/ctl/protocol.ts","../../extension/delegate.ts","../../src/workstream-scope.ts","../../extension/delegate-args.ts","../../extension/mu-run.ts","../../extension/delegate-calls.ts","../../extension/delegate-format.ts","../../src/delegate-verdict.ts","../../extension/delegate-process-format.ts","../../extension/delegate-trace.ts","../../src/state-dir.ts","../../extension/nudge.ts"],"sourcesContent":["/**\n * mu pi extension: serves the per-agent control socket from inside the\n * agent's interactive pi, so mu gets exact send / status / wait without\n * replacing the TUI or scraping the pane.\n *\n * Inert unless `$MU_CTL_SOCK` is set (mu injects it at spawn). Imports\n * nothing from mu except the protocol, and nothing from pi: the pi API is\n * typed structurally below so pi stays a peer, not a dependency.\n */\nimport { randomUUID } from \"node:crypto\";\nimport {\n chmodSync,\n existsSync,\n linkSync,\n mkdirSync,\n readFileSync,\n realpathSync,\n rmSync,\n statSync,\n} from \"node:fs\";\nimport { connect, createServer, type Server, type Socket } from \"node:net\";\nimport { dirname, join } from \"node:path\";\nimport {\n CTL_COMMANDS,\n CTL_FEATURES,\n CTL_MSGID_MAX_LENGTH,\n CTL_MSGID_MEMORY,\n CTL_OPS,\n CTL_PROTOCOL_VERSION,\n type CtlBlocked,\n type CtlCommandName,\n type CtlReply,\n type CtlState,\n type CtlTool,\n encode,\n INCARNATION_MISMATCH,\n LineDecoder,\n UNKNOWN_OP_PREFIX,\n} from \"../src/ctl/protocol.js\";\nimport {\n type DelegateCtx,\n defaultRunner,\n type MuDelegateApi,\n type MuRunner,\n registerDelegate,\n} from \"./delegate.js\";\nimport {\n type MuNudgeApi,\n parallelSettle,\n registerCloseNudge,\n registerNudge,\n withQueuedInput,\n} from \"./nudge.js\";\n\n/** The mu package version, baked in by tsup's `define`; absent when run from source. */\ndeclare const __MU_VERSION__: string | undefined;\nconst EXT_VERSION = typeof __MU_VERSION__ === \"string\" ? __MU_VERSION__ : undefined;\n\n/** The slice of pi's ExtensionContext this extension uses. */\nexport interface MuPiContext extends DelegateCtx {\n /** pi's session manager: the session file, and the id the settle wait runs as. */\n sessionManager?: { getSessionFile(): string | undefined; getSessionId?(): string };\n isIdle(): boolean;\n hasPendingMessages(): boolean;\n abort(): void;\n}\n\n/** The slice of pi's ReplacedSessionContext: bound to the NEW session. */\nexport interface MuPiReplacedContext extends MuPiContext {\n sendUserMessage(text: string): Promise<void>;\n}\n\n/** The slice of pi's ExtensionCommandContext (command handlers only). */\nexport interface MuPiCommandContext extends MuPiContext {\n newSession(options?: {\n withSession?: (ctx: MuPiReplacedContext) => Promise<void>;\n }): Promise<{ cancelled: boolean }>;\n reload(): Promise<void>;\n compact(options?: {\n customInstructions?: string;\n onComplete?: (result: unknown) => void;\n onError?: (error: Error) => void;\n }): void;\n}\n\n/** The slice of pi's ExtensionAPI this extension uses. */\nexport interface MuPiApi extends MuDelegateApi {\n on(\n event:\n | \"session_start\"\n | \"session_shutdown\"\n | \"session_before_compact\"\n | \"agent_start\"\n | \"agent_end\"\n | \"agent_settled\"\n | \"tool_execution_start\"\n | \"tool_execution_end\"\n | \"message_start\"\n | \"ui_prompt_start\"\n | \"ui_prompt_end\"\n | Parameters<MuNudgeApi[\"on\"]>[0],\n handler: (event: unknown, ctx: MuPiContext) => unknown,\n ): unknown;\n sendUserMessage(\n text: string,\n options?: { deliverAs?: \"steer\" | \"followUp\"; expandPromptTemplates?: boolean },\n ): void | Promise<void>;\n registerCommand(\n name: string,\n options: {\n description: string;\n handler: (args: string, ctx: MuPiCommandContext) => Promise<void>;\n },\n ): void;\n}\n\n/** Internal command behind the `fresh` op: new session + prompt, inside pi. */\nexport const FRESH_COMMAND = \"mu-fresh\";\n/** The extension's own bound on a fresh op that never reaches agent_start. */\nexport const FRESH_TIMEOUT_MS = 30_000;\n/** Internal command behind the `command` op, per session command: `mu-new`, ... */\nexport function commandName(name: CtlCommandName): string {\n return `mu-${name}`;\n}\n/** The extension's own bound on a `command` op that never completes. */\nexport const COMMAND_TIMEOUT_MS = 30_000;\n/** Cap on `lastText` in a wait reply, in UTF-8 bytes (before the marker).\n * A longer message keeps its TAIL: the final lines (a CLOSE block) are\n * what a consumer reads, and the reply says `lastTextTruncated: true`. */\nexport const LAST_TEXT_MAX_BYTES = 64 * 1024;\nexport const LAST_TEXT_TRUNCATED = \"[truncated, see pane]\";\n/** How long session_start waits for another pi to answer on the socket path. */\nexport const LIVE_PROBE_MS = 500;\n\ntype Reply = CtlReply;\nconst V = CTL_PROTOCOL_VERSION;\n\nfunction fail(error: string): Reply {\n return { v: V, ok: false, error };\n}\n\n/** Best effort: the version of the pi package running this process. */\nfunction detectPiVersion(): string | undefined {\n try {\n const entry = process.argv[1];\n if (!entry) return undefined;\n let dir = dirname(realpathSync(entry));\n for (let i = 0; i < 6; i++) {\n const pkgPath = join(dir, \"package.json\");\n if (existsSync(pkgPath)) {\n const pkg: unknown = JSON.parse(readFileSync(pkgPath, \"utf8\"));\n if (typeof pkg === \"object\" && pkg !== null) {\n const { name, version } = pkg as { name?: unknown; version?: unknown };\n if (typeof name === \"string\" && /pi/.test(name) && typeof version === \"string\") {\n return version;\n }\n }\n }\n const up = dirname(dir);\n if (up === dir) break;\n dir = up;\n }\n } catch {\n // Unknown version is reported as absent, never as an error.\n }\n return undefined;\n}\n\nfunction str(o: Record<string, unknown>, k: string): string | undefined {\n const x = o[k];\n return typeof x === \"string\" ? x : undefined;\n}\n\nfunction num(o: Record<string, unknown>, k: string): number | undefined {\n const x = o[k];\n return typeof x === \"number\" && Number.isFinite(x) ? x : undefined;\n}\n\n/** A `fresh` op in flight: its prompt and the reply it is waiting to send. */\ntype PendingFresh = {\n text: string;\n /** Set once the new session exists, so its agent_start is the prompt's. */\n armed: boolean;\n settle: (r: Reply) => void;\n};\n\n/** A `command` op in flight: the session command and its pending reply. */\ntype PendingCommand = {\n name: CtlCommandName;\n instructions?: string;\n /** reload: set by the session_start (reason reload) the reload produced. */\n reloaded: boolean;\n settle: (r: Reply) => void;\n};\n\n/**\n * Process-global state, keyed by socket path. pi re-runs this factory\n * for every session (a /new or /mu-fresh replaces the extension runtime),\n * so the socket server, the run counters and an in-flight fresh must\n * outlive any one runtime. Each runtime refreshes `pi` and `handle`.\n */\ntype Shared = {\n server?: Server;\n /** Set by bind(): another pi serves the socket, so this pi is not the agent. */\n nested?: boolean;\n /** Inode of the socket file this process bound; the only file it may unlink. */\n ino?: number;\n conns: Set<Socket>;\n /** Minted with the entry, so once per pi process per socket; /new and /reload keep it. */\n incarnation: string;\n /** Last CTL_MSGID_MEMORY accepted msgIds (insertion order), with the runs the reply carried. */\n accepted: Map<string, { runs: number; at: number }>;\n /** Held waits; called with \"settle\" on agent_settled, \"blocked\" on ui_prompt_start. */\n waiters: Set<(why: \"settle\" | \"blocked\") => void>;\n state: CtlState;\n since: number;\n runs: number;\n /** Tools executing now by toolCallId, insertion order (the last is the one `status` reports). */\n tools: Map<string, CtlTool>;\n /** Final assistant text of the last settled run; served by `wait`. */\n lastText: string;\n /** True when `lastText` lost its head to the tail cap. */\n lastTextTruncated?: boolean;\n /** Captured on agent_end, published to `lastText` on agent_settled. */\n endText?: string;\n endTextTruncated?: boolean;\n /** Error that ended the last settled run, if any; served by `wait`. */\n lastError?: string;\n endError?: string;\n /** Session file of the last settled run; served by `wait`. */\n sessionFile?: string;\n ctx?: MuPiContext;\n pi: MuPiApi;\n handle: (req: Record<string, unknown>, conn: Socket) => Promise<Reply>;\n fresh?: PendingFresh;\n command?: PendingCommand;\n};\n\nconst SHARED = Symbol.for(\"mu.pi.ctl\");\ntype SharedMap = Map<string, Shared>;\n\nfunction sharedMap(): SharedMap {\n const g = globalThis as { [SHARED]?: SharedMap };\n g[SHARED] ??= new Map();\n return g[SHARED];\n}\n\n/**\n * Text of the last assistant message in an agent_end event's `messages`:\n * its text parts joined, no tool calls or thinking. \"\" when there is none.\n * `truncated` when the tail cap cut the head off.\n */\nexport function lastAssistantText(event: unknown): { text: string; truncated: boolean } {\n const msgs =\n typeof event === \"object\" && event !== null\n ? (event as { messages?: unknown }).messages\n : undefined;\n if (!Array.isArray(msgs)) return { text: \"\", truncated: false };\n for (let i = msgs.length - 1; i >= 0; i--) {\n const m: unknown = msgs[i];\n if (typeof m !== \"object\" || m === null) continue;\n const { role, content } = m as { role?: unknown; content?: unknown };\n if (role !== \"assistant\") continue;\n if (typeof content === \"string\") return capTail(content);\n if (!Array.isArray(content)) return { text: \"\", truncated: false };\n const parts = content.flatMap((c: unknown) => {\n if (typeof c !== \"object\" || c === null) return [];\n const { type, text } = c as { type?: unknown; text?: unknown };\n return type === \"text\" && typeof text === \"string\" ? [text] : [];\n });\n return capTail(parts.join(\"\"));\n }\n return { text: \"\", truncated: false };\n}\n\n/** The final assistant message's error, when the run stopped on one\n * (pi's own retries exhausted: overloaded, connection, auth). */\nexport function lastAssistantError(event: unknown): string | undefined {\n const msgs =\n typeof event === \"object\" && event !== null\n ? (event as { messages?: unknown }).messages\n : undefined;\n if (!Array.isArray(msgs)) return undefined;\n for (let i = msgs.length - 1; i >= 0; i--) {\n const m: unknown = msgs[i];\n if (typeof m !== \"object\" || m === null) continue;\n const { role, stopReason, errorMessage } = m as {\n role?: unknown;\n stopReason?: unknown;\n errorMessage?: unknown;\n };\n if (role !== \"assistant\") continue;\n if (stopReason !== \"error\") return undefined;\n return typeof errorMessage === \"string\" && errorMessage !== \"\"\n ? capText(errorMessage)\n : \"unknown error\";\n }\n return undefined;\n}\n\n/** Keep the last LAST_TEXT_MAX_BYTES bytes, the marker on its own first line. */\nfunction capTail(text: string): { text: string; truncated: boolean } {\n if (Buffer.byteLength(text, \"utf8\") <= LAST_TEXT_MAX_BYTES) return { text, truncated: false };\n const buf = Buffer.from(text, \"utf8\");\n // Cut on bytes; drop a code point split by the cut.\n const tail = buf\n .subarray(buf.length - LAST_TEXT_MAX_BYTES)\n .toString(\"utf8\")\n .replace(/^\\uFFFD/, \"\");\n return { text: `${LAST_TEXT_TRUNCATED}\\n${tail}`, truncated: true };\n}\n\nfunction capText(text: string): string {\n if (Buffer.byteLength(text, \"utf8\") <= LAST_TEXT_MAX_BYTES) return text;\n // Cut on bytes; drop a code point split by the cut.\n const cut = Buffer.from(text, \"utf8\").subarray(0, LAST_TEXT_MAX_BYTES).toString(\"utf8\");\n return `${cut.replace(/\\uFFFD$/, \"\")}\\n${LAST_TEXT_TRUNCATED}`;\n}\n\n/** Open extension dialogs, outermost first; process-global like Shared. */\ntype UiPrompts = { open: { kind: string; title?: string }[]; since: number };\nconst UI_PROMPTS = Symbol.for(\"mu.pi.uiPrompts\");\n\nfunction uiPrompts(): UiPrompts {\n const g = globalThis as { [UI_PROMPTS]?: UiPrompts };\n g[UI_PROMPTS] ??= { open: [], since: 0 };\n return g[UI_PROMPTS];\n}\n\n/** The open extension dialog pi is waiting on (innermost), or undefined. */\nexport function uiBlocked(): CtlBlocked | undefined {\n const u = uiPrompts();\n const top = u.open[u.open.length - 1];\n if (!top) return undefined;\n return {\n kind: top.kind,\n ...(top.title !== undefined ? { title: top.title } : {}),\n since: u.since,\n };\n}\n\n/** Whether pi is waiting on a blocking extension dialog right now. */\nexport function isUiBlocked(): boolean {\n return uiPrompts().open.length > 0;\n}\n\nfunction promptOf(event: unknown): { kind: string; title?: string } {\n const e = typeof event === \"object\" && event !== null ? (event as Record<string, unknown>) : {};\n const kind = typeof e.kind === \"string\" ? e.kind : \"custom\";\n const title = typeof e.title === \"string\" && e.title !== \"\" ? e.title : undefined;\n return { kind, ...(title !== undefined ? { title } : {}) };\n}\n\n/** Track ui_prompt_start / ui_prompt_end; `onStart` runs after each start. */\nfunction trackUiPrompts(pi: MuPiApi, onStart: () => void = () => {}): void {\n pi.on(\"ui_prompt_start\", (e) => {\n const u = uiPrompts();\n if (u.open.length === 0) u.since = Date.now();\n u.open.push(promptOf(e));\n onStart();\n });\n // A new runtime has no dialog open: drop any whose end a replaced\n // session never delivered.\n pi.on(\"session_start\", () => {\n uiPrompts().open.length = 0;\n });\n pi.on(\"ui_prompt_end\", (e) => {\n const u = uiPrompts();\n // Close the innermost dialog of this kind; prompts nest, so ends come LIFO.\n const { kind } = promptOf(e);\n let i = u.open.length - 1;\n while (i >= 0 && u.open[i]?.kind !== kind) i--;\n u.open.splice(i >= 0 ? i : u.open.length - 1, 1);\n });\n}\n\n/** Inode at `path`, or undefined when there is no file. */\nfunction inodeOf(path: string): number | undefined {\n try {\n return statSync(path).ino;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Whether some process is serving `path`. Refused / missing means a stale\n * file. A connect that neither succeeds nor fails in time counts as live:\n * never steal a socket on a guess.\n */\nfunction socketIsLive(path: string): Promise<boolean> {\n return new Promise((resolve) => {\n const c = connect(path);\n const done = (live: boolean) => {\n clearTimeout(timer);\n c.destroy();\n resolve(live);\n };\n const timer = setTimeout(() => done(true), LIVE_PROBE_MS);\n c.once(\"connect\", () => done(true));\n c.once(\"error\", (e: NodeJS.ErrnoException) =>\n done(e.code !== \"ENOENT\" && e.code !== \"ECONNREFUSED\"),\n );\n });\n}\n\n/** Per-process counter so a rebind never reuses a temp name a closing server owns. */\nlet bindSeq = 0;\n\nfunction reasonOf(event: unknown): string | undefined {\n const r =\n typeof event === \"object\" && event !== null\n ? (event as { reason?: unknown }).reason\n : undefined;\n return typeof r === \"string\" ? r : undefined;\n}\n\nexport default function muPi(pi: MuPiApi, run: MuRunner = defaultRunner()): void {\n const delegates = registerDelegate(pi, run);\n // Identity follows the bind: a pi that finds MU_CTL_SOCK served by\n // another pi is nested and gets none of the agent's nudges.\n const nested = serveCtl(pi);\n // The settle wait and the close nudge run in parallel, as one handler.\n // A delegate wake on its way starts a turn whose settle waits; an open\n // dialog means nobody is driving. Either holds the nudges. The settle wait\n // shows delegate answers and tells the delegate side which, so it wakes pi\n // only for answers no settle showed.\n const hold = withQueuedInput(() =>\n delegates.answerPending() ? \"wake\" : isUiBlocked() ? \"blocked\" : undefined,\n );\n const settle = parallelSettle(pi, hold);\n registerNudge(settle.api, run, undefined, nested, hold, delegates.delivered);\n registerCloseNudge(settle.api, run, process.env, nested, hold);\n settle.flush();\n}\n\n/**\n * Child side: serve `$MU_CTL_SOCK` for the mu that spawned this pi.\n * Returns whether this pi is nested (another pi serves the socket), read\n * from the process-global state so a reloaded runtime sees the decision.\n */\nfunction serveCtl(pi: MuPiApi): () => boolean {\n const sock = process.env.MU_CTL_SOCK;\n if (!sock) {\n trackUiPrompts(pi);\n return () => false;\n }\n const sockPath: string = sock;\n const piVersion = detectPiVersion();\n\n const map = sharedMap();\n const existing = map.get(sockPath);\n const g: Shared = existing ?? {\n conns: new Set(),\n incarnation: randomUUID(),\n accepted: new Map(),\n waiters: new Set(),\n state: \"idle\",\n since: Date.now(),\n runs: 0,\n tools: new Map(),\n lastText: \"\",\n pi,\n handle,\n };\n g.pi = pi;\n g.handle = handle;\n // A /reload can hand us an entry minted by older code that lacks later fields.\n (g as Partial<Shared>).incarnation ??= randomUUID();\n (g as Partial<Shared>).accepted ??= new Map();\n (g as Partial<Shared>).tools ??= new Map();\n map.set(sockPath, g);\n\n const status = () => ({\n incarnation: g.incarnation,\n state: g.state,\n since: g.since,\n runs: g.runs,\n pending: g.ctx?.hasPendingMessages() ?? false,\n tool: [...g.tools.values()].at(-1) ?? null,\n ...sessionFileOf(g.ctx),\n ...blockedField(),\n });\n\n /** Remember an accepted msgId with the `runs` its reply carried; evicts the oldest. */\n const remember = (id: string | undefined, runs: number): void => {\n if (id === undefined) return;\n g.accepted.delete(id);\n g.accepted.set(id, { runs, at: Date.now() });\n for (const old of g.accepted.keys()) {\n if (g.accepted.size <= CTL_MSGID_MEMORY) break;\n g.accepted.delete(old);\n }\n };\n\n const blockedField = (): { blocked?: CtlBlocked } => {\n const b = uiBlocked();\n return b ? { blocked: b } : {};\n };\n\n trackUiPrompts(pi, () => {\n for (const w of [...g.waiters]) w(\"blocked\");\n });\n\n const settleFresh = (r: Reply) => {\n const f = g.fresh;\n if (!f) return;\n g.fresh = undefined;\n f.settle(r);\n };\n\n const settleCommand = (r: Reply) => {\n const c = g.command;\n if (!c) return;\n g.command = undefined;\n c.settle(r);\n };\n\n pi.on(\"agent_start\", (_e, c) => {\n g.ctx = c;\n g.state = \"busy\";\n g.since = Date.now();\n // The new session's run started: the fresh prompt landed.\n if (g.fresh?.armed) settleFresh({ v: V, ok: true, ...status() });\n });\n\n // A settled run can span several low-level runs (retry, follow-up):\n // the last agent_end before the settle holds the final answer.\n // The running tool, for the dashboard: a run that ends or settles clears it.\n pi.on(\"tool_execution_start\", (e) => {\n const { toolCallId, toolName } = (e ?? {}) as { toolCallId?: unknown; toolName?: unknown };\n if (typeof toolCallId === \"string\" && typeof toolName === \"string\") {\n g.tools.set(toolCallId, { name: toolName, since: Date.now() });\n }\n });\n pi.on(\"tool_execution_end\", (e) => {\n g.tools.delete(String((e as { toolCallId?: unknown } | undefined)?.toolCallId));\n });\n\n pi.on(\"agent_end\", (e) => {\n g.tools.clear();\n const cut = lastAssistantText(e);\n g.endText = cut.text;\n g.endTextTruncated = cut.truncated;\n g.endError = lastAssistantError(e);\n });\n\n /** The session file of `c`, as a spreadable field; {} when unknown. */\n function sessionFileOf(c: MuPiContext | undefined): { sessionFile?: string } {\n try {\n const f = c?.sessionManager?.getSessionFile();\n return f ? { sessionFile: f } : {};\n } catch {\n return {}; // stale ctx: the pointer is a convenience\n }\n }\n\n pi.on(\"agent_settled\", (_e, c) => {\n g.ctx = c;\n g.state = \"idle\";\n g.since = Date.now();\n g.tools.clear();\n g.runs++;\n g.lastText = g.endText ?? \"\";\n g.lastTextTruncated = g.endTextTruncated === true;\n g.endText = undefined;\n g.endTextTruncated = undefined;\n g.lastError = g.endError;\n g.endError = undefined;\n g.sessionFile = sessionFileOf(c).sessionFile;\n for (const w of [...g.waiters]) w(\"settle\");\n });\n\n pi.registerCommand(FRESH_COMMAND, {\n description: \"mu internal: new session + the prompt mu queued (run by mu agent send --fresh)\",\n handler: async (_args, ctx) => {\n const f = g.fresh;\n if (!f) return; // typed by hand: nothing queued\n try {\n const r = await ctx.newSession({\n withSession: async (c) => {\n g.ctx = c;\n f.armed = true;\n await c.sendUserMessage(f.text);\n },\n });\n if (r.cancelled) settleFresh(fail(\"new session was cancelled\"));\n } catch (e) {\n settleFresh(fail(e instanceof Error ? e.message : String(e)));\n }\n // The run finished without an agent_start we saw: still landed.\n settleFresh({ v: V, ok: true, ...status() });\n },\n });\n\n // A compaction we asked for has started: reply now, not after the\n // summary call. Errors before this point (e.g. \"Nothing to compact\")\n // reach the reply through compact's onError.\n pi.on(\"session_before_compact\", () => {\n if (g.command?.name === \"compact\") settleCommand({ v: V, ok: true, ...status() });\n });\n\n /** Run the queued session command `name` with pi's command context. */\n async function runCommand(name: CtlCommandName, ctx: MuPiCommandContext): Promise<void> {\n const c = g.command;\n if (c?.name !== name) return; // typed by hand: nothing queued\n const ok = () => settleCommand({ v: V, ok: true, ...status() });\n const failWith = (e: unknown) =>\n settleCommand(fail(e instanceof Error ? e.message : String(e)));\n try {\n if (name === \"new\") {\n const r = await ctx.newSession();\n if (r.cancelled) settleCommand(fail(\"new session was cancelled\"));\n else ok();\n } else if (name === \"reload\") {\n await ctx.reload();\n // pi's reload returns quietly when it refuses (streaming, compacting).\n if (c.reloaded) ok();\n else settleCommand(fail(\"pi did not reload (busy or compacting)\"));\n } else {\n ctx.compact({\n ...(c.instructions !== undefined ? { customInstructions: c.instructions } : {}),\n onComplete: ok,\n onError: failWith,\n });\n }\n } catch (e) {\n failWith(e);\n }\n }\n\n for (const name of CTL_COMMANDS) {\n pi.registerCommand(commandName(name), {\n description: `mu internal: /${name} requested over the control socket (mu agent send '/${name}')`,\n handler: (_args, ctx) => runCommand(name, ctx),\n });\n }\n\n function command(req: Record<string, unknown>): Promise<Reply> | Reply {\n const stale = incarnationRefusal(req);\n if (stale) return stale;\n const name = CTL_COMMANDS.find((n) => n === req.name);\n if (name === undefined) {\n return fail(`command must be one of ${CTL_COMMANDS.join(\", \")}`);\n }\n if (g.fresh || g.command) return fail(\"a fresh send or command is already in progress\");\n const busy = !(g.ctx?.isIdle() ?? g.state === \"idle\");\n if (busy && req.force !== true) return fail(\"busy\");\n const instructions = str(req, \"instructions\");\n return new Promise<Reply>((resolve) => {\n const timer = setTimeout(() => settleCommand(fail(`/${name} timed out`)), COMMAND_TIMEOUT_MS);\n g.command = {\n name,\n ...(instructions !== undefined ? { instructions } : {}),\n reloaded: false,\n settle: (r) => {\n clearTimeout(timer);\n resolve(r);\n },\n };\n Promise.resolve(\n g.pi.sendUserMessage(`/${commandName(name)}`, { expandPromptTemplates: true }),\n ).catch((e: unknown) => settleCommand(fail(e instanceof Error ? e.message : String(e))));\n });\n }\n\n function fresh(req: Record<string, unknown>): Promise<Reply> | Reply {\n const stale = incarnationRefusal(req, \"expectIncarnation\");\n if (stale) return stale;\n const text = str(req, \"text\");\n if (text === undefined) return fail(\"fresh needs a string text\");\n const id = msgIdOf(req);\n if (id.error) return fail(id.error);\n if (g.fresh || g.command) return fail(\"a fresh send or command is already in progress\");\n const busy = !(g.ctx?.isIdle() ?? g.state === \"idle\");\n if (busy && req.force !== true) return fail(\"busy\");\n return new Promise<Reply>((resolve) => {\n const timer = setTimeout(() => settleFresh(fail(\"fresh timed out\")), FRESH_TIMEOUT_MS);\n g.fresh = {\n text,\n armed: false,\n settle: (r) => {\n clearTimeout(timer);\n // Every ok settle is a landed prompt (run started, or finished unseen).\n if (r.ok) remember(id.id, r.runs ?? g.runs);\n resolve(r);\n },\n };\n // expandPromptTemplates dispatches extension commands, even mid-run.\n Promise.resolve(\n g.pi.sendUserMessage(`/${FRESH_COMMAND}`, { expandPromptTemplates: true }),\n ).catch((e: unknown) => settleFresh(fail(e instanceof Error ? e.message : String(e))));\n });\n }\n\n /**\n * A request that names `expectIncarnation` is for the pi process the caller\n * saw (its spawn handshake). Another process now bound to this socket path\n * refuses it before anything is dispatched. Absent: no check.\n */\n function incarnationRefusal(\n req: Record<string, unknown>,\n key = \"expectIncarnation\",\n ): Reply | undefined {\n if (!(key in req) || req[key] === g.incarnation) return undefined;\n return { ...fail(INCARNATION_MISMATCH), incarnation: g.incarnation };\n }\n\n /** The optional msgId of `req`: absent is fine; present must be a string of 1-64 characters. */\n function msgIdOf(req: Record<string, unknown>): { id?: string; error?: string } {\n if (!(\"msgId\" in req)) return {};\n const id = req.msgId;\n if (typeof id === \"string\" && id.length >= 1 && id.length <= CTL_MSGID_MAX_LENGTH)\n return { id };\n return { error: `msgId must be a string of 1-${CTL_MSGID_MAX_LENGTH} characters` };\n }\n\n async function handle(req: Record<string, unknown>, conn: Socket): Promise<Reply> {\n switch (req.op) {\n case \"hello\":\n return {\n v: V,\n ok: true,\n agent: process.env.MU_AGENT_NAME,\n workstream: process.env.MU_WORKSTREAM,\n piVersion,\n incarnation: g.incarnation,\n ops: [...CTL_OPS],\n features: [...CTL_FEATURES],\n ...(EXT_VERSION !== undefined ? { extVersion: EXT_VERSION } : {}),\n };\n case \"status\": {\n const id = msgIdOf(req);\n if (id.error) return fail(id.error);\n if (id.id === undefined) return { v: V, ok: true, ...status() };\n const got = g.accepted.get(id.id);\n const msg = got ? { id: id.id, accepted: true, ...got } : { id: id.id, accepted: false };\n return { v: V, ok: true, ...status(), msg };\n }\n case \"send\": {\n const stale = incarnationRefusal(req);\n if (stale) return stale;\n const text = str(req, \"text\");\n if (text === undefined) return fail(\"send needs a string text\");\n const id = msgIdOf(req);\n if (id.error) return fail(id.error);\n const mode = req.mode === \"steer\" ? \"steer\" : \"followUp\";\n // Measured before dispatch: `runs` is the caller's wait baseline,\n // and a run this send starts may settle before the reply is read.\n const before = status();\n // A message sent while idle starts a run; options are only for a busy pi.\n if (g.ctx?.isIdle() ?? g.state === \"idle\") await g.pi.sendUserMessage(text);\n else await g.pi.sendUserMessage(text, { deliverAs: mode });\n remember(id.id, before.runs);\n return { v: V, ok: true, ...before };\n }\n case \"fresh\":\n return fresh(req);\n case \"command\":\n return command(req);\n case \"wait\":\n if (\"incarnation\" in req && req.incarnation !== g.incarnation) {\n return { ...fail(INCARNATION_MISMATCH), incarnation: g.incarnation };\n }\n return wait(\n num(req, \"afterRuns\"),\n num(req, \"timeoutMs\"),\n conn,\n req.returnOnBlocked === true,\n );\n case \"abort\":\n if (!g.ctx) return fail(\"no pi context yet\");\n {\n // The run may have settled since the caller's status probe.\n const wasBusy = !g.ctx.isIdle();\n if (wasBusy) g.ctx.abort();\n return { v: V, ok: true, state: g.state, wasBusy };\n }\n case \"interrupt\":\n return interrupt(req, conn);\n default:\n return { ...fail(`${UNKNOWN_OP_PREFIX}${String(req.op)}`), ops: [...CTL_OPS] };\n }\n }\n\n /**\n * Abort a busy turn, wait for its settle, then send `text` as a new run.\n * The waiter is registered before the abort, so a settle that lands at\n * once is not missed. `runs` is read after that settle and before the\n * send: the caller's wait baseline for the new run, not the aborted one.\n */\n async function interrupt(req: Record<string, unknown>, conn: Socket): Promise<Reply> {\n const stale = incarnationRefusal(req);\n if (stale) return stale;\n const text = str(req, \"text\");\n if (text === undefined) return fail(\"interrupt needs a string text\");\n const id = msgIdOf(req);\n if (id.error) return fail(id.error);\n const wasBusy = !(g.ctx?.isIdle() ?? g.state === \"idle\");\n const { pending } = status();\n if (wasBusy) {\n if (!g.ctx) return fail(\"no pi context yet\");\n const settled = wait(g.runs, num(req, \"timeoutMs\"), conn);\n g.ctx.abort();\n const w = await settled;\n if (!w.ok) return w;\n }\n const before = status();\n await g.pi.sendUserMessage(text);\n remember(id.id, before.runs);\n return { v: V, ok: true, ...before, pending, wasBusy };\n }\n\n const settledRun = () => ({\n lastText: g.lastText,\n ...(g.lastTextTruncated === true ? { lastTextTruncated: true } : {}),\n ...(g.lastError !== undefined ? { lastError: g.lastError } : {}),\n ...(g.sessionFile !== undefined ? { sessionFile: g.sessionFile } : {}),\n });\n\n /**\n * Resolve once a run past `afterRuns` has settled (any next settle when\n * omitted). With `onBlocked`, an open or opening dialog ends the wait\n * first: `ended: \"blocked\"`, no settled-run fields, runs unchanged.\n */\n function wait(\n afterRuns: number | undefined,\n timeoutMs: number | undefined,\n conn: Socket,\n onBlocked = false,\n ) {\n if (afterRuns !== undefined && g.runs > afterRuns && g.state === \"idle\") {\n return Promise.resolve<Reply>({\n v: V,\n ok: true,\n ...status(),\n ...settledRun(),\n ended: \"settled\",\n });\n }\n const blockedReply = (): Reply => ({ v: V, ok: true, ...status(), ended: \"blocked\" });\n if (onBlocked && isUiBlocked()) return Promise.resolve(blockedReply());\n return new Promise<Reply>((resolve) => {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const done = (r: Reply) => {\n g.waiters.delete(waiter);\n if (timer) clearTimeout(timer);\n conn.off(\"close\", onClose);\n resolve(r);\n };\n // A settle at or below `afterRuns` is not the run asked for: keep waiting.\n const waiter = (why: \"settle\" | \"blocked\") => {\n if (why === \"blocked\") {\n if (onBlocked) done(blockedReply());\n return;\n }\n if (afterRuns !== undefined && g.runs <= afterRuns) return;\n done({ v: V, ok: true, ...status(), ...settledRun(), ended: \"settled\" });\n };\n const onClose = () => done(fail(\"client closed\"));\n g.waiters.add(waiter);\n conn.on(\"close\", onClose);\n if (timeoutMs !== undefined) timer = setTimeout(() => done(fail(\"timeout\")), timeoutMs);\n });\n }\n\n /** Created once per process; dispatches to the newest runtime's handle. */\n function onConnection(conn: Socket): void {\n g.conns.add(conn);\n conn.setEncoding(\"utf8\");\n const dec = new LineDecoder();\n let seen = false;\n conn.on(\"close\", () => g.conns.delete(conn));\n conn.on(\"error\", () => {});\n conn.on(\"data\", (chunk: string) => {\n const line = dec.push(chunk)[0];\n if (line === undefined || seen) return;\n seen = true; // one request per connection\n let req: unknown;\n try {\n req = JSON.parse(line);\n } catch {\n conn.end(encode(fail(\"bad json\")));\n return;\n }\n if (typeof req !== \"object\" || req === null) {\n conn.end(encode(fail(\"request must be an object\")));\n return;\n }\n g.handle(req as Record<string, unknown>, conn).then(\n (r) => {\n if (!conn.destroyed) conn.end(encode(r));\n },\n (e: unknown) => {\n if (!conn.destroyed) conn.end(encode(fail(e instanceof Error ? e.message : String(e))));\n },\n );\n });\n }\n\n /**\n * Bind the socket unless another pi already serves it. A nested pi (a\n * probe or `pi -p` run inside an agent's pane) inherits MU_CTL_SOCK; it\n * must leave the agent's socket alone, not unlink and take it.\n */\n async function bind(): Promise<void> {\n mkdirSync(dirname(sockPath), { recursive: true, mode: 0o700 });\n if (await socketIsLive(sockPath)) {\n g.nested = true;\n process.stderr.write(\n `mu: control socket ${sockPath} is served by another pi; nested pi: mu agent features off\\n`,\n );\n return;\n }\n rmSync(sockPath, { force: true });\n // Listen on a private name, then hard-link it into place. libuv unlinks\n // the name a server listened on when it closes, so the public path must\n // never be that name: closing would delete whatever file sits there by\n // then. link() also fails on an existing path, so a racing pi keeps it.\n const tmp = join(dirname(sockPath), `.${process.pid.toString(36)}${(++bindSeq).toString(36)}`);\n rmSync(tmp, { force: true });\n const s = createServer(onConnection);\n await new Promise<void>((resolve, reject) => {\n s.once(\"error\", reject);\n s.listen(tmp, () => {\n s.off(\"error\", reject);\n resolve();\n });\n });\n chmodSync(tmp, 0o600);\n try {\n linkSync(tmp, sockPath);\n } catch (e) {\n s.close();\n if ((e as NodeJS.ErrnoException).code !== \"EEXIST\") throw e;\n g.nested = true;\n process.stderr.write(\n `mu: control socket ${sockPath} was taken by another pi; nested pi: mu agent features off\\n`,\n );\n return;\n } finally {\n rmSync(tmp, { force: true });\n }\n g.server = s;\n g.ino = inodeOf(sockPath);\n g.nested = false;\n }\n\n pi.on(\"session_start\", async (e, c) => {\n g.ctx = c;\n if (reasonOf(e) === \"reload\" && g.command?.name === \"reload\") g.command.reloaded = true;\n const s = g.server;\n if (s) {\n // A new/resumed session keeps the same socket, while the path is ours.\n if (g.ino !== undefined && inodeOf(sockPath) === g.ino) return;\n // Orphaned: the file was deleted or replaced under a live server.\n // Stop accepting on the dead inode (open connections finish) and rebind.\n g.server = undefined;\n g.ino = undefined;\n s.close();\n }\n await bind();\n });\n\n pi.on(\"session_shutdown\", async (e) => {\n // Session replacement (new / resume / fork / reload) keeps the socket\n // and its connections: an in-flight fresh is answered by the next\n // runtime. Only quit (or an unknown reason) tears the server down.\n const reason = reasonOf(e);\n if (reason === \"new\" || reason === \"resume\" || reason === \"fork\" || reason === \"reload\") {\n return;\n }\n const s = g.server;\n const ino = g.ino;\n g.server = undefined;\n g.ino = undefined;\n map.delete(sockPath);\n if (!s) return;\n g.waiters.clear();\n settleFresh(fail(\"pi is shutting down\"));\n settleCommand(fail(\"pi is shutting down\"));\n for (const c of g.conns) c.destroy();\n await new Promise<void>((resolve) => s.close(() => resolve()));\n // Unlink only the file this process bound: another pi may own the path now.\n if (ino !== undefined && inodeOf(sockPath) === ino) rmSync(sockPath, { force: true });\n });\n\n return () => g.nested === true;\n}\n","/**\n * mu control socket protocol: JSON lines over a unix socket, one request\n * per connection. Shared by mu's client and the mu pi extension, so this\n * file imports nothing from mu — the extension loads it standalone.\n */\n\nexport const CTL_PROTOCOL_VERSION = 1;\n\nexport type CtlState = \"busy\" | \"idle\";\n\n/**\n * pi is waiting on a blocking extension dialog (ui_prompt_start without\n * its ui_prompt_end): a confirm, select, input, editor or custom prompt.\n * `kind` and `title` are the innermost open dialog's; `since` is when the\n * first one opened (ms epoch).\n */\nexport type CtlBlocked = { kind: string; title?: string; since: number };\n\nexport type CtlRequest =\n | { op: \"hello\" }\n /** With msgId, also reply `msg`: whether this extension accepted that send/fresh/interrupt. */\n | { op: \"status\"; msgId?: string }\n /**\n * `msgId` (send, fresh, interrupt; a string of 1-CTL_MSGID_MAX_LENGTH\n * characters) lets the caller ask `status` later whether the request\n * was accepted, when no reply arrived.\n */\n | {\n op: \"send\";\n text: string;\n mode?: \"steer\" | \"followUp\";\n msgId?: string;\n /** Refused before acting (INCARNATION_MISMATCH) when it is not the extension's current incarnation. */\n expectIncarnation?: string;\n }\n /**\n * Resolve once a run past afterRuns settles. With returnOnBlocked, also\n * resolve (ended \"blocked\", runs unchanged) when a dialog is open or\n * opens. Older extensions ignore the flag and hold until the settle.\n */\n | {\n op: \"wait\";\n afterRuns?: number;\n timeoutMs?: number;\n returnOnBlocked?: boolean;\n /** Refused at once (INCARNATION_MISMATCH) when it is not the extension's current one. */\n incarnation?: string;\n }\n | { op: \"abort\" }\n /**\n * Make a busy pi act on `text` now: abort the running turn, wait for\n * agent_settled (up to timeoutMs), then send `text` as a new run. Idle:\n * just send. Replies `timeout` and sends nothing when pi does not settle.\n */\n | {\n op: \"interrupt\";\n text: string;\n timeoutMs?: number;\n msgId?: string;\n /** As on `send`: another incarnation is refused before the abort. */\n expectIncarnation?: string;\n }\n /** New session + prompt as one operation. Refused with error \"busy\" unless force. */\n | {\n op: \"fresh\";\n text: string;\n force?: boolean;\n msgId?: string;\n /** As on `send`: another incarnation is refused before any state changes. */\n expectIncarnation?: string;\n }\n /**\n * Run one of pi's session commands inside pi (sendUserMessage cannot run\n * built-in slash commands). Refused with error \"busy\" unless force.\n */\n | {\n op: \"command\";\n name: CtlCommandName;\n instructions?: string;\n force?: boolean;\n /** As on `send`: another incarnation is refused before any session change. */\n expectIncarnation?: string;\n };\n\n/** Session commands the `command` op runs: `/new`, `/reload`, `/compact`. */\nexport const CTL_COMMANDS = [\"new\", \"reload\", \"compact\"] as const;\nexport type CtlCommandName = (typeof CTL_COMMANDS)[number];\n\n/**\n * Every op this protocol defines. The extension reports the ops it serves\n * in its `hello` reply (and in an unknown-op error), so mu can tell an\n * extension loaded by an older pi process from a broken one.\n */\nexport const CTL_OPS = [\n \"hello\",\n \"status\",\n \"send\",\n \"wait\",\n \"abort\",\n \"interrupt\",\n \"fresh\",\n \"command\",\n] as const satisfies readonly CtlRequest[\"op\"][];\n\n/**\n * Optional capabilities, listed in the `hello` reply's `features`. Ops stay\n * as they are: a feature is a field an old client never sends and ignores.\n * `fence`: `expectIncarnation` is honoured on every side-effecting op\n * (send, fresh, interrupt, command); an extension without it ignores the\n * field on interrupt and command, so a caller never relies on it there.\n */\nexport const CTL_FEATURES = [\"incarnation\", \"msgId\", \"fence\"] as const;\nexport type CtlFeature = (typeof CTL_FEATURES)[number];\n\n/** How many accepted msgIds the extension remembers (oldest evicted). */\nexport const CTL_MSGID_MEMORY = 64;\n/** Longest msgId the extension accepts. */\nexport const CTL_MSGID_MAX_LENGTH = 64;\n\n/** Error text of a `wait`, `send` or `fresh` that named another pi process's incarnation. */\nexport const INCARNATION_MISMATCH = \"incarnation mismatch\";\n\n/** The tool pi is executing (innermost, latest started); `since` is ms epoch. */\nexport type CtlTool = { name: string; since: number };\n\nexport type CtlStatus = {\n state: CtlState;\n since: number;\n runs: number;\n pending: boolean;\n /** The pi session file (where the transcript is written); absent for an ephemeral pi or an older extension. */\n sessionFile?: string;\n /** Set while pi waits on an extension dialog; absent from older extensions. */\n blocked?: CtlBlocked;\n /** The running tool, `null` when none; absent from older extensions (unknown, not \"none\"). */\n tool?: CtlTool | null;\n};\n\nexport type CtlReply =\n | ({ v: 1; ok: true } & Partial<CtlStatus> & {\n agent?: string;\n workstream?: string;\n piVersion?: string;\n /** hello only: the ops this extension serves. Absent: predates reporting. */\n ops?: string[];\n /** hello only: the optional features this extension serves. Absent: none. */\n features?: string[];\n /**\n * hello, status, send, fresh, interrupt, wait: minted once per pi\n * process per socket; stable across /new and /reload, new after pi\n * restarts. Absent from older extensions.\n */\n incarnation?: string;\n /** status with msgId only: whether that msgId was accepted, and the reply's `runs`/time if so. */\n msg?: { id: string; accepted: boolean; runs?: number; at?: number };\n /** hello only: the mu package version the extension was built from. */\n extVersion?: string;\n /** wait only: \"blocked\" when a dialog ended the wait before a settle (returnOnBlocked). */\n ended?: \"settled\" | \"blocked\";\n /** wait only: text of the settled run's final assistant message (\"\" when none). */\n lastText?: string;\n /** wait only: true when `lastText` lost its head to the 64 KiB tail cap. Absent otherwise. */\n lastTextTruncated?: boolean;\n /** wait only: the error that ended the settled run (retries exhausted). */\n lastError?: string;\n /** wait only: the settled pi's session file, where its full transcript lives. */\n sessionFile?: string;\n /**\n * abort, interrupt: pi was busy, so a turn was aborted. For abort,\n * absent from older extensions (which always call abort).\n */\n wasBusy?: boolean;\n })\n | {\n v: 1;\n ok: false;\n error: string;\n ops?: string[];\n /** With INCARNATION_MISMATCH: the extension's current incarnation. */\n incarnation?: string;\n };\n\n/** Error text of a reply to an op the extension does not serve. */\nexport const UNKNOWN_OP_PREFIX = \"unknown op: \";\n\n/** One frame. JSON.stringify escapes \"\\n\" inside strings, so the frame is one line. */\nexport function encode(msg: object): string {\n return `${JSON.stringify(msg)}\\n`;\n}\n\n/** Splits a stream into lines on \"\\n\" only (never U+2028/U+2029). */\nexport class LineDecoder {\n private buf = \"\";\n\n push(chunk: string): string[] {\n this.buf += chunk;\n const parts = this.buf.split(\"\\n\");\n this.buf = parts.pop() ?? \"\";\n return parts;\n }\n}\n","/**\n * mu pi extension, parent side: the `mu_delegate` tool.\n *\n * A delegate is a scratch agent started for one task. The tool spawns it,\n * hands it the task and returns at once. When the delegate's run settles its\n * answer is recorded (`mu delegates finish`: verdict note, report, close) and\n * the parent's settle wait shows it to the model (nudge.ts). The one identity\n * is the call id; the pi message this side sends is only a WAKE, a one-line\n * pointer that starts a turn when pi is idle and nothing else will. Losing or\n * repeating a wake loses or repeats no answer.\n *\n * Everything is the `mu` CLI (spawn / send / wait --json / read / abort /\n * close): the tool only orders the calls and formats the result, so a\n * shell gets the same delegation (VISION § 1, rule 2). With no multiplexer\n * the spawn fails NoMultiplexerError and the call runs as a child pi under\n * `mu delegates run <call-id>` instead (src/delegate-process.ts). The one\n * thing only an extension can do is the callback into the parent\n * conversation, and that is presentation. No extension-only state: the\n * in-flight set below is the list of `mu agent wait` children this pi owns.\n *\n * Separate from the child side (the control-socket server in mu-pi.ts):\n * that one serves a pi mu spawned; this one runs in a pi that is not.\n */\nimport { randomBytes } from \"node:crypto\";\nimport { statSync } from \"node:fs\";\nimport { qualifiedRefProblem, workstreamNameProblem } from \"../src/workstream-scope.js\";\nimport { labelStem, modelCommand, normalizeModel } from \"./delegate-args.js\";\nimport {\n type CallInfo,\n callInfoOf,\n callsApi,\n type FinishResult,\n type RecordTarget,\n} from \"./delegate-calls.js\";\nimport {\n DELEGATE_TIMEOUT_S,\n DELEGATE_WORKSTREAM,\n type DroppedWake,\n delegateMessage,\n droppedNote,\n evidenceLines,\n lastAssistantTextIn,\n type MessageExtras,\n type PaneFate,\n type WaitAgent,\n type WakeAnswer,\n wakeText,\n} from \"./delegate-format.js\";\nimport { type ProcessRun, processFailedText, processStarted } from \"./delegate-process-format.js\";\nimport { delegateTraceOn, TRACE_EVENTS, trace, traceFields } from \"./delegate-trace.js\";\nimport {\n defaultRunner,\n type MuResult,\n type MuRunner,\n parseEnvelope,\n parseOkEnvelope,\n} from \"./mu-run.js\";\n\nexport { recordNote } from \"../src/delegate-verdict.js\";\nexport { labelStem, modelCommand, normalizeModel } from \"./delegate-args.js\";\nexport {\n DELEGATE_TIMEOUT_S,\n DELEGATE_WORKSTREAM,\n type DroppedWake,\n delegateMessage,\n droppedNote,\n formatElapsed,\n lastAssistantTextIn,\n type MessageExtras,\n type PaneFate,\n type WaitAgent,\n type WakeAnswer,\n wakeText,\n} from \"./delegate-format.js\";\nexport { delegateTraceOn, delegateTracePath } from \"./delegate-trace.js\";\nexport {\n defaultRunner,\n type MuResult,\n type MuRunner,\n parseEnvelope,\n parseOkEnvelope,\n} from \"./mu-run.js\";\n\n/** The slice of pi's ExtensionAPI the delegate side uses. */\nexport interface MuDelegateApi {\n registerTool(tool: DelegateTool): void;\n sendMessage(\n message: { customType: string; content: string; display: boolean; details?: unknown },\n options?: { triggerTurn?: boolean; deliverAs?: \"steer\" | \"followUp\" | \"nextTurn\" },\n ): void | Promise<void>;\n on(event: string, handler: (event: unknown, ctx: DelegateCtx) => unknown): unknown;\n /** pi's in-process bus between extensions. */\n events: { emit(channel: string, data: unknown): void };\n}\n\n/** The slice of pi's ExtensionContext the delegate side uses. */\nexport interface DelegateCtx {\n sessionManager?: { getSessionId?(): string };\n hasUI?: boolean;\n cwd?: string;\n isIdle?(): boolean;\n hasPendingMessages?(): boolean;\n ui?: {\n notify(message: string, type?: \"info\" | \"warning\" | \"error\"): void;\n /** Raw terminal input, non-consuming here (the settle wait's Esc). */\n onTerminalInput?(handler: (data: string) => undefined): () => void;\n };\n}\n\ntype ToolResult = { content: { type: \"text\"; text: string }[]; details: unknown };\n\nexport interface DelegateTool {\n name: string;\n label: string;\n description: string;\n promptSnippet?: string;\n parameters: object;\n execute(\n id: string,\n params: Record<string, unknown>,\n signal?: AbortSignal,\n onUpdate?: unknown,\n ctx?: DelegateCtx,\n ): Promise<ToolResult>;\n}\n\nexport const DELEGATE_TOOL = \"mu_delegate\";\nexport const DELEGATE_CANCEL_TOOL = \"mu_delegate_cancel\";\nexport const DELEGATE_REISSUE_TOOL = \"mu_delegate_reissue\";\nexport const DELEGATE_MESSAGE_TYPE = \"mu-delegate\";\n/**\n * murmur's channel for outstanding background work, as\n * `{ source, count }`. murmur shows the count on this agent's card,\n * renders a stopped agent with work out as `waiting`, and holds back\n * `done` until it is zero: a parent that ended its turn to wait on\n * delegates has not finished. A string, not an import: neither side\n * depends on the other, and with no murmur loaded nobody listens.\n */\nexport const PENDING_CHANNEL = \"murmur:pending\";\n\n/** Default cap on delegates in flight from one pi session. */\nexport const DELEGATE_MAX_DEFAULT = 16;\n/** The queue holds this many caps' worth of calls waiting for a slot. A\n * fan-out (refuters per finding, checkers per claim) issues several\n * caps' worth in one turn; past this, the model is refused. */\nexport const DELEGATE_QUEUE_FACTOR = 4;\n\n/** `MU_DELEGATE_MAX`: a positive integer, else the default. */\nexport function delegateMax(env: NodeJS.ProcessEnv = process.env): number {\n const n = Number(env.MU_DELEGATE_MAX);\n return Number.isInteger(n) && n > 0 ? n : DELEGATE_MAX_DEFAULT;\n}\nconst W = DELEGATE_WORKSTREAM;\n\n/** Registration guards: an unmanaged pi, not switched off. No mux needed:\n * without one a delegate runs as a child pi process (`mu delegates run`). */\nexport function delegateEnabled(env: NodeJS.ProcessEnv = process.env): boolean {\n if (env.MU_MANAGED_AGENT) return false; // no helper-spawns-helper\n return env.MU_DELEGATE !== \"0\";\n}\n\nfunction isDir(p: string): boolean {\n try {\n return statSync(p).isDirectory();\n } catch {\n return false;\n }\n}\n\n/** Which agent a delegate spawned as: the registry incarnation and pane the\n * spawn reported. A close acts on that one only, never on a replacement\n * that took the name since. */\nexport type DelegateIdentity = { paneId: string; incarnation: number };\n\n/**\n * One delegate this pi waits on. `cancelling` is set while a cancel's abort\n * is in flight: the abort itself settles the run, so a wait resolving then\n * is parked in `parked` instead of delivered, and delivered after all if\n * the abort fails.\n */\ntype Inflight = {\n abort: AbortController;\n call: CallInfo;\n /** The delegate's pi session file, reported by the spawn's send. */\n sessionFile?: string;\n /** What it spawned as; closing is bound to it. */\n identity?: DelegateIdentity;\n cancelling: boolean;\n parked?: () => Promise<void>;\n /** Mux-free: the `mu delegates run` of a child pi, no pane. Aborting\n * `abort` SIGTERMs it, which cancels the call durably before it exits. */\n process?: Promise<MuResult>;\n};\n\n/** A call past the cap, waiting for a slot. Its delegate name is picked\n * at spawn, so the queue also hands out a handle (`queued-3`); the call\n * id works as well. `registered` settles once its row is durable. */\ntype Queued = {\n handle: string;\n call: CallInfo;\n ctx: DelegateCtx | undefined;\n /** Settles once the call's row is durable. */\n registered: Promise<unknown>;\n};\n\n/** The pi session id of a ctx whose sessionManager exposes it (a stale ctx throws). */\nfunction piSessionId(ctx: DelegateCtx | undefined): string | undefined {\n try {\n const sm = (ctx as { sessionManager?: { getSessionId?: () => string } } | undefined)\n ?.sessionManager;\n return sm?.getSessionId?.();\n } catch {\n return undefined;\n }\n}\n\n/** What the rest of the extension may ask the delegate side. */\nexport interface DelegateHandle {\n /** A wake is being delivered or waits in pi's follow-up queue: its own turn\n * runs the settle wait. pi's hasPendingMessages() does not count custom\n * follow-ups, so this is the only signal. */\n answerPending(): boolean;\n /** The settle showed these answers (call ids), or found nothing owed by a wait\n * started at epoch ms `before`: no wake is owed for them. */\n delivered(shown: readonly string[] | { before: number }): void;\n}\n\nexport function registerDelegate(\n pi: MuDelegateApi,\n run: MuRunner = defaultRunner(),\n): DelegateHandle {\n if (!delegateEnabled()) return { answerPending: () => false, delivered: () => {} };\n if (delegateTraceOn())\n for (const ev of TRACE_EVENTS)\n pi.on(ev, (e, ctx) => {\n trace(ev, traceFields(e, ctx));\n });\n /** pi.sendMessage, traced: the call, its options, and how it returned. */\n const send = (\n message: Parameters<MuDelegateApi[\"sendMessage\"]>[0],\n options: Parameters<MuDelegateApi[\"sendMessage\"]>[1],\n why: string,\n ): void | Promise<void> => {\n const d = message.details as { wake?: unknown; calls?: unknown } | undefined;\n const a = typeof d?.wake === \"number\" ? arriving.get(d.wake) : undefined;\n if (a && options) {\n options = { ...options };\n a.message = message;\n a.opts = [...(a.opts ?? []), options];\n }\n const at = { why, wake: d?.wake, calls: d?.calls, ...options };\n trace(\"sendMessage\", { ...at, arriving: arriving.size });\n try {\n const r = pi.sendMessage(message, options);\n trace(\"sendMessage.returned\", { ...at, async: r !== undefined });\n return r;\n } catch (e) {\n trace(\"sendMessage.threw\", { ...at, error: String(e) });\n throw e;\n }\n };\n const inflight = new Map<string, Inflight>();\n /** Calls past the cap check whose delegate is not yet in `inflight`. */\n let starting = 0;\n /** Calls past the cap, FIFO, at most `DELEGATE_QUEUE_FACTOR * delegateMax()` long. */\n const queue: Queued[] = [];\n let queueSeq = 0;\n /** Answers recorded here that no settle has shown yet and no wake has\n * carried into the conversation, by call id. */\n const owed = new Map<string, WakeAnswer & { at: number }>();\n /** Wakes that have not entered the conversation: being delivered, or queued\n * behind a running turn. Keyed by a per-wake id carried in the message's\n * details, cleared on its message_start. `sent`: pi.sendMessage returned (pi\n * accepted it, which says nothing about where it sits). */\n const arriving = new Map<\n number,\n {\n sent: boolean;\n calls: string[];\n /** The wake as sent, to send again if pi's queue loses it. */\n message?: Parameters<MuDelegateApi[\"sendMessage\"]>[0];\n /** Sent again after pi lost it; one more loss drops it. */\n resent?: boolean;\n /** Every options object handed to pi for it: pi reads one lazily when it\n * runs a send it deferred, so a dropped wake is defused through them. */\n opts?: { triggerTurn?: boolean; deliverAs?: \"steer\" | \"followUp\" | \"nextTurn\" }[];\n }\n >();\n let wakeSeq = 0;\n /** A pi run is active (agent_start .. agent_settled): its settle will look. */\n let busy = false;\n let settleCheck: ReturnType<typeof setImmediate> | undefined;\n let closed = false;\n let lastPending = 0;\n /** Running, starting and queued: every delegate whose answer is still\n * to come back here. Failed panes have answered, so they do not count. */\n const reportPending = () => {\n const count = inflight.size + starting + queue.length;\n if (count === lastPending) return;\n lastPending = count;\n try {\n pi.events.emit(PENDING_CHANNEL, { source: DELEGATE_TOOL, count });\n } catch {\n // a listener's fault must not cost a delegate its answer\n }\n };\n /** Wake pi for every owed answer no wake covers yet: ONE message, a pointer per\n * answer; its turn's settle delivers the reports. */\n const wake = (why: string) => {\n const covered = new Set([...arriving.values()].flatMap((a) => a.calls));\n const due = [...owed.values()].filter((a) => !covered.has(a.callId));\n if (due.length === 0 || closed) return;\n const id = ++wakeSeq;\n const ids = due.map((a) => a.callId);\n arriving.set(id, { sent: false, calls: ids });\n void Promise.resolve(\n send(\n {\n customType: DELEGATE_MESSAGE_TYPE,\n content: wakeText(due),\n display: true,\n details: { wake: id, calls: ids },\n },\n { deliverAs: \"followUp\", triggerTurn: true },\n why,\n ),\n ).then(\n () => {\n const a = arriving.get(id);\n if (a) a.sent = true;\n },\n () => arriving.delete(id), // nothing will arrive; the next settle looks again\n );\n };\n let wakeSoon: ReturnType<typeof setImmediate> | undefined;\n /** An answer recorded while pi is idle: nothing will settle and show it, so\n * wake now (batched: answers recorded in one tick share one wake). */\n const wakeIfIdle = () => {\n if (wakeSoon !== undefined) return;\n wakeSoon = setImmediate(() => {\n wakeSoon = undefined;\n if (!busy) wake(\"wake\");\n });\n };\n const calls = callsApi(run);\n /** Per runtime: two reloads of one session never reuse a call id. */\n const token = randomBytes(3).toString(\"hex\");\n let callSeq = 0;\n const inflightKey = (ws: string, name: string) => `${ws}/${name}`;\n /** Drop a delegate from the in-flight set, start the next queued call\n * into the freed slot. */\n const forget = (key: string) => {\n inflight.delete(key);\n drain();\n reportPending();\n };\n /** A start that failed after its tool call returned, said as a follow-up. */\n const startFailed = (handle: string, e: unknown, what = \"Queued delegate\") =>\n void Promise.resolve(\n send(\n {\n customType: DELEGATE_MESSAGE_TYPE,\n content: `${what} ${handle} could not start: ${e instanceof Error ? e.message : String(e)}`,\n display: true,\n details: { name: handle, workstream: W, outcome: null, closed: false },\n },\n { deliverAs: \"followUp\", triggerTurn: true },\n \"start-failed\",\n ),\n ).catch(() => {});\n /** Start queued calls while there is a free slot. A queued call's tool\n * call has already returned, so a failed start becomes a follow-up. */\n function drain(): void {\n while (queue.length > 0 && inflight.size + starting < delegateMax()) {\n const q = queue.shift();\n if (!q) break;\n starting++; // held until start() takes over the slot\n void q.registered\n .then(async () => {\n try {\n await calls.mark(q.call.callId, \"starting\");\n } catch (e) {\n starting--; // start() never ran: its finally would have freed the slot\n reportPending();\n throw e;\n }\n return start(q.call, undefined, q.ctx, q.handle);\n })\n .then(\n () => {},\n (e: unknown) => {\n startFailed(q.handle, e);\n drain();\n },\n );\n }\n }\n\n const mu = run;\n // mu prints ONE envelope: `{ok:true,data,next}` or `{ok:false,error,message,\n // next,exit,data?}`. A success yields its `data`; a failure yields its\n // partial `data` (a spawn whose --send failed) plus `error` and `message`.\n const json = (r: MuResult): Record<string, unknown> | undefined => parseEnvelope(r.stdout);\n /** One line on why a call failed: the envelope's message, else the raw text. */\n const why = (r: MuResult): string => {\n const m = json(r)?.message;\n return (typeof m === \"string\" ? m : r.stderr || r.stdout).trim();\n };\n const failure = (what: string, r: MuResult) =>\n new Error(`${what} failed (exit ${r.code}): ${why(r)}`);\n /** The words for a failed `mu delegates` write. */\n const errText = (e: unknown) => (e instanceof Error ? e.message : String(e));\n\n /**\n * Close a delegate's pane, bound to the agent it spawned as. `agent close`\n * only previews until it gets `--if <revision>`, so: preview, check that\n * the preview is a success envelope for THIS pane and incarnation with a\n * safe-integer revision, then apply once with that revision. Anything\n * else (no identity, a failed or malformed preview, another incarnation\n * under the name, a stale revision) keeps the pane and says why. It never\n * previews again and never retries onto a replacement.\n */\n async function closeDelegate(\n name: string,\n id: DelegateIdentity | undefined,\n W: string,\n ): Promise<PaneFate> {\n if (id === undefined) return { closed: false, why: \"its spawn did not report an identity\" };\n const p = await mu([\"agent\", \"close\", name, \"-w\", W, \"--json\"]);\n const d = p.code === 0 ? parseOkEnvelope(p.stdout) : undefined;\n if (d === undefined) return { closed: false, why: `close preview failed: ${why(p)}` };\n if (d.kind === \"none\") return { closed: false, why: \"it is no longer registered\" };\n if (d.kind !== \"agent\" || d.id !== id.incarnation || d.pane_id !== id.paneId)\n return { closed: false, why: \"the name now belongs to another agent\" };\n if (!Number.isSafeInteger(d.revision))\n return { closed: false, why: \"close preview had no revision\" };\n const c = await mu([\"agent\", \"close\", name, \"-w\", W, \"--if\", String(d.revision), \"--json\"]);\n return c.code === 0 ? { closed: true } : { closed: false, why: `close refused: ${why(c)}` };\n }\n\n /** A spawn that failed. `unsent`: nothing was written to a pane, so the call\n * stays reissuable (refused). `kept`: a pane may be running; it is evidence. */\n class SpawnFail extends Error {\n constructor(\n message: string,\n readonly kind: \"unsent\" | \"kept\" | \"unknown\" | \"aborted\" | \"refused\" | \"nomux\",\n ) {\n super(message);\n }\n }\n\n /**\n * Spawn the delegate bound to its task and send it the prompt in ONE mu call\n * (`spawn --next-free --task <delegate task> --attempt <task> --send`): mu\n * picks the free name under its spawn lock, claims the task for the new\n * agent and journals the delivery, so a replay never sends twice. Returns\n * the name and the send's `runs`, the exact wait baseline.\n */\n async function spawn(\n call: CallInfo,\n text: string,\n cwd: string | undefined,\n signal?: AbortSignal,\n ): Promise<{\n name: string;\n runs: number;\n attach?: string;\n workspace?: string;\n sessionFile?: string;\n identity?: DelegateIdentity;\n }> {\n if (signal?.aborted) throw new SpawnFail(\"cancelled before it spawned\", \"aborted\");\n const ws = call.workstream;\n const req = call.request;\n const stem = labelStem(req.label);\n // A label names the delegate (delegate-review, then delegate-review-2);\n // without one it is numbered (delegate-1, delegate-2).\n const base = stem ? `delegate-${stem}` : \"delegate-1\";\n const args = [\n \"agent\",\n \"spawn\",\n base,\n \"-w\",\n ws,\n \"--next-free\",\n \"--task\",\n call.task,\n \"--attempt\",\n call.task,\n \"--send\",\n text,\n \"--json\",\n ];\n // With a workspace, cwd names the git repo the worktree is made from.\n if (req.workspace === true) args.push(\"--worktree\", ...(req.cwd ? [\"--root\", req.cwd] : []));\n else if (cwd) args.push(\"--cwd\", cwd);\n const cli = req.cli ? req.cli : undefined;\n if (cli) args.push(\"--cli\", cli);\n if (req.model) args.push(\"--command\", modelCommand(cli ?? \"pi\", req.model));\n // An abort SIGTERMs the spawn, which rolls itself back; the runner returns once it exited.\n const r = await mu(args, signal);\n const out = json(r);\n const stale = (out?.task as { stale?: unknown } | undefined)?.stale;\n if (typeof stale === \"string\")\n throw new SpawnFail(\n `the attempt of ${ws}/${call.task} is stale: its agent was ${stale}; the replacement was left alone`,\n \"unsent\",\n );\n const spawned = (out?.agent as { name?: unknown } | undefined)?.name;\n // No multiplexer, nothing spawned: start() runs it as a child pi instead.\n // Only this error: any other failure is not a licence to start it twice.\n if (typeof spawned !== \"string\" && out?.error === \"NoMultiplexerError\")\n throw new SpawnFail(\"no multiplexer\", \"nomux\");\n // No agent in the reply: the spawn itself failed, nothing is up.\n if (typeof spawned !== \"string\" && signal?.aborted)\n throw new SpawnFail(\"cancelled while it spawned; the spawn rolled back\", \"aborted\");\n if (typeof spawned !== \"string\") {\n const msg = failure(\"mu agent spawn\", r).message;\n // A refusal that fails the same on every reissue is final, not 'reissue'.\n if (out?.error === \"WorktreeVcsRequiredError\")\n throw new SpawnFail(`${msg}. Pass cwd: <a git repo>`, \"refused\");\n throw new SpawnFail(msg, out?.error === \"UsageError\" ? \"refused\" : \"unsent\");\n }\n const name = spawned;\n // The agent record's SQL keys: `id` is the registry incarnation.\n const row = out?.agent as { pane_id?: unknown; id?: unknown; cwd?: unknown } | undefined;\n const identity: DelegateIdentity | undefined =\n typeof row?.pane_id === \"string\" && Number.isSafeInteger(row.id)\n ? { paneId: row.pane_id, incarnation: row.id as number }\n : undefined;\n if (signal?.aborted) {\n // The user cancelled while the pane came up: take it down again.\n await closeDelegate(name, identity, ws);\n throw new SpawnFail(\"cancelled while it spawned\", \"aborted\");\n }\n // A fresh spawn reports its control socket; a replay answers from the\n // journal and carries none (the send below is the proof).\n if (out?.ctl !== undefined && out.ctl !== \"ok\") {\n throw new SpawnFail(\n `${ws}/${name} spawned but its control socket is ${String(out.ctl)}, so its answer cannot come back. Pane kept; close it with: mu agent close ${name} -w ${ws}`,\n \"kept\",\n );\n }\n const sent = out?.send as\n | { ok?: unknown; error?: unknown; runs?: unknown; message?: unknown; sessionFile?: unknown }\n | undefined;\n if (sent?.ok !== true && sent?.error === \"AgentSendIndeterminateError\") {\n // The prompt may already be running: keep the pane, never auto-retry.\n const reason = typeof sent.message === \"string\" ? sent.message : \"no reply\";\n throw new SpawnFail(\n `mu agent send to ${ws}/${name}: delivery unknown (${reason}). Pane kept; do NOT resend blindly. Check with: mu agent read ${name} -w ${ws} -n 20 (or attach), then close it with: mu agent close ${name} -w ${ws}`,\n \"unknown\",\n );\n }\n if (sent?.ok !== true) {\n // Nothing reached it: the pane is just an idle pi. Take it down.\n const c = await closeDelegate(name, identity, ws);\n const pane = c.closed\n ? \"Pane closed.\"\n : `Pane kept (${c.why}); close it with: mu agent close ${name} -w ${ws}`;\n const reason = typeof sent?.message === \"string\" ? sent.message : why(r);\n throw new SpawnFail(\n `mu agent send to ${ws}/${name} failed (exit ${r.code}): ${reason}. ${pane}`,\n \"unsent\",\n );\n }\n const attach: unknown = out?.attach;\n // The worktree is the agent's cwd (`agents.cwd`).\n const wsPath = req.workspace === true ? (row as { cwd?: unknown } | undefined)?.cwd : undefined;\n return {\n name,\n // A pi just spawned has settled no run, so 0 is exact when an older\n // extension's reply carries no runs.\n runs: typeof sent.runs === \"number\" ? sent.runs : 0,\n ...(identity ? { identity } : {}),\n ...(typeof attach === \"string\" ? { attach } : {}),\n ...(typeof wsPath === \"string\" ? { workspace: wsPath } : {}),\n ...(typeof sent.sessionFile === \"string\" ? { sessionFile: sent.sessionFile } : {}),\n };\n }\n\n /** Check `record` names a real task, before anything spawns. */\n async function resolveRecord(raw: unknown): Promise<RecordTarget | undefined> {\n if (raw === undefined) return undefined;\n const r = raw as { task?: unknown; workstream?: unknown } | null;\n const task = typeof r?.task === \"string\" ? r.task : \"\";\n if (task.trim() === \"\") throw new Error(\"mu_delegate: record.task must name a task\");\n // The one validator (never trims): an empty, blank or padded scope is an\n // error here, as it is at the CLI, never another valid workstream.\n const scope = (value: string, what: string): string => {\n const problem = workstreamNameProblem(value, what);\n if (problem !== undefined) throw new Error(`mu_delegate: ${problem} Nothing spawned.`);\n return value;\n };\n const rawWs = r?.workstream;\n const ws =\n rawWs === undefined || rawWs === null\n ? \"\"\n : scope(typeof rawWs === \"string\" ? rawWs : String(rawWs), \"record.workstream\");\n const slash = task.indexOf(\"/\");\n if (slash >= 0) {\n const refProblem = qualifiedRefProblem(task);\n if (refProblem !== undefined) throw new Error(`mu_delegate: ${refProblem} Nothing spawned.`);\n const prefix = task.slice(0, slash);\n if (ws && ws !== prefix) {\n throw new Error(\n `mu_delegate: record.task ${task} conflicts with record.workstream ${ws}. Nothing spawned.`,\n );\n }\n }\n if (task !== task.trim()) {\n throw new Error(\n `mu_delegate: record.task ${JSON.stringify(task)} has surrounding whitespace. Nothing spawned.`,\n );\n }\n // Scope is explicit: <ws>/<task> or record.workstream. mu has no ambient\n // default, so refuse here, before anything spawns, rather than let `task\n // show` guess or fail after the fact.\n if (!ws && slash < 0) {\n throw new Error(\n `mu_delegate: record.task ${task} needs a workstream: pass record.task as <workstream>/${task}, or set record.workstream. Nothing spawned.`,\n );\n }\n const shown = await mu([\"task\", \"show\", task, ...(ws ? [\"-w\", ws] : []), \"--json\"]);\n const out = json(shown);\n // `show` names the task by `id` (its local_id) and its workstream by `workstream`.\n const t = out?.task as { id?: unknown; workstream?: unknown } | undefined;\n if (shown.code !== 0 || typeof t?.id !== \"string\" || typeof t.workstream !== \"string\") {\n throw new Error(\n `mu_delegate: record task ${ws ? `${ws}/` : \"\"}${task} not found (exit ${shown.code}): ${why(shown)}. Nothing spawned.`,\n );\n }\n return { workstream: t.workstream, task: t.id };\n }\n\n /** The follow-up's line about where the answer is durable (a failed record only). */\n const recordedLine = (call: CallInfo, err: string): string =>\n `Recording failed: ${err}. The call ${call.callId} is still open; its answer is in this message. Record it yourself.`;\n\n /**\n * Record one finished wait, then let the settle show it. The result is made\n * durable FIRST: the verdict on the judged task, then the delegate's report\n * and close, in one op group (`mu delegates finish`). A run with no final\n * answer records what the follow-up used to say (outcome, error, what to do,\n * session, partial text, pane tail). Only a `done` call may then lose its\n * pane. A record that failed leaves nothing for a wait to find: that answer\n * alone is sent whole, as a follow-up.\n */\n async function deliver(\n call: CallInfo,\n name: string,\n wait: MuResult,\n keep: boolean,\n extras: MessageExtras,\n identity?: DelegateIdentity,\n ) {\n const ws = call.workstream;\n const agent = (json(wait)?.agents as WaitAgent[] | undefined)?.[0];\n const outcome = agent?.outcome;\n const tail =\n outcome === \"done\" || outcome === \"timeout\" || outcome === \"pending\" || outcome === \"error\"\n ? undefined\n : (await mu([\"agent\", \"read\", name, \"-n\", \"50\", \"-w\", ws])).stdout;\n const sessionFile = agent?.sessionFile ?? extras.sessionFile;\n const x: MessageExtras = {\n ...extras,\n workstream: ws,\n ...(sessionFile ? { sessionFile } : {}),\n ...(tail ? { tail } : {}),\n };\n // A blocked run is mid-flight: no partial text, which could read as its answer.\n const partial =\n outcome !== \"done\" && outcome !== \"blocked\" && sessionFile\n ? lastAssistantTextIn(sessionFile)\n : undefined;\n // What a gap records: its own wording (the pane is kept for every outcome but\n // empty, and the pane line is the only difference), plus what it wrote so far.\n const kept: PaneFate = {\n closed: false,\n why: outcome === \"blocked\" ? \"waiting on a dialog\" : \"kept as evidence\",\n };\n const gap = () =>\n [\n delegateMessage(\n name,\n agent,\n outcome === \"empty\" ? ({ closed: !keep } as PaneFate) : kept,\n x,\n ),\n partial ? `Partial answer so far:\\n${partial}` : undefined,\n ]\n .filter((v) => v !== undefined)\n .join(\"\\n\\n\");\n let fin: FinishResult | undefined;\n let finErr = \"unknown error\";\n try {\n fin = await calls.finish(call.callId, {\n outcome: outcome ?? \"no result\",\n text: outcome === \"done\" ? (agent?.lastText ?? \"\") : gap(),\n ...(extras.elapsedMs !== undefined ? { elapsedMs: extras.elapsedMs } : {}),\n author: name,\n });\n } catch (e) {\n finErr = errText(e);\n }\n // Close only after a clean finish that is on record: a died or timed-out\n // pane, or one whose record failed, is evidence.\n let pane: PaneFate = { closed: false, why: \"keep: true\" };\n if (outcome === \"blocked\") pane = kept;\n else if (outcome !== \"done\" && outcome !== \"empty\") pane = kept;\n else if (fin?.state !== \"done\" && outcome === \"done\")\n pane = { closed: false, why: \"its result is not recorded\" };\n else if (!keep) pane = await closeDelegate(name, identity, ws);\n if (fin === undefined) {\n // Nothing durable for the settle to show: the whole answer, once, here.\n await send(\n {\n customType: DELEGATE_MESSAGE_TYPE,\n content: `${delegateMessage(name, agent, pane, x)}\\n\\n${recordedLine(call, finErr)}`,\n display: true,\n details: { name, workstream: ws, call_id: call.callId, outcome: outcome ?? null },\n },\n { deliverAs: \"followUp\", triggerTurn: true },\n \"unrecorded\",\n );\n return;\n }\n owed.set(call.callId, {\n callId: call.callId,\n name,\n workstream: ws,\n task: call.task,\n // A failed record says so (the answer is kept as the report): record it yourself.\n outcome:\n fin.state === \"failed\" && fin.error\n ? `${outcome ?? \"no result\"}, NOT recorded: ${fin.error}`\n : (outcome ?? \"no result\"),\n ...(fin.verdict ? { verdict: fin.verdict } : {}),\n ...(call.record && fin.recorded\n ? { record: `${call.record.workstream}/${call.record.task}` }\n : {}),\n ...(pane.closed ? {} : { kept: pane.why }),\n at: Date.now(),\n });\n wakeIfIdle();\n }\n\n /**\n * Watch one running pane delegate (`mu agent wait` past `runs`) and deliver\n * its answer when its run settles. Used by a fresh start and by a reloaded\n * runtime re-adopting a call the previous runtime was watching.\n */\n async function watch(\n call: CallInfo,\n name: string,\n runs: number,\n o: {\n keep: boolean;\n timeoutS: number;\n queuedAs?: string;\n attach?: string;\n workspace?: string;\n sessionFile?: string;\n identity?: DelegateIdentity;\n /** Epoch ms the delegate started running (default now). A re-adopted call\n * passes its durable start, so `timeoutS` stays one deadline across reloads. */\n startedAt?: number;\n /** Runs once the call is in `inflight`, before its wait starts. */\n tracked?: () => Promise<void>;\n },\n ): Promise<Inflight> {\n const ws = call.workstream;\n const key = inflightKey(ws, name);\n const entry: Inflight = {\n abort: new AbortController(),\n call,\n cancelling: false,\n ...(o.sessionFile ? { sessionFile: o.sessionFile } : {}),\n ...(o.identity ? { identity: o.identity } : {}),\n };\n inflight.set(key, entry);\n // The slot is released only now that the call is counted in `inflight`.\n if (o.tracked === undefined) reportPending();\n await o.tracked?.();\n // The send's `runs` is pi's count before this prompt: waiting past it\n // catches the run even if it settled before this wait started.\n const started = o.startedAt ?? Date.now();\n // What is left of the deadline; at least 1 s, so a run that settled while no\n // runtime watched (`--after-runs` still counts it) is recorded, not timed out.\n const left = Math.max(1, Math.ceil(o.timeoutS - (Date.now() - started) / 1000));\n const waiting = mu(\n [\n \"agent\",\n \"wait\",\n name,\n \"-w\",\n ws,\n \"--json\",\n \"--timeout\",\n String(left),\n \"--after-runs\",\n String(runs),\n ],\n entry.abort.signal,\n );\n const settle = async (r: MuResult) => {\n trace(\"settle\", { call: call.callId, name, code: r.code });\n forget(key);\n try {\n await deliver(\n call,\n name,\n r,\n o.keep,\n {\n timeoutS: o.timeoutS,\n elapsedMs: Date.now() - started,\n ...(o.queuedAs ? { queuedAs: o.queuedAs } : {}),\n ...(o.attach ? { attach: o.attach } : {}),\n ...(o.workspace ? { workspace: o.workspace } : {}),\n ...(entry.sessionFile ? { sessionFile: entry.sessionFile } : {}),\n },\n entry.identity,\n );\n } catch (e) {\n // A throw here would be an unhandled rejection and a lost answer.\n const content = `Delegate ${ws}/${name} settled, but delivering its answer failed: ${e instanceof Error ? e.message : String(e)}. Read it with: mu agent read ${name} -n 50 -w ${ws}`;\n await Promise.resolve(\n send(\n {\n customType: DELEGATE_MESSAGE_TYPE,\n content,\n display: true,\n details: { name, workstream: ws, outcome: null, closed: false },\n },\n { deliverAs: \"followUp\", triggerTurn: true },\n \"deliver-failed\",\n ),\n ).catch(() => {});\n }\n };\n void waiting.then(async (r) => {\n if (inflight.get(key) !== entry) return; // cancelled or shut down\n if (entry.cancelling) entry.parked = () => settle(r);\n else await settle(r);\n });\n return entry;\n }\n\n /** Spawn, send, and watch one registered call. The caller holds one\n * `starting` slot and has already moved the call to `starting`; the slot\n * is released once the delegate is in `inflight` (or on failure). A\n * failure is made durable here: nothing sent leaves the call refused\n * (reissuable), a pane that may be running fails it with the pane kept.\n * Returns the tool result. */\n async function start(\n call: CallInfo,\n signal: AbortSignal | undefined,\n ctx: DelegateCtx | undefined,\n queuedAs?: string,\n ): Promise<ToolResult> {\n let slotHeld = true;\n const freeSlot = () => {\n if (slotHeld) {\n starting--;\n reportPending();\n }\n slotHeld = false;\n };\n reportPending(); // the count moves at once, before the pane exists\n const ws = call.workstream;\n const req = call.request;\n try {\n const keep = req.keep === true;\n const timeoutS = req.timeoutS ?? DELEGATE_TIMEOUT_S;\n // Without --cwd the pane inherits the mux session's start dir (wherever\n // the FIRST scratch spawn ran), and a missing dir silently becomes\n // $HOME: pin it to the caller's and check it exists.\n let cwd: string | undefined;\n if (req.workspace !== true) {\n cwd = req.cwd ? req.cwd : (ctx?.cwd ?? process.cwd());\n if (!isDir(cwd))\n throw new SpawnFail(`mu_delegate: cwd ${cwd} is not a directory`, \"unsent\");\n }\n let spawned: Awaited<ReturnType<typeof spawn>>;\n try {\n spawned = await spawn(call, req.text, cwd, signal);\n } catch (e) {\n if (e instanceof SpawnFail && e.kind === \"nomux\") {\n freeSlot(); // startProcess counts it in inflight at once\n return startProcess(call);\n }\n const fail = e instanceof SpawnFail ? e : new SpawnFail(errText(e), \"unsent\");\n await settleFailedStart(call, fail);\n throw new Error(\n fail.kind === \"unsent\"\n ? `${fail.message}. The call is durable and refused: reissue it with ${DELEGATE_REISSUE_TOOL} { call_id: \"${call.callId}\" } (task ${ws}/${call.task}).`\n : `${fail.message}. Recorded on ${ws}/${call.task} as failed.`,\n );\n }\n const { name, runs, attach, workspace, sessionFile, identity } = spawned;\n await watch(call, name, runs, {\n keep,\n timeoutS,\n ...(queuedAs ? { queuedAs } : {}),\n ...(attach ? { attach } : {}),\n ...(workspace ? { workspace } : {}),\n ...(sessionFile ? { sessionFile } : {}),\n ...(identity ? { identity } : {}),\n tracked: async () => {\n freeSlot(); // now counted in inflight\n reportPending();\n await calls.mark(call.callId, \"running\", { agent: name }).catch((e) => {\n trace(\"mark.running.failed\", { call: call.callId, error: errText(e) });\n });\n },\n });\n const lines = [\n `Delegated to ${ws}/${name} (task ${ws}/${call.task}, call ${call.callId}). Its answer arrives with your next settle (and stays on the task: mu task notes ${call.task} -w ${ws}); carry on, or end your turn if your next step needs it. Do not poll.`,\n workspace ? `Workspace: ${workspace}` : undefined,\n attach ? `Attach: ${attach}` : undefined,\n `Cancel: ${DELEGATE_CANCEL_TOOL} { name: \"${name}\" }`,\n ].filter((x) => x !== undefined);\n return {\n content: [{ type: \"text\", text: lines.join(\"\\n\") }],\n details: {\n name,\n workstream: ws,\n task: `${ws}/${call.task}`,\n state: \"running\",\n call_id: call.callId,\n attach: attach ?? null,\n workspace: workspace ?? null,\n keep,\n },\n };\n } finally {\n // A start that threw frees its slot here, and a call queued while it\n // was starting must take that slot: drain whether queued or direct.\n freeSlot();\n drain();\n }\n }\n\n /**\n * No multiplexer: run the call as a child `pi --mode rpc` through\n * `mu delegates run <call-id>`, which sends once, waits, finishes the call\n * durably (verdict, report, close) and stops the child before it prints its\n * one result. The delegate is named by its task; there is no pane to attach\n * or close, and `keep` needs a pane (the run would hold its child forever),\n * so it is dropped here. A refused run (nothing sent) stays reissuable.\n */\n /** A run that exited without finishing its call (killed before its own\n * signal handler, or a crash) must not leave it starting: finish it. A\n * finished call ignores this, so the normal path writes nothing. */\n const finishOrphan = (call: CallInfo, outcome: string, text: string) =>\n calls.finish(call.callId, { outcome, text, author: call.caller }).catch((e: unknown) => {\n trace(\"finishOrphan.failed\", { call: call.callId, error: errText(e) });\n return undefined;\n });\n\n function startProcess(call: CallInfo): ToolResult {\n const ws = call.workstream;\n const name = call.task;\n const key = inflightKey(ws, name);\n const entry: Inflight = { abort: new AbortController(), call, cancelling: false };\n inflight.set(key, entry);\n reportPending();\n const settle = async (r: MuResult) => {\n const o = (json(r) ?? {}) as ProcessRun;\n forget(key);\n if (o.outcome === undefined || o.state === \"refused\") {\n const text = processFailedText(call, o, why(r), r.code, DELEGATE_REISSUE_TOOL);\n if (o.state !== \"refused\") await finishOrphan(call, \"error\", text);\n startFailed(name, new Error(text), \"Delegate\");\n return;\n }\n // The run finished the call durably (verdict, report, close): owed to the settle.\n const verdict = await calls\n .show(call.callId)\n .then((x) => x.verdict ?? undefined)\n .catch(() => undefined);\n owed.set(call.callId, {\n callId: call.callId,\n name,\n workstream: ws,\n task: call.task,\n outcome: o.outcome,\n ...(verdict ? { verdict } : {}),\n ...(call.record && o.state === \"done\"\n ? { record: `${call.record.workstream}/${call.record.task}` }\n : {}),\n at: Date.now(),\n });\n wakeIfIdle();\n };\n // A cancel's SIGTERM aborts the turn, finishes the call, then stops the\n // child (up to ~11 s); SIGKILL before that would orphan the child pi.\n const running = mu(\n [\"delegates\", \"run\", call.callId, \"--no-keep\", \"--json\"],\n entry.abort.signal,\n undefined,\n { drainMs: 20_000 },\n );\n entry.process = running;\n void running.then(async (r) => {\n if (inflight.get(key) !== entry) return; // cancelled or shut down\n await settle(r);\n });\n return processStarted(call, DELEGATE_CANCEL_TOOL);\n }\n\n /** Make a failed start durable: unsent -> refused (reissuable, brief kept);\n * a possibly-running pane -> finished as failed; a cancel -> cancelled. */\n async function settleFailedStart(call: CallInfo, fail: SpawnFail): Promise<void> {\n try {\n if (fail.kind === \"unsent\") await calls.mark(call.callId, \"refused\", { error: fail.message });\n else\n await calls.finish(call.callId, {\n outcome:\n fail.kind === \"aborted\" ? \"cancelled\" : fail.kind === \"unknown\" ? \"unknown\" : \"error\",\n text: fail.message,\n author: call.caller,\n });\n } catch (e) {\n trace(\"settleFailedStart.failed\", { call: call.callId, error: errText(e) });\n }\n }\n\n /** The delegate's own pi session file, for a never-started or cancelled call: none. */\n const callIdIn = (name: string) => name.startsWith(\"pi:\");\n\n /** Admit a registered call: a free slot starts it now, else the queue holds\n * it. (Refusal past the queue is decided by the caller, before it registers.) */\n const admission = (): \"starting\" | \"queued\" | \"refused\" => {\n const max = delegateMax();\n if (inflight.size + starting < max) return \"starting\";\n return queue.length < DELEGATE_QUEUE_FACTOR * max ? \"queued\" : \"refused\";\n };\n\n /** The text and details of a call that was queued or refused. */\n const queuedResult = (\n call: CallInfo,\n state: \"queued\" | \"refused\",\n handle: string,\n position: number,\n ): ToolResult => {\n const max = delegateMax();\n const taskRef = `${call.workstream}/${call.task}`;\n const text =\n state === \"refused\"\n ? `REFUSED, not started: ${inflight.size + starting} running and ${queue.length} queued (MU_DELEGATE_MAX=${max}). The call is durable (task ${taskRef}, call ${call.callId}) and will NOT start on its own. Reissue it once slots free, as answers arrive: ${DELEGATE_REISSUE_TOOL} { call_id: \"${call.callId}\" }. List: mu delegates.`\n : `Queued as ${handle} (#${position}; ${inflight.size + starting} running, MU_DELEGATE_MAX=${max}; task ${taskRef}, call ${call.callId}). It starts when a slot frees, and its answer arrives with a settle like any delegate's; do not poll. Cancel: ${DELEGATE_CANCEL_TOOL} { name: \"${handle}\" }`;\n return {\n content: [{ type: \"text\", text }],\n details: {\n name: handle,\n workstream: call.workstream,\n task: taskRef,\n state,\n call_id: call.callId,\n ...(state === \"queued\" ? { queued: true, position } : { refused: true }),\n },\n };\n };\n\n pi.registerTool({\n name: DELEGATE_TOOL,\n label: \"mu delegate\",\n description: `Subagent: run one self-contained task in a fresh pi agent (its own mux pane in mu's ${W} workstream; with no tmux or herdr, a child pi process with no pane) while you keep working. Use it whenever you would reach for a subagent: research, a review, a draft, an investigation, or a refuter of a claim, plan or fix before you act on it; call it several times to fan out in parallel (at most ${delegateMax()} run at once; up to ${DELEGATE_QUEUE_FACTOR * delegateMax()} more are queued and start as slots free; past that a call is refused: durable, reissue it with ${DELEGATE_REISSUE_TOOL}). Every call is a mu task (kind delegate): the result names it, and the full answer stays on it. The subagent starts with no context, in your working directory: put everything it needs in task. The call returns at once and the answer arrives later, with a settle (a wave's as ONE summary): carry on with other work, or end your turn if your next step needs the answer (it resumes you). The pane closes after a clean finish; keep: true leaves it open (needs a mux). When the check judges a mu task, set record so its verdict lands on that task; leave it out when there is no task. Set wave to group a fan-out (mu delegates tally).`,\n promptSnippet:\n \"Subagent: delegate a self-contained task to a background pi agent; its answer arrives later, with a settle\",\n parameters: {\n type: \"object\",\n properties: {\n task: { type: \"string\", description: \"The complete task, with all context it needs\" },\n label: {\n type: \"string\",\n description:\n \"Short label naming the delegate, e.g. 'review' → delegate-review. Use one per subtask when fanning out.\",\n },\n brief: {\n type: \"string\",\n description:\n \"Optional standing role or rules, sent before the task, e.g. 'You are a reviewer; read only.' The rules are instructions, not enforced. The job itself goes in task.\",\n },\n cwd: {\n type: \"string\",\n description:\n \"Working directory for the delegate (default: yours); with workspace, the git repo the worktree is made from\",\n },\n timeout: {\n type: \"number\",\n exclusiveMinimum: 0,\n description: `Seconds to wait for the answer (default ${DELEGATE_TIMEOUT_S}). On timeout you get a \"still running\" answer instead, and the real answer will not arrive later; the subagent keeps running in its pane.`,\n },\n workspace: {\n type: \"boolean\",\n description:\n \"For tasks that edit files: its own git worktree branched from the current commit of the repo at cwd (default: yours). The result names the path; changes stay there until you merge them. This isolates repository edits only: the subagent runs as you, with your files, environment and network.\",\n },\n cli: {\n type: \"string\",\n description:\n \"Agent CLI key (default pi). Only keys with $MU_<KEY>_COMMAND set in pi's environment exist; to pick a model, use model instead.\",\n },\n model: {\n type: \"string\",\n description:\n \"Model for the subagent, passed to pi as --model (e.g. 'sonnet', '<provider>/<model>:high' copied from `pi --list-models`); appended to the cli's command. Default: the cli's own model. Use it to vary models across a review panel.\",\n },\n keep: {\n type: \"boolean\",\n description:\n \"Keep the pane after it finishes, to talk to it again (needs a mux; ignored without one)\",\n },\n record: {\n type: \"object\",\n description:\n \"When the answer arrives, write its VERDICT/EVIDENCE onto this task as a note (for a check that judges a mu task; omit with no task); name the workstream: task as <ws>/<task>, or set workstream.\",\n properties: {\n task: { type: \"string\" },\n workstream: { type: \"string\" },\n },\n required: [\"task\"],\n additionalProperties: false,\n },\n wave: {\n type: \"string\",\n description:\n \"Label grouping the calls of one fan-out; `mu delegates tally -w <workstream> --wave <label>` counts their verdicts per judged task.\",\n },\n workstream: {\n type: \"string\",\n description: `Workstream that holds the delegate task and runs the delegate (default: ${W}).`,\n },\n },\n required: [\"task\"],\n additionalProperties: false,\n },\n async execute(_id, params, signal, _onUpdate, ctx) {\n const task = typeof params.task === \"string\" ? params.task.trim() : \"\";\n if (!task) throw new Error(\"mu_delegate needs a non-empty task\");\n const t = params.timeout;\n if (t !== undefined && !(typeof t === \"number\" && Number.isFinite(t) && t > 0))\n throw new Error(\n `mu_delegate: timeout must be a positive number of seconds (got ${JSON.stringify(t)})`,\n );\n // With workspace, cwd is only what the caller named: the repo to branch.\n const callCwd =\n typeof params.cwd === \"string\" && params.cwd\n ? params.cwd\n : params.workspace !== true\n ? (ctx?.cwd ?? process.cwd())\n : undefined;\n if (callCwd !== undefined && !isDir(callCwd))\n throw new Error(`mu_delegate: cwd ${callCwd} is not a directory`);\n let model: string | undefined;\n if (params.model !== undefined && params.model !== \"\") {\n model = normalizeModel(params.model);\n if (!model)\n throw new Error(\n `mu_delegate: model must be one pi model id like 'provider/id:thinking', as listed by \\`pi --list-models\\` (got ${JSON.stringify(params.model)}); omit it for the cli's default`,\n );\n }\n let workstream = W;\n if (params.workstream !== undefined) {\n const problem = workstreamNameProblem(\n typeof params.workstream === \"string\" ? params.workstream : String(params.workstream),\n \"workstream\",\n );\n if (problem !== undefined) throw new Error(`mu_delegate: ${problem} Nothing spawned.`);\n workstream = params.workstream as string;\n }\n if (\n params.wave !== undefined &&\n (typeof params.wave !== \"string\" || params.wave.trim() === \"\")\n )\n throw new Error(\n `mu_delegate: wave must be a non-empty label (got ${JSON.stringify(params.wave)})`,\n );\n const record = await resolveRecord(params.record);\n const brief = typeof params.brief === \"string\" ? params.brief.trim() : \"\";\n const label =\n typeof params.label === \"string\" && params.label.trim() ? params.label.trim() : undefined;\n // Count slots synchronously, before any await: parallel calls in one\n // turn all run this line before the first register returns.\n const decision = admission();\n const handle = decision === \"starting\" ? \"\" : `queued-${++queueSeq}`;\n if (decision === \"starting\") starting++;\n const session = piSessionId(ctx) || process.env.PI_SESSION_ID || `local-${token}`;\n const caller = `pi:${session}`;\n const info: Omit<CallInfo, \"task\"> = {\n callId: `${caller}:${token}-${++callSeq}`,\n caller,\n workstream,\n ...(typeof params.wave === \"string\" ? { wave: params.wave.trim() } : {}),\n ...(record ? { record } : {}),\n request: {\n text: brief ? `${brief}\\n\\n${task}` : task,\n ...(label ? { label } : {}),\n ...(typeof params.cli === \"string\" && params.cli ? { cli: params.cli } : {}),\n ...(model ? { model } : {}),\n ...(callCwd !== undefined ? { cwd: callCwd } : {}),\n ...(params.workspace === true ? { workspace: true } : {}),\n ...(typeof t === \"number\" ? { timeoutS: Math.ceil(t) } : {}),\n ...(params.keep === true ? { keep: true } : {}),\n },\n };\n if (decision === \"starting\") {\n // Durable before it spawns: a start that fails here frees its slot.\n let reg: Awaited<ReturnType<typeof calls.register>>;\n try {\n reg = await calls.register(info, \"starting\");\n } catch (e) {\n starting--;\n reportPending();\n drain();\n throw new Error(\n `mu_delegate: could not register the call: ${errText(e)}. Nothing spawned.`,\n );\n }\n return start(reg.call, signal, ctx);\n }\n if (decision === \"refused\") {\n let reg: Awaited<ReturnType<typeof calls.register>>;\n try {\n reg = await calls.register(info, \"refused\");\n } catch (e) {\n throw new Error(\n `mu_delegate: could not register the call: ${errText(e)}. Nothing spawned.`,\n );\n }\n return queuedResult(reg.call, \"refused\", handle, 0);\n }\n // Full: wait in the queue (FIFO, up to DELEGATE_QUEUE_FACTOR caps' worth).\n const entry: Queued = {\n handle,\n call: { ...info, task: \"\" },\n ctx,\n registered: Promise.resolve(),\n };\n entry.registered = calls.register(info, \"queued\").then((reg) => {\n entry.call = reg.call;\n });\n queue.push(entry);\n reportPending();\n try {\n await entry.registered;\n } catch (e) {\n const at = queue.indexOf(entry);\n if (at >= 0) queue.splice(at, 1);\n reportPending();\n throw new Error(`mu_delegate: could not register the call: ${errText(e)}. Nothing queued.`);\n }\n return queuedResult(entry.call, \"queued\", handle, queue.indexOf(entry) + 1 || queue.length);\n },\n });\n\n pi.registerTool({\n name: DELEGATE_REISSUE_TOOL,\n label: \"mu delegate reissue\",\n description: `Run a call ${DELEGATE_TOOL} refused (the queue was full): same call, same task, never a second verdict. Takes the call_id from the refusal; starts now if a slot is free, else queues.`,\n parameters: {\n type: \"object\",\n properties: { call_id: { type: \"string\", description: \"The refused call's id\" } },\n required: [\"call_id\"],\n additionalProperties: false,\n },\n async execute(_id, params, signal, _onUpdate, ctx) {\n const callId = typeof params.call_id === \"string\" ? params.call_id : \"\";\n if (!callId) throw new Error(`${DELEGATE_REISSUE_TOOL} needs a call_id`);\n const shown = await calls.show(callId).catch((e: unknown) => {\n throw new Error(`${DELEGATE_REISSUE_TOOL}: ${errText(e)}`);\n });\n if (shown.state !== \"refused\")\n throw new Error(`${DELEGATE_REISSUE_TOOL}: call ${callId} is ${shown.state}, not refused.`);\n // Synchronous from here to the slot count: parallel reissues cannot overfill.\n const decision = admission();\n if (decision === \"refused\")\n throw new Error(\n `${DELEGATE_REISSUE_TOOL}: still full (${inflight.size + starting} running, ${queue.length} queued). Nothing changed; reissue ${callId} when an answer arrives.`,\n );\n if (decision === \"starting\") starting++;\n try {\n await calls.mark(callId, decision === \"starting\" ? \"starting\" : \"queued\");\n } catch (e) {\n if (decision === \"starting\") {\n starting--;\n reportPending();\n drain();\n }\n throw new Error(`${DELEGATE_REISSUE_TOOL}: ${errText(e)}`);\n }\n if (decision === \"starting\") return start(shown.call, signal, ctx);\n const handle = `queued-${++queueSeq}`;\n queue.push({ handle, call: shown.call, ctx, registered: Promise.resolve() });\n reportPending();\n return queuedResult(shown.call, \"queued\", handle, queue.length);\n },\n });\n\n pi.registerTool({\n name: DELEGATE_CANCEL_TOOL,\n label: \"mu delegate cancel\",\n description: `Stop a delegate started by ${DELEGATE_TOOL}: abort its turn and close its pane (keep: true leaves the pane open; a mux-free one's child pi is stopped). A queued or refused call is cancelled too (name it by its handle or call_id). The verdict target, if any, gets \"no verdict (cancelled)\". Its answer is not shown afterwards.`,\n parameters: {\n type: \"object\",\n properties: {\n name: {\n type: \"string\",\n description: \"Delegate name (delegate-1), queue handle (queued-2) or call_id\",\n },\n keep: { type: \"boolean\", description: \"Leave the pane open after aborting\" },\n },\n required: [\"name\"],\n additionalProperties: false,\n },\n async execute(_id, params) {\n const name = typeof params.name === \"string\" ? params.name : \"\";\n if (!name) throw new Error(\"mu_delegate_cancel needs a name\");\n const cancelCall = async (call: CallInfo, author: string, text?: string) => {\n try {\n const f = await calls.finish(call.callId, {\n outcome: \"cancelled\",\n ...(text ? { text } : {}),\n author,\n });\n if (f.recorded && call.record)\n return ` Recorded on ${call.record.workstream}/${call.record.task} as a note (no verdict: cancelled).`;\n return f.changed ? ` Task ${call.workstream}/${call.task} closed (cancelled).` : \"\";\n } catch (e) {\n return ` Recording the cancel failed: ${errText(e)}.`;\n }\n };\n const qi = queue.findIndex((q) => q.handle === name || q.call.callId === name);\n if (qi >= 0) {\n const [q] = queue.splice(qi, 1);\n reportPending();\n let recorded = \"\";\n if (q) {\n await q.registered.catch(() => {});\n recorded = await cancelCall(q.call, q.handle);\n }\n return {\n content: [\n { type: \"text\", text: `Dropped ${name} from the queue; it never started.${recorded}` },\n ],\n details: { name, workstream: q?.call.workstream ?? W },\n };\n }\n const found = [...inflight].find(\n ([key, e]) =>\n key === name || key === inflightKey(e.call.workstream, name) || e.call.callId === name,\n );\n if (!found && callIdIn(name)) {\n // Not in this runtime (refused, or another session's): cancel the durable call.\n const shown = await calls.show(name).catch((e: unknown) => {\n throw new Error(`mu_delegate_cancel: ${errText(e)}`);\n });\n const recorded = await cancelCall(shown.call, name);\n return {\n content: [{ type: \"text\", text: `Cancelled ${name} (${shown.state}).${recorded}` }],\n details: { name, workstream: shown.call.workstream },\n };\n }\n const key = found?.[0];\n const entry = found?.[1];\n const ws = entry?.call.workstream ?? W;\n const agentName = key ? key.slice(key.indexOf(\"/\") + 1) : name;\n if (entry?.process && key) {\n // SIGTERM the run: it aborts the child's turn, finishes the call\n // cancelled and stops the child; its log and session file stay.\n entry.abort.abort();\n forget(key);\n await entry.process;\n await finishOrphan(entry.call, \"cancelled\", \"cancelled\");\n const shown = await calls.show(entry.call.callId).catch(() => undefined);\n const where = entry.call.record\n ? ` Recorded on ${entry.call.record.workstream}/${entry.call.record.task} as a note (no verdict: cancelled).`\n : \"\";\n return {\n content: [\n {\n type: \"text\",\n text: `Cancelled ${ws}/${agentName} (child pi stopped; call ${shown?.state ?? \"cancelling\"}).${where}`,\n },\n ],\n details: { name: agentName, workstream: ws },\n };\n }\n if (entry) entry.cancelling = true;\n const ab = await mu([\"agent\", \"abort\", agentName, \"-w\", ws]);\n if (ab.code !== 0) {\n // Not cancelled after all: keep waiting, or deliver what settled meanwhile.\n if (entry) {\n entry.cancelling = false;\n const parked = entry.parked;\n entry.parked = undefined;\n if (parked) void parked();\n }\n throw failure(`mu agent abort ${ws}/${agentName}`, ab);\n }\n if (entry && key) {\n entry.abort.abort();\n forget(key);\n }\n let text = `Aborted ${ws}/${agentName}.`;\n // Its transcript; what it wrote before the abort goes into the report.\n const sessionFile = entry?.sessionFile;\n const evidence = evidenceLines({ ...(sessionFile ? { sessionFile } : {}) });\n // The result is durable before the pane goes: the cancel closes the task.\n if (entry)\n text += await cancelCall(\n entry.call,\n agentName,\n sessionFile ? lastAssistantTextIn(sessionFile) : undefined,\n );\n if (params.keep === true) text += \" Pane kept.\";\n else {\n const c = await closeDelegate(agentName, entry?.identity, ws);\n text += c.closed ? \" Pane closed.\" : ` Pane kept: ${c.why}`;\n }\n if (evidence.length > 0) text += `\\n${evidence.join(\"\\n\")}`;\n return { content: [{ type: \"text\", text }], details: { name: agentName, workstream: ws } };\n },\n });\n\n // A wake enters the conversation at its message_start: at once when pi is\n // idle, or when the running turn drains its follow-ups. Its answers are then\n // in front of the model (as pointers); its turn's settle shows the reports.\n pi.on(\"message_start\", (e) => {\n const m = (e as { message?: { role?: unknown; customType?: unknown; details?: unknown } })\n .message;\n if (m?.role !== \"custom\" || m.customType !== DELEGATE_MESSAGE_TYPE) return;\n const id = (m.details as { wake?: unknown } | undefined)?.wake;\n if (typeof id !== \"number\") return;\n for (const c of arriving.get(id)?.calls ?? []) owed.delete(c);\n arriving.delete(id);\n });\n\n /** Stop waking for these: the reports stay recorded and the next settle's wait\n * still owes them. One line per answer in the conversation (no turn). */\n const dropWakes = (ids: number[], also: string[] = []) => {\n const names = new Set(also);\n for (const id of ids) {\n const a = arriving.get(id);\n if (!a) continue;\n arriving.delete(id);\n // pi may still run a send it deferred while settling: no turn.\n for (const o of a.opts ?? []) o.triggerTurn = false;\n for (const c of a.calls) names.add(c);\n }\n const dropped: DroppedWake[] = [];\n for (const c of names) {\n const a = owed.get(c);\n if (!a) continue;\n owed.delete(c);\n dropped.push(a);\n }\n trace(\"dropped\", { calls: dropped.map((d) => d.callId) });\n if (dropped.length === 0) return;\n void Promise.resolve(\n send(\n {\n customType: DELEGATE_MESSAGE_TYPE,\n content: droppedNote(dropped),\n display: true,\n details: { dropped: dropped.map((d) => d.callId) },\n },\n { triggerTurn: false },\n \"dropped-note\",\n ),\n ).catch(() => {});\n };\n /** After a normal settle, with pi idle one tick later (pi runs the sends it\n * deferred right after this event) and nothing accepted since: a wake pi\n * accepted that never started was cleared from its queue (the dequeue key, a\n * failed compaction flush). Resend ONE; lost twice, drop it with a note. With\n * no wake lost, wake for any answer the settle did not show. */\n const recoverLost = (candidates: number[], ctx: DelegateCtx) => {\n settleCheck = undefined;\n if (closed) return;\n let idle = false;\n try {\n idle = ctx.isIdle?.() ?? true;\n } catch {\n // stale ctx: the next settle looks again\n }\n if (!idle) return;\n // Accepted after the settle began: pi may be about to run it, and its own\n // run settles again.\n if ([...arriving].some(([id, a]) => a.sent && !candidates.includes(id))) return;\n const lost = candidates.filter((id) => arriving.get(id)?.sent);\n dropWakes(lost.filter((id) => arriving.get(id)?.resent));\n const next = lost.find((id) => arriving.has(id));\n const a = next === undefined ? undefined : arriving.get(next);\n if (next === undefined || !a?.message) {\n wake(\"wake-after-settle\");\n return;\n }\n a.resent = true;\n trace(\"resend\", { wake: next, calls: a.calls });\n void Promise.resolve(\n send(a.message, { deliverAs: \"followUp\", triggerTurn: true }, \"resend\"),\n ).catch(() => {\n arriving.delete(next);\n });\n };\n pi.on(\"agent_start\", () => {\n busy = true;\n });\n pi.on(\"agent_settled\", (e, ctx) => {\n busy = false;\n const sent = [...arriving].filter(([, a]) => a.sent).map(([id]) => id);\n // Escape clears pi's queue along with the run: what it held never arrives,\n // and the user stopped. No wake: one note; the next prompt's settle shows them.\n if ((e as { aborted?: unknown }).aborted === true) {\n clearImmediate(settleCheck);\n dropWakes(sent, [...owed.keys()]);\n return;\n }\n if (sent.length === 0 && owed.size === 0) return;\n clearImmediate(settleCheck);\n settleCheck = setImmediate(() => recoverLost(sent, ctx));\n });\n\n // The watchers die with a runtime, but the calls are durable: the next runtime\n // of the same pi session (/reload, resume, `pi -c`) re-adopts this session's\n // `running` pane calls, so no wait owes an answer nobody watches. A call whose\n // agent is gone ends as failed through the same recorder.\n pi.on(\"session_start\", async (_e, ctx) => {\n const session = piSessionId(ctx) || process.env.PI_SESSION_ID;\n if (!session || closed) return;\n const r = await mu([\"delegates\", \"list\", \"--caller\", `pi:${session}`, \"--json\"]).catch(\n () => undefined,\n );\n const items = (r ? (json(r)?.items as Record<string, unknown>[] | undefined) : undefined) ?? [];\n for (const row of items) {\n // A mux-free run is its own child (agent = its task) and finishes by itself.\n if (row.state !== \"running\" || typeof row.agent !== \"string\" || row.agent === row.task)\n continue;\n const call = callInfoOf(row);\n if (call.caller !== `pi:${session}` || inflight.has(inflightKey(call.workstream, row.agent)))\n continue;\n // One-shot delegates: the first run is the answer, so 0 is the exact baseline.\n // The deadline runs from when it went `running` (the row's last update), not\n // from this reload, so a reload loop never extends it.\n const since = typeof row.updatedAt === \"string\" ? Date.parse(row.updatedAt) : Number.NaN;\n await watch(call, row.agent, 0, {\n keep: call.request.keep === true,\n timeoutS: call.request.timeoutS ?? DELEGATE_TIMEOUT_S,\n ...(Number.isFinite(since) ? { startedAt: since } : {}),\n });\n }\n });\n\n // The watchers die with this runtime (/reload, /new, quit): say which\n // delegates lose their callback, so none is lost silently. The names\n // are also in the tool results, and `mu agent wait` recovers them.\n pi.on(\"session_shutdown\", async (e, ctx) => {\n closed = true;\n clearImmediate(settleCheck);\n clearImmediate(wakeSoon);\n trace(\"session_shutdown.state\", {\n arriving: [...arriving.values()].map((a) => ({ calls: a.calls, sent: a.sent })),\n owed: [...owed.keys()],\n inflight: [...inflight.keys()],\n });\n // Wakes die with this runtime; the recorded answers stay owed to the next wait.\n arriving.clear();\n owed.clear();\n if (inflight.size === 0 && queue.length === 0) return;\n const shown = (key: string) => (key.startsWith(`${W}/`) ? key.slice(W.length + 1) : key);\n const names = [...inflight].flatMap(([k, e]) => (e.process ? [] : [shown(k)]));\n const procs = [...inflight].flatMap(([k, e]) => (e.process ? [shown(k)] : []));\n const sessions = [...inflight].flatMap(([k, e]) =>\n e.sessionFile ? [`${shown(k)}: ${e.sessionFile}`] : [],\n );\n const dropped = queue.splice(0);\n // A mux-free run is this pi's child: quit cancels it (durably), while a\n // reload or session switch leaves it to finish onto its task.\n const reason = (e as { reason?: unknown } | undefined)?.reason;\n const replacing =\n reason === \"reload\" || reason === \"new\" || reason === \"resume\" || reason === \"fork\";\n const stopping: Promise<unknown>[] = [];\n for (const f of inflight.values())\n if (!f.process || !replacing) {\n f.abort.abort();\n const call = f.call;\n if (f.process)\n stopping.push(f.process.then(() => finishOrphan(call, \"cancelled\", \"pi quit\")));\n }\n inflight.clear();\n reportPending();\n // Quit: each run has cancelled its call and stopped its child before it exits.\n await Promise.all(stopping);\n // A queued call never started and nothing will drain it now: park it as\n // refused (durable, listable, reissuable) instead of leaving it queued forever.\n const refused: string[] = [];\n await Promise.all(\n dropped.map(async (q) => {\n try {\n await q.registered;\n await calls.mark(q.call.callId, \"refused\", {\n error: \"its session ended before it started\",\n });\n refused.push(q.call.callId);\n } catch {\n // best effort: `mu delegates` shows what state it stayed in\n }\n }),\n );\n const parts: string[] = [];\n if (names.length > 0)\n parts.push(\n `${names.length} delegate${names.length === 1 ? \"\" : \"s\"} still running: ${names.join(\", \")}. ${\n reason === \"reload\"\n ? \"This session's next runtime re-adopts them and delivers their answers.\"\n : `Their answers will not come back here; use mu agent wait <name> -w ${W} --json.`\n }`,\n );\n if (procs.length > 0)\n parts.push(\n replacing\n ? `${procs.length} mux-free delegate${procs.length === 1 ? \"\" : \"s\"} still running: ${procs.join(\", \")}. Each finishes onto its task (mu task notes <name> -w ${W}); the answer will not come back here.`\n : `${procs.length} mux-free delegate${procs.length === 1 ? \"\" : \"s\"} cancelled: ${procs.join(\", \")}.`,\n );\n if (sessions.length > 0) parts.push(`Sessions: ${sessions.join(\"; \")}.`);\n if (dropped.length > 0)\n parts.push(\n `${dropped.length} queued, never started: ${dropped.map((q) => q.handle).join(\", \")}. Re-issue them${refused.length > 0 ? ` (durable and refused: ${DELEGATE_REISSUE_TOOL} in a new pi session; list: mu delegates --all)` : \"\"}.`,\n );\n const msg = parts.join(\" \");\n if (ctx?.hasUI && ctx.ui) ctx.ui.notify(msg, \"warning\");\n else process.stderr.write(`mu: ${msg}\\n`);\n });\n\n return {\n answerPending: () => arriving.size > 0,\n delivered(shown) {\n if (Array.isArray(shown)) for (const c of shown) owed.delete(c);\n else\n for (const [c, a] of owed) if (a.at < (shown as { before: number }).before) owed.delete(c);\n },\n };\n}\n","// The one validator for a workstream name typed as scope (`-w`, a\n// `<ws>/<name>` ref prefix, a record's `workstream`). Pure and\n// dependency-free: the CLI (src/cli.ts) and the pi extension\n// (extension/delegate.ts, extension/nudge.ts) all call it, so the\n// answer to \"is this a valid scope?\" is the same everywhere.\n//\n// It never trims. Trimming turns a quoting accident (`-w ' auth'`) into\n// a different, valid workstream. Empty, blank and padded names are\n// rejected, and so is any name holding whitespace, a comma, a slash or a\n// control character (a list or a `<ws>/<name>` ref pasted as one name).\n// It does not check the rest of the name's shape or that it exists.\n\n/** Why `value` is not a usable workstream name, or undefined when it is. */\nexport function workstreamNameProblem(value: string, flag = \"-w/--workstream\"): string | undefined {\n if (value.length > 0 && value.trim().length === 0) {\n return `${flag} got a blank (whitespace-only) value ${JSON.stringify(value)}. Pass a workstream name.`;\n }\n if (value.length === 0 || value !== value.trim()) {\n return `${flag} got ${JSON.stringify(value)}: pass a bare workstream name with no surrounding whitespace.`;\n }\n if (/[\\s,/\\p{Cc}]/u.test(value)) {\n return `${flag} got ${JSON.stringify(value)}: a workstream name has no whitespace, ',' or '/'.`;\n }\n return undefined;\n}\n\n/**\n * Names from repeated / comma-separated values. A structurally empty\n * fragment (`\"a,\"`) is a comma artifact and is dropped; a fragment is\n * never trimmed, and a padded or blank one, or a lone empty value, is a\n * problem.\n */\nexport function parseWorkstreamFragments(\n values: readonly string[],\n flag = \"-w/--workstream\",\n): { names: string[] } | { problem: string } {\n const names: string[] = [];\n for (const value of values) {\n const lone = value === \"\" ? workstreamNameProblem(value, flag) : undefined;\n if (lone !== undefined) return { problem: lone };\n for (const fragment of value.split(\",\")) {\n if (fragment === \"\") continue;\n const problem = workstreamNameProblem(fragment, flag);\n if (problem !== undefined) return { problem };\n names.push(fragment);\n }\n }\n return { names };\n}\n\n/**\n * Why a qualified `<ws>/<name>` ref is unusable, or undefined (a bare ref\n * has no prefix to check). Both halves are validated and never trimmed:\n * ` own/t`, `own/ t` and `own/` are errors, not another entity.\n */\nexport function qualifiedRefProblem(raw: string): string | undefined {\n const slash = raw.indexOf(\"/\");\n if (slash === -1) return undefined;\n const flag = `qualified ref ${JSON.stringify(raw)}:`;\n const prefix = workstreamNameProblem(raw.slice(0, slash), flag);\n if (prefix !== undefined) return prefix;\n const name = raw.slice(slash + 1);\n if (name === \"\" || name !== name.trim() || /[\\s\\p{Cc}]/u.test(name)) {\n return `${flag} the name after '/' must be non-empty with no whitespace.`;\n }\n return undefined;\n}\n","/**\n * Reading a mu_delegate call's arguments: label stems, model ids and the\n * command a model implies. Pure; split from delegate.ts.\n */\n\n/** A label → agent-name stem: lowercase, [a-z0-9-], ≤ 20 chars. */\nexport function labelStem(label: unknown): string | undefined {\n if (typeof label !== \"string\") return undefined;\n const stem = label\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .slice(0, 20)\n .replace(/-+$/, \"\");\n return stem || undefined;\n}\n\n/** Model values that need no shell quoting inside a `--command` string. */\nconst MODEL_BARE_RE = /^[A-Za-z0-9._:/@+=-]+$/;\n\n/**\n * Forgive the usual slips in a `model` value: surrounding quotes or\n * backticks, a pasted `--model ` / `--model=` prefix, stray whitespace.\n * Anything else (brackets as in `gpt-6.1-sol[1m]`, odd provider ids) is\n * kept and shell-quoted by `modelCommand`, so pi gets to judge the id.\n * Returns undefined for an empty value or one with inner whitespace,\n * which no model id has.\n */\nexport function normalizeModel(raw: unknown): string | undefined {\n if (typeof raw !== \"string\") return undefined;\n let m = raw.trim();\n for (let prev = \"\"; prev !== m; ) {\n prev = m;\n m = m\n .replace(/^--model(?:=|\\s+)/, \"\")\n .replace(/^([\"'`])(.*)\\1$/s, \"$2\")\n .trim();\n }\n return m && !/\\s/.test(m) ? m : undefined;\n}\n\nfunction shellArg(s: string): string {\n return MODEL_BARE_RE.test(s) ? s : `'${s.replace(/'/g, \"'\\\\''\")}'`;\n}\n\n/**\n * The command a delegate with `model` runs: the cli key's command\n * (`$MU_<KEY>_COMMAND`, else the key itself, as `resolveCliCommand` in\n * src/agents/spawn.ts does) plus `--model <model>`. Inlined: the extension\n * bundles standalone and spawn.ts pulls in the DB.\n */\nexport function modelCommand(\n cli: string,\n model: string,\n env: NodeJS.ProcessEnv = process.env,\n): string {\n const override = env[`MU_${cli.toUpperCase().replace(/-/g, \"_\")}_COMMAND`];\n const base = override && override.trim() !== \"\" ? override.trim() : cli;\n return `${base} --model ${shellArg(model)}`;\n}\n","/**\n * Running `mu` from the pi extensions: the runner seam (tests inject a fake)\n * and the reading of its one `--json` envelope. Pure plumbing, shared by the\n * delegate tools and the nudges.\n */\nimport { execFile } from \"node:child_process\";\nimport { existsSync } from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\n\nexport type MuResult = { code: number; stdout: string; stderr: string };\n/** Per-call options. `env` is merged over this process's env for that child only\n * (undefined deletes a key). `drainMs` bounds how long an aborted child (SIGTERM'd,\n * its final document kept: a `mu wait` snapshot) may run before SIGKILL; default 10 s. */\nexport type MuRunOpts = { env?: Record<string, string | undefined>; drainMs?: number };\n/** Runs `mu <args>`. The test seam: tests inject a fake. */\nexport type MuRunner = (\n args: readonly string[],\n signal?: AbortSignal,\n /** Written to the child's stdin (a `--text -` argument reads it). */\n stdin?: string,\n opts?: MuRunOpts,\n) => Promise<MuResult>;\n\nfunction childEnv(over: MuRunOpts[\"env\"]): NodeJS.ProcessEnv | undefined {\n if (over === undefined) return undefined;\n const env = { ...process.env };\n for (const [k, v] of Object.entries(over)) {\n if (v === undefined) delete env[k];\n else env[k] = v;\n }\n return env;\n}\n\n/** The CLI this extension ships with (dist/cli.js next to dist/extension/), else `mu` on PATH. */\nexport function defaultRunner(): MuRunner {\n let cli: string | undefined;\n try {\n const p = fileURLToPath(new URL(\"../cli.js\", import.meta.url));\n if (existsSync(p)) cli = p;\n } catch {\n // not a file: URL; use PATH\n }\n return (args, signal, stdin, opts) =>\n cli\n ? runChild(process.execPath, [cli, ...args], signal, stdin, opts)\n : runChild(\"mu\", args, signal, stdin, opts);\n}\n\n/** How long an aborted mu gets to exit (a spawn rolls back its worktree; a wait prints its snapshot) before SIGKILL. */\nconst ABORT_GRACE_MS = 10_000;\n\n/**\n * Run one child. The ONE terminate path: an abort sends SIGTERM and resolves\n * only once the child has EXITED, with its final stdout kept. mu rolls back on\n * SIGTERM, and a caller told \"cancelled\" while that runs would report a spawn\n * gone that is still removing its pane and worktree. SIGKILL follows after\n * `opts.drainMs` (default ABORT_GRACE_MS).\n */\nexport function runChild(\n cmd: string,\n argv: readonly string[],\n signal?: AbortSignal,\n stdin?: string,\n opts: MuRunOpts = {},\n): Promise<MuResult> {\n return new Promise((resolve) => {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const env = childEnv(opts.env);\n const child = execFile(\n cmd,\n [...argv],\n { maxBuffer: 16 * 1024 * 1024, ...(env ? { env } : {}) },\n (err, stdout, stderr) => {\n clearTimeout(timer);\n signal?.removeEventListener(\"abort\", onAbort);\n const code = err ? (typeof err.code === \"number\" ? err.code : err.signal ? 143 : 1) : 0;\n resolve({ code, stdout: String(stdout), stderr: String(stderr || err?.message || \"\") });\n },\n );\n function onAbort(): void {\n child.kill(\"SIGTERM\");\n timer = setTimeout(() => child.kill(\"SIGKILL\"), opts.drainMs ?? ABORT_GRACE_MS);\n }\n if (signal?.aborted) onAbort();\n else signal?.addEventListener(\"abort\", onAbort, { once: true });\n if (stdin !== undefined) {\n child.stdin?.on(\"error\", () => {}); // the child may exit before it reads\n child.stdin?.end(stdin);\n }\n });\n}\n\n/** A `mu --json` stdout as one object: the envelope's `data` on success, its\n * partial `data` plus `error`/`message` on failure; undefined when it is not\n * an envelope. */\nexport function parseEnvelope(stdout: string): Record<string, unknown> | undefined {\n try {\n const v = JSON.parse(stdout) as Record<string, unknown> | null;\n if (typeof v !== \"object\" || v === null || typeof v.ok !== \"boolean\") return undefined;\n const data =\n typeof v.data === \"object\" && v.data !== null ? (v.data as Record<string, unknown>) : {};\n return v.ok ? data : { ...data, error: v.error, message: v.message };\n } catch {\n return undefined;\n }\n}\n\n/** A `mu --json` stdout as its `data`, only when it is a SUCCESS envelope\n * (`ok:true`). A failure's partial data is not a success: a destructive\n * call that acts on a read must use this, never `parseEnvelope`. */\nexport function parseOkEnvelope(stdout: string): Record<string, unknown> | undefined {\n try {\n const v = JSON.parse(stdout) as Record<string, unknown> | null;\n if (typeof v !== \"object\" || v === null || v.ok !== true) return undefined;\n return typeof v.data === \"object\" && v.data !== null\n ? (v.data as Record<string, unknown>)\n : undefined;\n } catch {\n return undefined;\n }\n}\n","/**\n * The extension's side of a durable delegate call: thin wrappers over\n * `mu delegates register | mark | finish | show` (src/cli/delegates.ts).\n * The CLI owns the lifecycle; this only builds argv and reads the envelope,\n * so a shell drives the same states (VISION § 1, rule 2).\n */\nimport { type MuResult, type MuRunner, parseEnvelope, parseOkEnvelope } from \"./mu-run.js\";\n\n/** Where a delegate's answer is recorded: a task, resolved by `mu task show`. */\nexport type RecordTarget = { workstream: string; task: string };\n\n/** The stored spawn request of a call (`delegate_calls.request`). */\nexport type CallRequest = {\n text: string;\n label?: string;\n cli?: string;\n model?: string;\n cwd?: string;\n workspace?: boolean;\n timeoutS?: number;\n keep?: boolean;\n};\n\n/** One call as the extension tracks it: the durable ids and what a start needs. */\nexport type CallInfo = {\n callId: string;\n caller: string;\n workstream: string;\n /** The delegate task's local id. */\n task: string;\n wave?: string;\n record?: RecordTarget;\n request: CallRequest;\n};\n\nexport type CallState =\n | \"queued\"\n | \"starting\"\n | \"running\"\n | \"recording\"\n | \"done\"\n | \"failed\"\n | \"refused\"\n | \"cancelled\";\n\n/** A `mu delegates` verb that failed: its exit code and the one-line reason. */\nexport class MuCallError extends Error {\n override readonly name = \"MuCallError\";\n constructor(\n public readonly verb: string,\n public readonly code: number,\n reason: string,\n ) {\n super(`mu delegates ${verb} failed (exit ${code}): ${reason}`);\n }\n}\n\nexport type FinishResult = {\n changed: boolean;\n state: CallState;\n recorded: boolean;\n verdict: string | null;\n error?: string;\n};\n\nconst reason = (r: MuResult): string => {\n const m = parseEnvelope(r.stdout)?.message;\n return (typeof m === \"string\" ? m : r.stderr || r.stdout).trim();\n};\n\n/** The `data` of a success; a failure throws {@link MuCallError}. */\nasync function call(\n run: MuRunner,\n verb: string,\n args: readonly string[],\n stdin?: string,\n): Promise<Record<string, unknown>> {\n const r = await run([\"delegates\", verb, ...args, \"--json\"], undefined, stdin);\n // Success is an `ok:true` envelope only: a failure's partial data (or a success\n // whose own data has an `error` field, like a failed record) is not a CLI failure.\n const out = r.code === 0 ? parseOkEnvelope(r.stdout) : undefined;\n if (out === undefined) throw new MuCallError(verb, r.code, reason(r));\n return out;\n}\n\nconst rowOf = (data: Record<string, unknown>): Record<string, unknown> =>\n (data.call ?? {}) as Record<string, unknown>;\n\n/** The CLI's call row as a {@link CallInfo}. */\nexport function callInfoOf(row: Record<string, unknown>): CallInfo {\n const rec = row.record as { workstream?: string; task?: string } | null | undefined;\n return {\n callId: String(row.callId),\n caller: String(row.caller),\n workstream: String(row.workstream),\n task: String(row.task),\n ...(typeof row.wave === \"string\" ? { wave: row.wave } : {}),\n ...(rec?.workstream && rec.task\n ? { record: { workstream: rec.workstream, task: rec.task } }\n : {}),\n request: (row.request ?? { text: \"\" }) as CallRequest,\n };\n}\n\nexport function callsApi(run: MuRunner) {\n return {\n /** Create the call (task + brief + row, atomically). `created: false`: this id already existed. */\n async register(\n c: Omit<CallInfo, \"task\">,\n state: \"queued\" | \"starting\" | \"refused\",\n ): Promise<{ call: CallInfo; state: CallState; created: boolean }> {\n const q = c.request;\n const args = [\n c.callId,\n \"--caller\",\n c.caller,\n \"-w\",\n c.workstream,\n \"--text\",\n \"-\",\n \"--state\",\n state,\n ...(q.label ? [\"--label\", q.label] : []),\n ...(q.cli ? [\"--cli\", q.cli] : []),\n ...(q.model ? [\"--model\", q.model] : []),\n ...(q.cwd ? [\"--cwd\", q.cwd] : []),\n ...(q.workspace === true ? [\"--workspace\"] : []),\n ...(q.timeoutS !== undefined ? [\"--timeout\", String(q.timeoutS)] : []),\n ...(q.keep === true ? [\"--keep\"] : []),\n ...(c.wave ? [\"--wave\", c.wave] : []),\n ...(c.record ? [\"--record\", `${c.record.workstream}/${c.record.task}`] : []),\n ];\n const data = await call(run, \"register\", args, q.text);\n const row = rowOf(data);\n return {\n call: callInfoOf(row),\n state: row.state as CallState,\n created: data.created === true,\n };\n },\n /** One admission step (a compare-and-set on the stored state). */\n async mark(\n callId: string,\n to: \"queued\" | \"starting\" | \"running\" | \"refused\",\n extra: { agent?: string; error?: string } = {},\n ): Promise<void> {\n await call(run, \"mark\", [\n callId,\n to,\n ...(extra.agent ? [\"--agent\", extra.agent] : []),\n ...(extra.error ? [\"--error\", extra.error] : []),\n ]);\n },\n /** The recorder: verdict note, report and close, in one op group. Idempotent. */\n async finish(\n callId: string,\n o: { outcome: string; text?: string; elapsedMs?: number; author: string; record?: boolean },\n ): Promise<FinishResult> {\n const data = await call(\n run,\n \"finish\",\n [\n callId,\n \"--outcome\",\n o.outcome,\n \"--author\",\n o.author,\n ...(o.elapsedMs !== undefined ? [\"--elapsed-ms\", String(Math.round(o.elapsedMs))] : []),\n ...(o.record === false ? [\"--no-record\"] : []),\n ...(o.text?.trim() ? [\"--text\", \"-\"] : []),\n ],\n o.text?.trim() ? o.text : undefined,\n );\n return data as unknown as FinishResult;\n },\n async show(\n callId: string,\n ): Promise<{ call: CallInfo; state: CallState; verdict: string | null }> {\n const row = rowOf(await call(run, \"show\", [callId]));\n return {\n call: callInfoOf(row),\n state: row.state as CallState,\n verdict: typeof row.verdict === \"string\" ? row.verdict : null,\n };\n },\n };\n}\n","/**\n * The pure wording of the mu_delegate tool: the words for one finished wait\n * (recorded as the report of a run with no answer; sent whole only when the\n * record failed), the wake, and the note left when Escape drops wakes. Split\n * from delegate.ts (the runtime) so each stays under the file cap;\n * delegate.ts re-exports all of it.\n */\nimport { readFileSync } from \"node:fs\";\nimport { formatElapsed } from \"../src/delegate-verdict.js\";\n\n/** The reserved workstream delegates run in. */\nexport const DELEGATE_WORKSTREAM = \"scratch\";\n/** Default `mu agent wait --timeout` for a delegate, in seconds. */\nexport const DELEGATE_TIMEOUT_S = 3600;\n\nexport { formatElapsed };\n\n/** One agent row of `mu agent wait --json`, as far as the tool reads it. */\nexport type WaitAgent = {\n outcome?: string;\n lastText?: string;\n lastError?: string;\n /** The delegate's pi session file (mu ≥ 3.11.2 on the delegate side). */\n sessionFile?: string;\n /** outcome `blocked`: the extension dialog the delegate's pi waits on. */\n blocked?: { kind?: string; title?: string };\n /** The run baseline the wait counted from; a re-wait passes it as\n * `--after-runs` so a run that settles in between is not missed. */\n afterRuns?: number;\n};\n\n/** What happened to the pane after delivery, for the message. */\nexport type PaneFate = { closed: true } | { closed: false; why: string };\n\n/** Extras for the follow-up message; all optional. */\nexport type MessageExtras = {\n /** `mu agent read -n 50` for the outcomes without text. */\n tail?: string;\n attach?: string;\n timeoutS?: number;\n workspace?: string;\n /** How long the delegate ran, in ms. */\n elapsedMs?: number;\n /** The workstream the delegate runs in (default `scratch`). */\n workstream?: string;\n /** The delegate task (`<workstream>/<task>`): its report holds the full answer. */\n task?: string;\n /** The queue handle the caller was given (`queued-3`), if it was queued. */\n queuedAs?: string;\n /** The delegate's pi session file: the full transcript. */\n sessionFile?: string;\n};\n\n/**\n * Text of the last assistant message in a pi session file (JSONL), or\n * undefined when there is none or the file cannot be read. A delegate\n * that timed out, died or was cancelled has no final answer, but what it\n * wrote so far is here.\n */\nexport function lastAssistantTextIn(sessionFile: string): string | undefined {\n let raw: string;\n try {\n raw = readFileSync(sessionFile, \"utf8\");\n } catch {\n return undefined;\n }\n const lines = raw.split(\"\\n\");\n for (let i = lines.length - 1; i >= 0; i--) {\n const line = lines[i];\n if (!line?.includes('\"assistant\"')) continue;\n try {\n const e = JSON.parse(line) as { message?: { role?: unknown; content?: unknown } };\n if (e.message?.role !== \"assistant\") continue;\n const c = e.message.content;\n const text =\n typeof c === \"string\"\n ? c\n : Array.isArray(c)\n ? c\n .map((p: unknown) => {\n const q = p as { type?: unknown; text?: unknown };\n return q.type === \"text\" && typeof q.text === \"string\" ? q.text : \"\";\n })\n .join(\"\")\n : \"\";\n if (text.trim()) return text;\n } catch {\n // a torn last line while pi writes: keep looking\n }\n }\n return undefined;\n}\n\n/** Where to look next for a delegate with no final answer: its session file. */\nexport function evidenceLines(x: { sessionFile?: string }): string[] {\n return x.sessionFile ? [`Session: ${x.sessionFile}`] : [];\n}\n\n/**\n * The words for one finished wait. Pure: the CLI already\n * classified the outcome (`mu agent wait --json` → `outcome`); this only\n * words it.\n */\nexport function delegateMessage(\n name: string,\n agent: WaitAgent | undefined,\n pane: PaneFate,\n x: MessageExtras = {},\n): string {\n const timeoutS = x.timeoutS ?? DELEGATE_TIMEOUT_S;\n const W = x.workstream ?? DELEGATE_WORKSTREAM;\n const who = `Delegate ${W}/${name}${x.queuedAs ? ` (queued as ${x.queuedAs})` : \"\"}`;\n const took = x.elapsedMs !== undefined ? ` after ${formatElapsed(x.elapsedMs)}` : \"\";\n const fate = pane.closed ? \"Pane closed.\" : `Pane kept (${pane.why}).`;\n const look = [\n x.attach ? `Attach: ${x.attach}` : undefined,\n `Read: mu agent read ${name} -n 50 -w ${W}`,\n ].filter((v) => v !== undefined);\n const tailBlock = x.tail?.trim() ? `\\n\\nPane tail:\\n${x.tail.trimEnd()}` : \"\";\n const ws = x.workspace ? ` Workspace: ${x.workspace}` : \"\";\n const ev = evidenceLines(x);\n const evBlock = ev.length > 0 ? `\\n${ev.join(\"\\n\")}` : \"\";\n switch (agent?.outcome) {\n case \"done\":\n return `${who} finished${took}. ${fate}${ws}\\n\\n${agent.lastText ?? \"\"}`;\n case \"empty\":\n return `${who} finished${took} without a text answer. ${fate}${ws}${evBlock}${tailBlock}`;\n case \"error\":\n return [\n `${who} stopped on an API error${took}, after pi's own retries: ${(agent.lastError ?? \"unknown error\").replace(/[.\\s]+$/, \"\")}. ${fate}${ws}`,\n \"Decide: re-issue the call, or record the check as UNVERIFIED.\",\n ...ev,\n ...look,\n `Close: mu agent close ${name} -w ${W}`,\n ].join(\"\\n\");\n case \"died\":\n return `${who} died${took} before answering. ${fate}${ws}${evBlock}${tailBlock}`;\n case \"blocked\": {\n const b = agent.blocked;\n const dialog = `${b?.kind ?? \"dialog\"}${b?.title ? ` \"${b.title}\"` : \"\"}`;\n const lines = [\n `${who} is blocked on a ${dialog} dialog${took} and has NOT finished; stopped waiting, so its answer will not arrive here. ${fate}${ws}`,\n \"Answer the dialog in its pane (attach), then wait again; or close it and record the check as UNVERIFIED.\",\n ...ev,\n ...look,\n `Wait again: mu agent wait ${name} -w ${W} --json${agent.afterRuns !== undefined ? ` --after-runs ${agent.afterRuns}` : \"\"}`,\n `Close: mu agent close ${name} -w ${W}`,\n ];\n return `${lines.join(\"\\n\")}${tailBlock}`;\n }\n case \"timeout\":\n case \"pending\":\n return [\n `${who} is still running after ${timeoutS}s; stopped waiting, so its answer will not arrive here. ${fate}${ws}`,\n ...ev,\n ...look,\n `Wait again: mu agent wait ${name} -w ${W} --json${agent.afterRuns !== undefined ? ` --after-runs ${agent.afterRuns}` : \"\"}`,\n ].join(\"\\n\");\n default:\n return `${who}: mu agent wait gave no result. ${fate}${ws}${evBlock}${tailBlock}`;\n }\n}\n\n/** One recorded answer a wake points at. */\nexport type WakeAnswer = {\n callId: string;\n name: string;\n workstream: string;\n /** The delegate task's local id: its report is the full answer. */\n task: string;\n outcome: string;\n verdict?: string;\n /** `<ws>/<task>` its verdict was recorded on. */\n record?: string;\n /** Why the pane was kept (it is evidence), when it was. */\n kept?: string;\n};\n\n/** A wake an aborted run dropped: the answer it pointed at. */\nexport type DroppedWake = WakeAnswer;\n\nfunction answerLine(a: WakeAnswer): string {\n const how = [a.outcome, a.verdict, a.record ? `recorded on ${a.record}` : undefined]\n .filter((x) => x !== undefined)\n .join(\", \");\n const pane = a.kept\n ? ` Pane kept (${a.kept}): mu agent read ${a.name} -n 50 -w ${a.workstream}.`\n : \"\";\n return `- ${a.workstream}/${a.name} (${how}; call ${a.callId}): mu task notes ${a.task} -w ${a.workstream}.${pane}`;\n}\n\n/**\n * The wake: a one-line pointer per recorded answer, no answer text. It starts a\n * turn whose settle wait shows the reports; a lost or repeated wake loses or\n * repeats nothing. Pure.\n */\nexport function wakeText(answers: readonly WakeAnswer[]): string {\n const n = answers.length;\n return [\n `${n === 1 ? \"A delegate answer is\" : `${n} delegate answers are`} recorded; the settle shows ${n === 1 ? \"it\" : \"them\"} (or read the report):`,\n ...answers.map(answerLine),\n ].join(\"\\n\");\n}\n\n/**\n * The note left in the conversation when Escape drops queued wakes (no turn):\n * one line per answer. The reports stay recorded, and the next settle's wait\n * still owes them. Pure.\n */\nexport function droppedNote(dropped: readonly DroppedWake[]): string {\n const n = dropped.length;\n return [\n `Interrupted: ${n} delegate answer${n === 1 ? \"\" : \"s\"} recorded but not shown; the next settle shows ${n === 1 ? \"it\" : \"them\"}:`,\n ...dropped.map(answerLine),\n ].join(\"\\n\");\n}\n","// mu — a delegate's answer as a verdict: the pure half of src/delegates.ts.\n//\n// Dependency-free on purpose: the pi extension (extension/delegate.ts) bundles\n// standalone and must not pull in the DB, yet it words the same note.\n\n/** The verdict labels a check may answer. Anything else is UNVERIFIED. */\nexport const VERDICT_LABELS = [\"CONFIRMED\", \"REFUTED\", \"UNVERIFIED\"] as const;\nexport type VerdictLabel = (typeof VERDICT_LABELS)[number];\n\n/** `42s`, `3m 05s`, `1h 02m`. */\nexport function formatElapsed(ms: number): string {\n const t = Math.max(0, Math.round(ms / 1000));\n if (t < 60) return `${t}s`;\n const m = Math.floor(t / 60);\n if (m < 60) return `${m}m ${String(t % 60).padStart(2, \"0\")}s`;\n return `${Math.floor(m / 60)}h ${String(m % 60).padStart(2, \"0\")}m`;\n}\n\n/** A `VERDICT:` line: at the start of the line, behind at most ONE role word\n * (`REFUTER: VERDICT: …`, which is how checks write it by hand). Nothing else\n * may precede it, so a verdict quoted mid-line in the evidence is not one. */\nconst VERDICT_LINE = /^(?:\\w+: )?VERDICT:/;\nconst LABEL_RE = new RegExp(`\\\\b(${VERDICT_LABELS.join(\"|\")})\\\\b`);\n\n/** The index of the FIRST verdict line of `lines`, or -1. Later `VERDICT:`\n * lines are evidence text, not a second verdict. */\nfunction firstVerdictLine(lines: readonly string[]): number {\n return lines.findIndex((l) => VERDICT_LINE.test(l));\n}\n\n/** `line` as a verdict line: null when it is not one, else its label (the first\n * known label after the colon; undefined when it names none). */\nexport function verdictLineLabel(line: string): VerdictLabel | undefined | null {\n if (!VERDICT_LINE.test(line)) return null;\n const after = line.slice(line.indexOf(\"VERDICT:\") + \"VERDICT:\".length);\n return LABEL_RE.exec(after)?.[1] as VerdictLabel | undefined;\n}\n\n/** The label on the first `VERDICT:` line (the first known label after the\n * colon), or undefined when there is no verdict line or no known label. */\nexport function parseVerdict(answer: string): VerdictLabel | undefined {\n const lines = answer.trimEnd().split(\"\\n\");\n const at = firstVerdictLine(lines);\n if (at < 0) return undefined;\n return verdictLineLabel(lines[at] ?? \"\") ?? undefined;\n}\n\n/**\n * The note a delegate's answer leaves on the task it judged. A done answer\n * keeps everything from its first verdict line on, so a multi-line EVIDENCE\n * body (and any `VERDICT:` text quoted in it) survives whole (else the whole answer, marked NO VERDICT LINE); any\n * other outcome records the gap. Never cut: the note is the evidence.\n */\nexport function recordNote(\n label: string,\n name: string,\n outcome: string | undefined,\n lastText: string | undefined,\n elapsedMs: number,\n): string {\n if (outcome !== \"done\" || !lastText?.trim())\n return `REFUTER ${label}: no verdict (${outcome === \"done\" ? \"empty\" : (outcome ?? \"no result\")})`;\n const lines = lastText.trimEnd().split(\"\\n\");\n const at = firstVerdictLine(lines);\n const body = at >= 0 ? lines.slice(at).join(\"\\n\") : `NO VERDICT LINE: ${lastText.trimEnd()}`;\n return `REFUTER ${label} (${name}, ${formatElapsed(elapsedMs)}):\\n${body}`;\n}\n","/**\n * The pure wording of a mux-free delegate (no tmux, no herdr): the tool\n * result, and why a `mu delegates run <call-id> --json` sent nothing or died.\n * The runner (src/delegate-process.ts) finishes the call durably; its answer\n * reaches the model through the settle wait like any delegate's. Split from delegate.ts\n * (the runtime) so each stays under the file cap.\n */\nimport type { CallInfo } from \"./delegate-calls.js\";\n\n/** The fields of a `mu delegates run --json` result (or failure envelope) the tool reads. */\nexport type ProcessRun = {\n outcome?: string;\n state?: string;\n error?: string;\n message?: string;\n answer?: string;\n sessionFile?: string;\n sessionDir?: string;\n logPath?: string;\n workspace?: string;\n};\n\n/** The tool result for a call that now runs as a child pi. */\nexport function processStarted(call: CallInfo, cancelTool: string) {\n const ws = call.workstream;\n const name = call.task;\n const text = [\n `Delegated to ${ws}/${name} (call ${call.callId}) as a child pi process: no multiplexer, so no pane to attach. Its answer arrives with your next settle (and stays on the task: mu task notes ${call.task} -w ${ws}); carry on, or end your turn if your next step needs it. Do not poll.`,\n call.request.keep === true\n ? \"keep: true needs a multiplexer; the child stops after its answer (its session file stays).\"\n : undefined,\n `Cancel: ${cancelTool} { name: \"${name}\" }`,\n ].filter((x) => x !== undefined);\n return {\n content: [{ type: \"text\" as const, text: text.join(\"\\n\") }],\n details: {\n name,\n workstream: ws,\n task: `${ws}/${call.task}`,\n state: \"running\",\n call_id: call.callId,\n transport: \"process\",\n attach: null,\n workspace: null,\n keep: false,\n },\n };\n}\n\n/** Why a run sent nothing (refused) or died without a result (finished failed), with the next step. */\nexport function processFailedText(\n call: CallInfo,\n o: ProcessRun,\n fallback: string,\n code: number,\n reissueTool: string,\n): string {\n const reason = (o.error ?? o.message ?? fallback).replace(/[.\\s]+$/, \"\");\n const next =\n o.state === \"refused\"\n ? `The call is durable and refused: reissue it with ${reissueTool} { call_id: \"${call.callId}\" }`\n : `\\`mu delegates run\\` exited ${code} without a result; the call is recorded as failed (mu delegates show ${call.callId})`;\n return `${reason}. ${next} (task ${call.workstream}/${call.task}).`;\n}\n","/**\n * `MU_DELEGATE_TRACE=1`: the delivery trace of the mu_delegate tool, split\n * from delegate.ts. Off (and free) by default.\n */\nimport { appendFileSync, mkdirSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { defaultCacheDir } from \"../src/state-dir.js\";\n\n/** `MU_DELEGATE_TRACE=1` appends one JSON line per delivery step and pi\n * lifecycle event to `<mu cache dir>/delegate-trace.log`: for finding\n * where a follow-up got lost. Off (and free) by default. */\nexport function delegateTraceOn(env: NodeJS.ProcessEnv = process.env): boolean {\n return !!env.MU_DELEGATE_TRACE && env.MU_DELEGATE_TRACE !== \"0\";\n}\nexport function delegateTracePath(): string {\n return join(defaultCacheDir(), \"delegate-trace.log\");\n}\nexport function trace(event: string, data: Record<string, unknown> = {}): void {\n if (!delegateTraceOn()) return;\n try {\n mkdirSync(defaultCacheDir(), { recursive: true });\n const line = { t: new Date().toISOString(), pid: process.pid, event, ...data };\n appendFileSync(delegateTracePath(), `${JSON.stringify(line)}\\n`);\n } catch {\n // tracing must never cost a delegate its answer\n }\n}\n\n/** pi events the trace records, with what each says about delivery. */\nexport const TRACE_EVENTS = [\n \"session_start\",\n \"session_before_switch\",\n \"session_before_fork\",\n \"session_before_compact\",\n \"session_compact\",\n \"session_compact_failed\",\n \"session_before_tree\",\n \"session_tree\",\n \"agent_start\",\n \"agent_end\",\n \"agent_settled\",\n \"turn_end\",\n \"message_start\",\n \"message_end\",\n] as const;\n\nexport function traceFields(\n event: unknown,\n ctx: { isIdle?(): boolean; hasPendingMessages?(): boolean } | undefined,\n): Record<string, unknown> {\n const e = (event ?? {}) as Record<string, unknown>;\n const m = e.message as { role?: unknown; customType?: unknown; details?: unknown } | undefined;\n const d = m?.details as { delivery?: unknown; name?: unknown } | undefined;\n const out: Record<string, unknown> = {};\n if (m?.role) out.role = m.role;\n if (m?.customType) out.customType = m.customType;\n if (d?.delivery !== undefined) out.delivery = d.delivery;\n if (d?.name !== undefined) out.name = d.name;\n for (const k of [\"aborted\", \"reason\", \"willRetry\"]) if (e[k] !== undefined) out[k] = e[k];\n try {\n if (ctx?.isIdle) out.idle = ctx.isIdle();\n if (ctx?.hasPendingMessages) out.pendingMsgs = ctx.hasPendingMessages();\n } catch {\n out.ctx = \"stale\";\n }\n return out;\n}\n","// The mu state directory, resolved from builtins only so the CLI\n// bootstrap (src/main.ts) can locate its compile cache before it loads\n// any of the CLI graph. db.ts re-exports defaultStateDir.\n\nimport { homedir } from \"node:os\";\nimport { isAbsolute, join } from \"node:path\";\n\n/**\n * Resolve the canonical mu state directory:\n * MU_STATE_DIR > $XDG_STATE_HOME/mu-next (absolute only) > ~/.local/state/mu-next\n *\n * `mu-next`, not `mu`: 3.x owns `<state home>/mu`, and a shared default DB,\n * socket dir or lock dir would let the two builds corrupt each other.\n */\nexport function defaultStateDir(): string {\n if (process.env.MU_STATE_DIR) return process.env.MU_STATE_DIR;\n return join(xdgStateHome(homedir()), \"mu-next\");\n}\n\n/**\n * The mu cache directory, `$XDG_CACHE_HOME/mu` (absolute only) else\n * `~/.cache/mu`: files mu can lose at any time, such as copies of data\n * that lives elsewhere too.\n */\nexport function defaultCacheDir(): string {\n const xdg = process.env.XDG_CACHE_HOME;\n return join(xdg !== undefined && isAbsolute(xdg) ? xdg : join(homedir(), \".cache\"), \"mu\");\n}\n\n/** `$XDG_STATE_HOME`, or `<home>/.local/state` when it is unset, empty,\n * or relative: the XDG spec says such a value must be ignored, and a\n * relative one would scatter state across every cwd mu runs in. */\nexport function xdgStateHome(home: string): string {\n const xdg = process.env.XDG_STATE_HOME;\n return xdg !== undefined && isAbsolute(xdg) ? xdg : join(home, \".local\", \"state\");\n}\n","/**\n * mu pi extension: the keep-driving settle wait, and the close nudge.\n *\n * Keep-driving (registerNudge): every completed settle of an orchestrator runs\n * `mu wait --first --on-stall exit --json` as this session's callers (the\n * inherited managed identity and pi:<session>). Producers (spawn/send/claim)\n * arm that wait from state, so no shell line is parsed. The turn ends only when\n * nothing is owed, a `mu human-needed` stop is open (what is already ready is\n * still shown, without a blocking wait), the wait fails (shown), or the user\n * cancels it. The rule text lives in skills/mu/SKILL.md between the\n * keep-driving markers and heads the wait's result.\n *\n * Its worker-side twin, the close nudge: a mu-spawned pi worker\n * ($MU_AGENT_NAME + $MU_WORKSTREAM) that settles while it still owns an\n * IN_PROGRESS task is told once per prompt to close it or say why not.\n * `MU_NUDGE=0` turns both off.\n *\n * Neither runs in a nested pi (mu-pi.ts decides at bind) or on a remote host\n * (`MU_REMOTE=1`, no mu DB); close also skips a pi with no UI (`pi -p`, json),\n * where nobody can answer. Neither starts while a delegate wake is on its way\n * (its own turn waits) or a dialog is open.\n *\n * Delegate answers reach the model through the settle wait, never through a pi\n * echo: a `delegate` event is shown with that call's report (the durable task\n * note, capped, with a pointer), and an event of a wave waits for the rest of\n * the wave and shows ONE summary. `registerNudge` takes the delegate side's\n * `delivered` hook (mu-pi.ts); the delegate side sends a one-line wake only\n * when no live settle wait will catch a just-recorded answer (delegate.ts).\n */\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { defaultRunner, type MuRunner, parseEnvelope } from \"./delegate.js\";\n\nexport const NUDGE_MESSAGE_TYPE = \"mu-keep-driving\";\nexport const NUDGE_LOG_KIND = \"nudge\";\nexport const CLOSE_NUDGE_MESSAGE_TYPE = \"mu-close-task\";\nconst MARK_START = \"<!-- mu:keep-driving -->\";\nconst MARK_END = \"<!-- /mu:keep-driving -->\";\n\n/** The slice of pi's ExtensionContext the nudges read. */\nexport type MuNudgeCtx = {\n mode?: string;\n hasUI?: boolean;\n hasPendingMessages?: () => boolean;\n sessionManager?: { getSessionId?: () => string };\n ui?: { onTerminalInput?: (h: (data: string) => undefined) => () => void };\n};\n\n/** The slice of pi's ExtensionAPI the nudges use. */\nexport interface MuNudgeApi {\n on(\n event: \"agent_before_settle\" | \"input\" | \"ui_prompt_start\" | \"session_shutdown\",\n handler: (event: unknown, ctx: MuNudgeCtx) => unknown,\n ): unknown;\n}\n\n/**\n * True while this pi is nested: it inherited a MU_CTL_SOCK another pi\n * serves (a `pi -p` run inside an agent's pane). Read at settle time,\n * since the bind decision lands in session_start, after registration.\n */\nexport type NestedCheck = () => boolean;\nconst notNested: NestedCheck = () => false;\n\n/**\n * Why this settle must not be nudged, read at settle time and again after\n * every awaited read. \"input\": a user message is queued (pi's own count).\n * \"wake\": a delegate wake is queued or being delivered (pi's\n * hasPendingMessages() does not count custom follow-ups); its own turn runs\n * the wait. Both mean the next turn is already coming. \"blocked\": an extension\n * dialog is open. undefined when nothing holds the settle. Any hold skips the\n * wait's START; none discards the entries of a wait already consumed.\n */\nexport type SettleHold = (ctx?: MuNudgeCtx) => \"input\" | \"wake\" | \"blocked\" | undefined;\nconst noHold: SettleHold = () => undefined;\n\n/** A queued user message (pi's own count) holds like a wake: the next turn is coming. */\nexport function withQueuedInput(hold: SettleHold): SettleHold {\n return (ctx) => (ctx?.hasPendingMessages?.() ? \"input\" : hold(ctx));\n}\n\n/** No one can answer a nudge: print or json mode. */\nfunction noUI(ctx: MuNudgeCtx | undefined): boolean {\n return ctx?.hasUI === false;\n}\n\n/** `MU_NUDGE=0` turns the nudge off. */\nexport function nudgeEnabled(env: NodeJS.ProcessEnv = process.env): boolean {\n return env.MU_NUDGE !== \"0\";\n}\n\n/** The keep-driving paragraph from SKILL.md, one line per paragraph, or undefined without the markers. */\nexport function keepDrivingRule(skillMd: string): string | undefined {\n const i = skillMd.indexOf(MARK_START);\n const j = skillMd.indexOf(MARK_END);\n if (i < 0 || j < i) return undefined;\n // Unwrap the source's hard line breaks (paragraphs stay apart): the TUI wraps\n // the entry to the terminal, and kept breaks show as ragged mid-sentence cuts.\n const text = skillMd\n .slice(i + MARK_START.length, j)\n .trim()\n .split(/\\n\\s*\\n/)\n .map((p) => p.replace(/\\s*\\n\\s*/g, \" \"))\n .join(\"\\n\\n\");\n return text === \"\" ? undefined : text;\n}\n\n/** SKILL.md next to this file in either layout (source or dist/extension). */\nfunction readSkill(): string | undefined {\n for (const up of [\"..\", \"../..\"]) {\n const p = join(import.meta.dirname ?? \"\", up, \"skills\", \"mu\", \"SKILL.md\");\n if (existsSync(p)) return readFileSync(p, \"utf8\");\n }\n return undefined;\n}\n\ntype ListJson = {\n items?: { id?: string; status?: string; kind?: string }[];\n count?: number;\n more?: number;\n};\n\n/**\n * Every item of a task read, uncapped: `uncapped` is the flag that turns the 4 KB\n * cap off (`--all`; `--full` on owned-by). A result that still says `more` is\n * unknown (undefined): a cut is not proof that nothing else is running.\n */\nasync function allItems(\n run: MuRunner,\n argv: string[],\n uncapped: \"--all\" | \"--full\",\n): Promise<NonNullable<ListJson[\"items\"]> | undefined> {\n const r = await run([...argv, uncapped]);\n if (r.code !== 0) return undefined;\n // mu prints {ok,data:{items,count,more},next}; no envelope reads as \"unknown\".\n const data = parseEnvelope(r.stdout) as ListJson | undefined;\n if (data === undefined || !Array.isArray(data.items)) return undefined;\n if ((data.more ?? 0) > 0) return undefined;\n return data.items;\n}\n\n/** Write a `mu log` breadcrumb without holding the settle for it: the\n * nudge's message does not depend on the log line. */\nfunction breadcrumb(run: MuRunner, args: string[]): void {\n void run(args).catch(() => {});\n}\n\n/** A nudge's settle result. `yielded` undoes the nudge's once-per-prompt\n * bookkeeping when the merge drops the result for a late hold. A `receipt`\n * carries something already consumed (a wait's event): a late hold drops only\n * its continuation, never its entries. */\ntype SettleResult =\n | { entries?: unknown[]; continue?: boolean; yielded?: () => void; receipt?: boolean }\n | undefined;\ntype SettleHandler = (event: unknown, ctx: MuNudgeCtx) => unknown;\n\n/**\n * A view of `pi` whose `agent_before_settle` handlers run in PARALLEL\n * behind one real handler. pi awaits boundary handlers one after the\n * other, and each nudge awaits a mu subprocess, so several nudges held the\n * settle (and every `mu agent wait` on it) for the sum of their calls.\n * The merged result appends every handler's entries to the event's\n * (pi replaces `entries` with each handler's return, so separate\n * handlers dropped all but the last nudge) and continues when any asks.\n * A nudge that throws still reaches pi's extension-error path: after the\n * merged handler, one reporter handler per nudge rethrows that nudge's\n * error, so pi reports each failure (as it did when every nudge was its\n * own handler) while the other nudges' entries are still delivered.\n * The merge reads `hold` once more after the slowest nudge: a fast nudge\n * checked it long before, so input or a wake that queued meanwhile drops\n * every result, an open dialog the continuing ones, and each dropped nudge\n * may fire on a later settle. A receipt (a consumed wait event) keeps its\n * entries under any late hold and loses only its continuation.\n * Call `flush()` after registering the nudges.\n */\nexport function parallelSettle(\n pi: MuNudgeApi,\n hold: SettleHold = noHold,\n): { api: MuNudgeApi; flush(): void } {\n const handlers: SettleHandler[] = [];\n const api: MuNudgeApi = {\n on(event, handler) {\n if (event === \"agent_before_settle\") handlers.push(handler);\n else pi.on(event, handler);\n },\n };\n // Errors of the last settle, by handler index; each reporter takes its own.\n let errors: (unknown[] | undefined)[] = [];\n return {\n api,\n flush() {\n if (handlers.length === 0) return;\n pi.on(\"agent_before_settle\", async (event, ctx) => {\n errors = handlers.map(() => undefined);\n const results = await Promise.all(\n handlers.map(async (h, i) => {\n try {\n return (await h(event, ctx)) as SettleResult;\n } catch (err) {\n errors[i] = [err]; // reported by reporter i, after the merge\n return undefined;\n }\n }),\n );\n const late = hold(ctx);\n const fired = results.flatMap((r) => {\n if (r === undefined) return [];\n if (r.receipt === true && late !== undefined) return [{ entries: r.entries ?? [] }];\n if (late === \"input\" || late === \"wake\" || (late === \"blocked\" && r.continue === true)) {\n r.yielded?.();\n return [];\n }\n return [r];\n });\n if (fired.length === 0) return undefined;\n const prior = (event as { entries?: unknown[] } | null)?.entries ?? [];\n return {\n entries: [...prior, ...fired.flatMap((r) => r.entries ?? [])],\n ...(fired.some((r) => r.continue === true) ? { continue: true } : {}),\n };\n });\n handlers.forEach((_, i) => {\n pi.on(\"agent_before_settle\", () => {\n const err = errors[i];\n errors[i] = undefined;\n if (err !== undefined) throw err[0];\n return undefined;\n });\n });\n },\n };\n}\n\nfunction outcomeOf(event: unknown): unknown {\n return typeof event === \"object\" && event !== null\n ? (event as { outcome?: unknown }).outcome\n : undefined;\n}\n\n/** How long a cancelled wait may take to print its final snapshot before SIGKILL. */\nexport const SETTLE_DRAIN_MS = 3000;\n/** The one wait the settle runs: whatever this caller owns, first event. */\nexport const SETTLE_WAIT_ARGS = [\"wait\", \"--first\", \"--on-stall\", \"exit\", \"--json\"] as const;\n/**\n * Under an open human stop the settle does not block: this wait returns an event\n * already ready, or times out within a second.\n */\nexport const SETTLE_READY_ARGS = [\n \"wait\",\n \"--first\",\n \"--on-stall\",\n \"exit\",\n \"--timeout\",\n \"1\",\n \"--json\",\n] as const;\n/** At most this many ready events are shown by one settle under a human stop. */\nconst READY_MAX = 50;\n/** Escape, plain or in the kitty keyboard protocol. */\n// biome-ignore lint/suspicious/noControlCharactersInRegex: matching ESC is the point\nconst ESC = /^\\u001b(\\[27(;\\d+)*u)?$/;\n\ntype Envelope = { ok?: unknown; error?: unknown; data?: Record<string, unknown> };\n\nfunction envelopeOf(stdout: string): Envelope | undefined {\n try {\n const v = JSON.parse(stdout) as Envelope | null;\n return typeof v === \"object\" && v !== null && typeof v.ok === \"boolean\" ? v : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction sessionIdOf(ctx: MuNudgeCtx | undefined): string | undefined {\n try {\n return ctx?.sessionManager?.getSessionId?.() || undefined;\n } catch {\n return undefined; // a stale ctx throws\n }\n}\n\n/**\n * The child env per caller identity: the inherited managed `<ws>/<name>` (pi\n * session stripped), and `pi:<session>` (managed identity stripped). Each is a\n * separate `mu state --me` read: --me resolves one identity, and a human stop\n * either one recorded ends the loop.\n */\nfunction identityEnvs(sid: string | undefined): Record<string, string | undefined>[] {\n const e = process.env;\n const out: Record<string, string | undefined>[] = [];\n if (e.MU_MANAGED_AGENT === \"1\" && e.MU_WORKSTREAM && e.MU_AGENT_NAME)\n out.push({ PI_SESSION_ID: undefined });\n if (sid !== undefined) out.push({ MU_MANAGED_AGENT: undefined, PI_SESSION_ID: sid });\n return out;\n}\n\n/** Open human needs across every caller identity; undefined when a read failed. */\nasync function humanNeeds(run: MuRunner, sid: string | undefined): Promise<number | undefined> {\n const counts = await Promise.all(\n identityEnvs(sid).map(async (env) => {\n const r = await run([\"state\", \"--me\", \"--all\", \"--full\", \"--json\"], undefined, undefined, {\n env,\n }).catch(() => undefined);\n const env0 = r === undefined ? undefined : envelopeOf(r.stdout);\n const ws = env0?.ok === true ? env0.data?.workstreams : undefined;\n if (!Array.isArray(ws)) return undefined;\n return ws.reduce(\n (n: number, w: { human_needs?: unknown[] }) => n + (w.human_needs?.length ?? 0),\n 0,\n );\n }),\n );\n return counts.some((c) => c === undefined)\n ? undefined\n : counts.reduce((a: number, b) => a + (b ?? 0), 0);\n}\n\nfunction entry(content: string): unknown {\n return { type: \"custom_message\", customType: NUDGE_MESSAGE_TYPE, content, display: true };\n}\n\n/** One answer's report in a settle entry is cut to this many characters (tail of the pointer kept). */\nexport const REPORT_CAP = 4000;\n/** In a wave summary, each answer shown in full is cut to this. */\nexport const WAVE_REPORT_CAP = 1500;\nconst PENDING_STATES = new Set([\"queued\", \"starting\", \"running\", \"recording\"]);\n\n/** A delegate call row as `mu delegates show|list --json` prints it (the fields read here). */\ntype CallRow = {\n callId: string;\n task: string;\n workstream: string;\n state: string;\n verdict?: string | null;\n error?: string | null;\n wave?: string | null;\n record?: { workstream?: string; task?: string } | null;\n};\ntype Run1 = (args: readonly string[]) => Promise<Envelope | undefined>;\n\nconst recordOf = (c: CallRow): string | undefined =>\n c.record?.workstream && c.record.task ? `${c.record.workstream}/${c.record.task}` : undefined;\n\n/** The call's report note (its full answer), or undefined when unreadable. */\nasync function reportOf(mu: Run1, c: CallRow): Promise<string | undefined> {\n const v = await mu([\"task\", \"notes\", c.task, \"-w\", c.workstream, \"--json\"]);\n const items = (v?.ok === true ? v.data?.items : undefined) as\n | { kind?: string; content?: string }[]\n | undefined;\n return items?.filter((n) => n.kind === \"report\").at(-1)?.content;\n}\n\n/**\n * One answer as the model reads it: a header (call, task, state, verdict, record),\n * then the report capped to `cap` with the pointer to the whole of it. A recorded\n * check with a verdict is the header only: the verdict is on its task already.\n */\nasync function answerBlock(mu: Run1, c: CallRow, cap: number): Promise<string> {\n const where = recordOf(c);\n const notes = `mu task notes ${c.task} -w ${c.workstream}`;\n const head = [\n `Delegate answer: call ${c.callId}, task ${c.workstream}/${c.task}, ${c.state}`,\n c.verdict ? `, ${c.verdict}` : \"\",\n where ? `, recorded on ${where}` : \"\",\n c.error ? `. Error: ${c.error}` : \"\",\n \".\",\n ].join(\"\");\n if (where && c.verdict) return `${head} Full answer: ${notes}`;\n const text = await reportOf(mu, c);\n if (text === undefined) return `${head} Report unreadable here; read it: ${notes}`;\n const body =\n text.length > cap\n ? `${text.slice(0, cap)}\\n[... ${text.length - cap} more characters: ${notes}]`\n : text;\n return `${head}\\n${body}`;\n}\n\n/** The ONE wave line: counts per verdict, then one line per call. */\nfunction waveSummary(wave: string, rows: CallRow[]): string {\n const n = (p: (c: CallRow) => boolean) => rows.filter(p).length;\n const refused = rows.filter((c) => c.state === \"refused\");\n const counts = [\n `${n((c) => c.verdict === \"CONFIRMED\")}/${rows.length} CONFIRMED`,\n `${n((c) => c.verdict === \"REFUTED\")} REFUTED`,\n `${n((c) => c.state !== \"refused\" && !PENDING_STATES.has(c.state) && c.verdict !== \"CONFIRMED\" && c.verdict !== \"REFUTED\")} UNVERIFIED`,\n `${n((c) => PENDING_STATES.has(c.state))} pending`,\n `${refused.length} refused`,\n ].join(\", \");\n const lines = rows.map(\n (c) =>\n `- ${recordOf(c) ?? `${c.workstream}/${c.task}`}: ${c.state === \"refused\" ? \"REFUSED, reissue it: mu_delegate_reissue\" : (c.verdict ?? c.state)} (call ${c.callId})`,\n );\n return [`Wave ${wave}: ${counts}.`, ...lines].join(\"\\n\");\n}\n\n/** A wait result's `notices` (one line each; `waitData` never cuts them). */\nfunction noticesOf(d: Record<string, unknown>): string[] {\n return Array.isArray(d.notices)\n ? d.notices.filter((n): n is string => typeof n === \"string\")\n : [];\n}\n\n/** The firing snapshot of a wait result, when its event is a delegate answer. */\nfunction firingDelegate(d: Record<string, unknown>): string | undefined {\n const f = d.firing as { kind?: unknown; ref?: unknown } | undefined;\n if (f?.kind !== \"delegate\" || typeof f.ref !== \"string\") return undefined;\n return f.ref.startsWith(\"delegate:\") ? f.ref.slice(\"delegate:\".length) : undefined;\n}\n\n/**\n * The call ids of the delegate calls a wait result's snapshots still show (its owed picture), or\n * undefined when the result cut its snapshots (the picture is then unknown, not empty).\n */\nfunction pictureOf(d: Record<string, unknown>): Set<string> | undefined {\n if (typeof d.snapshotsCut === \"number\" && d.snapshotsCut > 0) return undefined;\n const snaps = Array.isArray(d.snapshots) ? (d.snapshots as { ref?: unknown }[]) : [];\n return new Set(\n snaps.flatMap((s) =>\n typeof s.ref === \"string\" && s.ref.startsWith(\"delegate:\")\n ? [s.ref.slice(\"delegate:\".length)]\n : [],\n ),\n );\n}\n\n/**\n * Told which delegate answers a settle showed the model: their call ids, or\n * `{ before }` when the wait found nothing owed (every answer recorded before\n * that wait started, at epoch ms `before`, was consumed: by this settle or by\n * a wait the model ran itself). The delegate side wakes pi only for answers no\n * settle showed.\n */\nexport type SettleDelivered = (shown: readonly string[] | { before: number }) => void;\nconst noDelivered: SettleDelivered = () => {};\n\n/**\n * The keep-driving settle wait. Every completed settle (no once-per-prompt latch,\n * no shell parsing: producers arm the wait from state) runs the ONE wait,\n * `mu wait --first --on-stall exit --json`, as this session's callers. The turn\n * then ends only when the wait says nothing is owed (WaitNothingError, or drained),\n * a human stop is open (ready events are still shown: no blocking wait, no\n * continue), the wait failed (shown), or the user cancelled it (Esc,\n * typed input, a dialog, shutdown). A heartbeat timeout with work still owed waits\n * again. An event continues the turn with the wait's own result (a wave's summary\n * replaces it: its snapshots predate the siblings' answers), which survives a\n * late hold (it was consumed). A delegate event adds that call's report; one of a\n * wave first waits for the rest of the wave (refused calls are listed, never\n * waited on) and adds ONE summary.\n */\nexport function registerNudge(\n pi: MuNudgeApi,\n run: MuRunner = defaultRunner(),\n skillMd: string | undefined = readSkill(),\n nested: NestedCheck = notNested,\n hold: SettleHold = noHold,\n delivered: SettleDelivered = noDelivered,\n): void {\n if (!nudgeEnabled()) return;\n if (process.env.MU_REMOTE === \"1\") return; // no mu DB on a remote host\n const rule = skillMd === undefined ? undefined : keepDrivingRule(skillMd);\n if (rule === undefined) return; // no markers: nothing true to quote\n\n let current: AbortController | undefined;\n const cancel = (): void => current?.abort();\n pi.on(\"input\", cancel);\n pi.on(\"ui_prompt_start\", cancel);\n pi.on(\"session_shutdown\", cancel);\n\n pi.on(\"agent_before_settle\", async (event, ctx) => {\n if (nested() || hold(ctx)) return;\n if (outcomeOf(event) !== \"completed\") return; // Esc or an error: stop\n const sid = sessionIdOf(ctx);\n if (identityEnvs(sid).length === 0) return; // no caller: nothing can be owed\n const env = { PI_SESSION_ID: sid };\n const ctl = new AbortController();\n current = ctl;\n const off =\n ctx?.ui?.onTerminalInput?.((data) => {\n if (ESC.test(data)) ctl.abort();\n return undefined; // never consumed: pi still sees the key\n }) ?? (() => {});\n const wait = (args: readonly string[]) =>\n run(args, ctl.signal, undefined, { env, drainMs: SETTLE_DRAIN_MS });\n const mu: Run1 = async (args) =>\n envelopeOf(\n (await run(args, undefined, undefined, { env }).catch(() => undefined))?.stdout ?? \"\",\n );\n const call = async (id: string): Promise<CallRow | undefined> => {\n const v = await mu([\"delegates\", \"show\", id, \"--json\"]);\n return (v?.ok === true ? v.data?.call : undefined) as CallRow | undefined;\n };\n /**\n * The report block(s) of a consumed delegate event. One of a wave keeps\n * running the same owned wait while siblings are pending (refused ones are\n * not waited on: they need a reissue), folding each sibling's answer into ONE\n * summary; any other event ends that and is shown after it. `stop`: a human\n * stop came with one of those results.\n */\n const answers = async (\n callId: string,\n shown: Set<string>,\n first: Record<string, unknown>,\n ): Promise<{\n blocks: string[];\n stop: boolean;\n /** A wave's: its label, whether every call was handed over, and its waits' notices. */\n wave?: { label: string; complete: boolean; notices: string[] };\n }> => {\n shown.add(callId);\n const c = await call(callId);\n if (c === undefined)\n return {\n blocks: [\n `Delegate answer: call ${callId}. Its row is unreadable here: mu delegates show ${callId}`,\n ],\n stop: false,\n };\n const wave = c.wave;\n if (!wave) return { blocks: [await answerBlock(mu, c, REPORT_CAP)], stop: false };\n const listed = async () => {\n const v = await mu([\"delegates\", \"list\", \"--wave\", wave, \"--json\"]);\n const items = (v?.ok === true ? v.data?.items : undefined) as CallRow[] | undefined;\n return Array.isArray(items) ? items : [c];\n };\n const after: string[] = [];\n const notices = new Set<string>(noticesOf(first));\n let stop = false;\n let rows = await listed();\n // Owed: a pending sibling, or a finished one whose event this wait has not yet handed over\n // (the cursor still owes it: leaving it would repeat the summary one settle per call). The\n // latest wait's picture says which: it drops what an earlier wait already consumed, so a\n // sibling absent from it is not owed (waiting for it would never end).\n let picture = pictureOf(first);\n const owedRow = (r: CallRow) =>\n PENDING_STATES.has(r.state) ||\n (r.state !== \"refused\" && !shown.has(r.callId) && picture?.has(r.callId) !== false);\n while (!ctl.signal.aborted && rows.some(owedRow)) {\n const r = await wait(SETTLE_WAIT_ARGS);\n const v = envelopeOf(r.stdout);\n if (v?.ok === false && v.error === \"WaitNothingError\") break;\n const d = v?.ok === true ? v.data : undefined;\n if (d === undefined) {\n after.push(\n `The wave's wait failed (exit ${r.code}): ${(r.stdout.trim() || r.stderr.trim()).slice(0, 500)}`,\n );\n break;\n }\n if (d.interrupted === true || d.drained === true) break;\n for (const n of noticesOf(d)) notices.add(n);\n picture = pictureOf(d);\n if (d.timedOut === true) continue;\n if (Array.isArray(d.humanNeeds) && d.humanNeeds.length > 0) stop = true;\n const id = firingDelegate(d);\n const sibling = id !== undefined && rows.some((x) => x.callId === id);\n if (id !== undefined) shown.add(id);\n if (sibling && !stop) {\n rows = await listed();\n continue;\n }\n // Another event ended the wave's wait: it is consumed, so it is shown too.\n after.push(`Another event came before the rest of wave ${wave}:\\n${JSON.stringify(d)}`);\n const oc = id === undefined || sibling ? undefined : await call(id);\n if (oc) after.push(await answerBlock(mu, oc, REPORT_CAP));\n break;\n }\n rows = await listed();\n const complete = !ctl.signal.aborted && after.length === 0 && !rows.some(owedRow);\n const bodies = await Promise.all(\n rows.filter((x) => shown.has(x.callId)).map((x) => answerBlock(mu, x, WAVE_REPORT_CAP)),\n );\n return {\n blocks: [waveSummary(wave, rows), ...bodies, ...after],\n stop,\n wave: { label: wave, complete, notices: [...notices] },\n };\n };\n /**\n * The settle under an open human stop: drain the events already ready (each\n * delegate answer with its report), show them, and never continue. Nothing\n * ready: the turn ends quietly.\n */\n const ready = async (): Promise<SettleResult> => {\n const blocks: string[] = [];\n const shown: string[] = [];\n for (let i = 0; i < READY_MAX && !ctl.signal.aborted; i++) {\n const started = Date.now();\n const r = await wait(SETTLE_READY_ARGS);\n const v = envelopeOf(r.stdout);\n if (v?.ok === false && v.error === \"WaitNothingError\") {\n delivered({ before: started });\n break;\n }\n const d = v?.ok === true ? v.data : undefined;\n if (d === undefined) {\n const why = (r.stdout.trim() || r.stderr.trim()).slice(0, 2000);\n blocks.push(`mu wait failed (exit ${r.code}): ${why}`);\n break;\n }\n if (d.drained === true) delivered({ before: started });\n if (d.interrupted === true || d.drained === true || d.timedOut === true) break;\n blocks.push(JSON.stringify(d));\n const id = firingDelegate(d);\n if (id === undefined) continue;\n shown.push(id);\n const c = await call(id);\n blocks.push(\n c === undefined\n ? `Delegate answer: call ${id}. Its row is unreadable here: mu delegates show ${id}`\n : await answerBlock(mu, c, REPORT_CAP),\n );\n }\n if (shown.length > 0) delivered(shown);\n if (blocks.length === 0) return undefined;\n const text = [\n \"[mu] A human stop is open (mu human-needed), so the settle did not wait. It showed what was already ready:\",\n ...blocks.flatMap((b) => [\"\", b]),\n ].join(\"\\n\");\n return { entries: [entry(text)], receipt: true };\n };\n let result: SettleResult;\n try {\n result = await (async (): Promise<SettleResult> => {\n for (;;) {\n const needs = await humanNeeds(run, sid);\n if (ctl.signal.aborted || hold(ctx)) return undefined;\n if (needs === undefined)\n return {\n entries: [\n entry(\n \"[mu] settle: could not read your open human needs (mu state --me); not waiting.\",\n ),\n ],\n };\n if (needs > 0) return ready(); // a deliberate human stop: show what is ready, never block\n const started = Date.now();\n const r = await wait(SETTLE_WAIT_ARGS);\n const v = envelopeOf(r.stdout);\n if (v?.ok === false && v.error === \"WaitNothingError\") {\n delivered({ before: started }); // nothing owed: every finished answer was consumed\n return undefined;\n }\n if (v === undefined || v.ok !== true || v.data === undefined) {\n const why = (r.stdout.trim() || r.stderr.trim()).slice(0, 2000);\n return { entries: [entry(`[mu] settle: mu wait failed (exit ${r.code}): ${why}`)] };\n }\n const d = v.data;\n if (d.drained === true) delivered({ before: started });\n if (d.interrupted === true || d.drained === true) return undefined; // cancelled, or nothing owed\n if (d.timedOut === true) continue; // work still owed: wait again\n const callId = firingDelegate(d);\n const shown = new Set<string>();\n const got = callId === undefined ? undefined : await answers(callId, shown, d);\n const blocks = got?.blocks ?? [];\n if (shown.size > 0) delivered([...shown]);\n const humanStop = Array.isArray(d.humanNeeds) && d.humanNeeds.length > 0;\n const stop = humanStop || got?.stop === true;\n const ran = `Work you own is still running, so the settle ran \\`mu ${SETTLE_WAIT_ARGS.join(\" \")}\\` for you.`;\n // A wave's summary supersedes the first wait's result: its snapshots predate the\n // siblings' answers (they would still read \"running\"). Kept when it carries a human need.\n // Its notices (a course check due) are never cut by the wait, so they stay.\n const w = got?.wave;\n const head =\n w !== undefined && !humanStop\n ? [\n w.complete\n ? `${ran} It waited until wave ${w.label} was in:`\n : `${ran} It waited for wave ${w.label}, which is not all in (below):`,\n ...w.notices.map((n) => `Notice: ${n}`),\n ]\n : [`${ran} Its result:`, JSON.stringify(d)];\n const text = [`[mu] ${rule}`, \"\", ...head, ...blocks.flatMap((b) => [\"\", b])].join(\"\\n\");\n return { entries: [entry(text)], ...(stop ? {} : { continue: true }), receipt: true };\n }\n })();\n } finally {\n off();\n if (current === ctl) current = undefined;\n }\n return result;\n });\n}\n\n/** The mu-spawned worker this pi runs as, or undefined outside mu. */\nexport function workerIdentity(\n env: NodeJS.ProcessEnv = process.env,\n): { agent: string; workstream: string } | undefined {\n const agent = env.MU_AGENT_NAME;\n const workstream = env.MU_WORKSTREAM;\n if (!agent || !workstream || workstream === \"scratch\") return undefined;\n return { agent, workstream };\n}\n\n/**\n * IN_PROGRESS task names owned by `agent`, from `mu task owned-by --json`. A\n * `kind=delegate` task is left out: a delegate is spawned with `--task` bound\n * to its own call task, and that call records the answer and closes it\n * (finishDelegate); a pane that closed it itself would lose the answer.\n */\nasync function ownedInProgress(\n run: MuRunner,\n agent: string,\n workstream: string,\n): Promise<string[] | undefined> {\n try {\n const items = await allItems(\n run,\n [\"task\", \"owned-by\", agent, \"-w\", workstream, \"--json\"],\n \"--full\",\n );\n if (items === undefined) return undefined;\n return items.flatMap((t) =>\n t.status === \"IN_PROGRESS\" && t.kind !== \"delegate\" && t.id ? [t.id] : [],\n );\n } catch {\n return undefined;\n }\n}\n\n/** The close-nudge text: name each task and the two ways out. */\nexport function closeNudgeText(workstream: string, names: string[]): string {\n const close = names\n .map((n) => `mu task close ${n} -w ${workstream} --evidence \"<what you verified>\"`)\n .join(\"\\n \");\n return [\n `[mu] You are stopping while you still own ${names.map((n) => `${workstream}/${n}`).join(\", \")} (IN_PROGRESS).`,\n \"If the work is done and verified, close it now:\",\n ` ${close}`,\n \"If you are blocked or need an answer, say so in one line and stop; the orchestrator will read your pane.\",\n ].join(\"\\n\");\n}\n\nexport function registerCloseNudge(\n pi: MuNudgeApi,\n run: MuRunner = defaultRunner(),\n env: NodeJS.ProcessEnv = process.env,\n nested: NestedCheck = notNested,\n hold: SettleHold = noHold,\n): void {\n if (!nudgeEnabled(env)) return;\n // A remote worker has no mu DB: `mu task owned-by` there would read nothing.\n // The orchestrator owns CLOSE (spawn --host sets MU_REMOTE=1).\n if (env.MU_REMOTE === \"1\") return;\n const me = workerIdentity(env);\n if (me === undefined) return;\n let fired = false;\n\n pi.on(\"input\", () => {\n fired = false;\n });\n\n pi.on(\"agent_before_settle\", async (event, ctx) => {\n if (fired || nested() || noUI(ctx) || hold(ctx)) return; // nested: workerIdentity is the parent's\n if (outcomeOf(event) !== \"completed\") return;\n fired = true;\n const names = await ownedInProgress(run, me.agent, me.workstream);\n if (names === undefined || names.length === 0) return;\n if (hold(ctx)) {\n fired = false;\n return;\n }\n breadcrumb(run, [\n \"log\",\n \"-w\",\n me.workstream,\n \"--kind\",\n NUDGE_LOG_KIND,\n `close: ${me.agent} settled owning ${names.join(\", \")}`,\n ]);\n return {\n entries: [\n {\n type: \"custom_message\",\n customType: CLOSE_NUDGE_MESSAGE_TYPE,\n content: closeNudgeText(me.workstream, names),\n display: true,\n },\n ],\n continue: true,\n yielded: () => {\n fired = false;\n },\n };\n });\n}\n"],"mappings":";AASA,SAAS,kBAAkB;AAC3B;AAAA,EACE;AAAA,EACA,cAAAA;AAAA,EACA;AAAA,EACA,aAAAC;AAAA,EACA,gBAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA,YAAAC;AAAA,OACK;AACP,SAAS,SAAS,oBAA8C;AAChE,SAAS,SAAS,QAAAC,aAAY;;;ACfvB,IAAM,uBAAuB;AA+E7B,IAAM,eAAe,CAAC,OAAO,UAAU,SAAS;AAQhD,IAAM,UAAU;AAAA,EACrB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AASO,IAAM,eAAe,CAAC,eAAe,SAAS,OAAO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E;AACA,aAAO,KAAK,EAAE,OAAO,KAAK,CAAC;AAAA,IAC7B;AACA,MAAE,SAAS;AACX,MAAE,MAAM,QAAQ,QAAQ;AACxB,MAAE,SAAS;AAAA,EACb;AAEA,KAAG,GAAG,iBAAiB,OAAO,GAAG,MAAM;AACrC,MAAE,MAAM;AACR,QAAI,SAAS,CAAC,MAAM,YAAY,EAAE,SAAS,SAAS,SAAU,GAAE,QAAQ,WAAW;AACnF,UAAM,IAAI,EAAE;AACZ,QAAI,GAAG;AAEL,UAAI,EAAE,QAAQ,UAAa,QAAQ,QAAQ,MAAM,EAAE,IAAK;AAGxD,QAAE,SAAS;AACX,QAAE,MAAM;AACR,QAAE,MAAM;AAAA,IACV;AACA,UAAM,KAAK;AAAA,EACb,CAAC;AAED,KAAG,GAAG,oBAAoB,OAAO,MAAM;AAIrC,UAAMK,UAAS,SAAS,CAAC;AACzB,QAAIA,YAAW,SAASA,YAAW,YAAYA,YAAW,UAAUA,YAAW,UAAU;AACvF;AAAA,IACF;AACA,UAAM,IAAI,EAAE;AACZ,UAAM,MAAM,EAAE;AACd,MAAE,SAAS;AACX,MAAE,MAAM;AACR,QAAI,OAAO,QAAQ;AACnB,QAAI,CAAC,EAAG;AACR,MAAE,QAAQ,MAAM;AAChB,gBAAY,KAAK,qBAAqB,CAAC;AACvC,kBAAc,KAAK,qBAAqB,CAAC;AACzC,eAAW,KAAK,EAAE,MAAO,GAAE,QAAQ;AACnC,UAAM,IAAI,QAAc,CAAC,YAAY,EAAE,MAAM,MAAM,QAAQ,CAAC,CAAC;AAE7D,QAAI,QAAQ,UAAa,QAAQ,QAAQ,MAAM,IAAK,QAAO,UAAU,EAAE,OAAO,KAAK,CAAC;AAAA,EACtF,CAAC;AAED,SAAO,MAAM,EAAE,WAAW;AAC5B;","names":["existsSync","mkdirSync","readFileSync","statSync","join","reason","W","call","reason","join","join","why","W","call","reason","entry","fail","text","key","a","e","existsSync","readFileSync","join","join","existsSync","readFileSync","call","entry","join","existsSync","readFileSync","statSync","mkdirSync","reason"]}