negotium 0.1.12 → 0.1.13

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 (137) hide show
  1. package/dist/canonical-mcp-bridge.js +2 -3
  2. package/dist/canonical-mcp-bridge.js.map +1 -1
  3. package/dist/chunk-a9y2rwxf.js.map +1 -1
  4. package/dist/{chunk-j0kjscb7.js → chunk-s2gez3wg.js} +20 -2
  5. package/dist/{chunk-j0kjscb7.js.map → chunk-s2gez3wg.js.map} +2 -2
  6. package/dist/cron.js +49 -25
  7. package/dist/cron.js.map +15 -14
  8. package/dist/hosted-agent.js +3012 -17
  9. package/dist/hosted-agent.js.map +30 -3
  10. package/dist/main.js +31323 -36
  11. package/dist/main.js.map +198 -3
  12. package/dist/prompts.js +11 -8
  13. package/dist/prompts.js.map +4 -4
  14. package/dist/runtime/src/application/submit-user-message.ts +3 -0
  15. package/dist/runtime/src/index.ts +7 -0
  16. package/dist/runtime/src/mcp/runtime-spec.ts +3 -0
  17. package/dist/runtime/src/mcp/session-comm/server.ts +1 -1
  18. package/dist/runtime/src/platform/mcp-config.ts +13 -0
  19. package/dist/runtime/src/prompts/builders.ts +20 -6
  20. package/dist/runtime/src/query/active-rooms.ts +2 -0
  21. package/dist/runtime/src/runtime/delivery-ack.ts +112 -0
  22. package/dist/runtime/src/runtime/errors.ts +12 -12
  23. package/dist/runtime/src/runtime/turn-runner.ts +12 -0
  24. package/dist/runtime/src/storage/runtime-turn-requests.ts +1 -0
  25. package/dist/runtime/src/types/api.ts +2 -0
  26. package/dist/runtime/src/types.ts +2 -0
  27. package/dist/runtime/src/version.ts +1 -1
  28. package/dist/runtime-helpers.js.map +1 -1
  29. package/dist/storage.js.map +1 -1
  30. package/dist/types/packages/core/src/mcp/runtime-spec.d.ts +2 -0
  31. package/dist/types/packages/core/src/platform/mcp-config.d.ts +4 -0
  32. package/dist/types/packages/core/src/prompts/builders.d.ts +2 -0
  33. package/dist/types/packages/core/src/types/api.d.ts +2 -0
  34. package/dist/types/packages/core/src/types.d.ts +2 -0
  35. package/dist/types/packages/core/src/version.d.ts +1 -1
  36. package/dist/vault.js.map +1 -1
  37. package/package.json +1 -1
  38. package/dist/chunk-00q25k7p.js +0 -2387
  39. package/dist/chunk-00q25k7p.js.map +0 -26
  40. package/dist/chunk-03kv7mvj.js +0 -2152
  41. package/dist/chunk-03kv7mvj.js.map +0 -15
  42. package/dist/chunk-05pm51dh.js +0 -589
  43. package/dist/chunk-05pm51dh.js.map +0 -11
  44. package/dist/chunk-0eh16bk1.js +0 -2936
  45. package/dist/chunk-0eh16bk1.js.map +0 -20
  46. package/dist/chunk-0yfqyv88.js +0 -108
  47. package/dist/chunk-0yfqyv88.js.map +0 -10
  48. package/dist/chunk-1k7t7bnx.js +0 -97
  49. package/dist/chunk-1k7t7bnx.js.map +0 -10
  50. package/dist/chunk-3gkfr9vb.js +0 -431
  51. package/dist/chunk-3gkfr9vb.js.map +0 -11
  52. package/dist/chunk-5akd1gbj.js +0 -281
  53. package/dist/chunk-5akd1gbj.js.map +0 -10
  54. package/dist/chunk-7k19pcg8.js +0 -577
  55. package/dist/chunk-7k19pcg8.js.map +0 -14
  56. package/dist/chunk-81tbfbmt.js +0 -10
  57. package/dist/chunk-81tbfbmt.js.map +0 -10
  58. package/dist/chunk-82qhv1mq.js +0 -512
  59. package/dist/chunk-82qhv1mq.js.map +0 -13
  60. package/dist/chunk-8dy7e2a9.js +0 -103
  61. package/dist/chunk-8dy7e2a9.js.map +0 -10
  62. package/dist/chunk-8f2sqmrj.js +0 -1712
  63. package/dist/chunk-8f2sqmrj.js.map +0 -18
  64. package/dist/chunk-9hjeemfz.js +0 -372
  65. package/dist/chunk-9hjeemfz.js.map +0 -10
  66. package/dist/chunk-a4aa2ccv.js +0 -141
  67. package/dist/chunk-a4aa2ccv.js.map +0 -10
  68. package/dist/chunk-bsg215q3.js +0 -3536
  69. package/dist/chunk-bsg215q3.js.map +0 -20
  70. package/dist/chunk-bxnfsc7w.js +0 -58
  71. package/dist/chunk-bxnfsc7w.js.map +0 -10
  72. package/dist/chunk-c500xe9z.js +0 -33
  73. package/dist/chunk-c500xe9z.js.map +0 -10
  74. package/dist/chunk-cngrf7ab.js +0 -149
  75. package/dist/chunk-cngrf7ab.js.map +0 -10
  76. package/dist/chunk-d7tprf06.js +0 -53
  77. package/dist/chunk-d7tprf06.js.map +0 -10
  78. package/dist/chunk-ddnrmkrv.js +0 -61
  79. package/dist/chunk-ddnrmkrv.js.map +0 -10
  80. package/dist/chunk-edb07sjp.js +0 -567
  81. package/dist/chunk-edb07sjp.js.map +0 -14
  82. package/dist/chunk-ejcm6zx8.js +0 -591
  83. package/dist/chunk-ejcm6zx8.js.map +0 -11
  84. package/dist/chunk-ezs352qs.js +0 -237
  85. package/dist/chunk-ezs352qs.js.map +0 -11
  86. package/dist/chunk-f5xgprg1.js +0 -59
  87. package/dist/chunk-f5xgprg1.js.map +0 -10
  88. package/dist/chunk-fbtb3v0s.js +0 -1339
  89. package/dist/chunk-fbtb3v0s.js.map +0 -16
  90. package/dist/chunk-ffefbd3r.js +0 -17
  91. package/dist/chunk-ffefbd3r.js.map +0 -10
  92. package/dist/chunk-gaknyw04.js +0 -708
  93. package/dist/chunk-gaknyw04.js.map +0 -14
  94. package/dist/chunk-gxmny6tq.js +0 -1637
  95. package/dist/chunk-gxmny6tq.js.map +0 -15
  96. package/dist/chunk-h7bj5zwb.js +0 -3069
  97. package/dist/chunk-h7bj5zwb.js.map +0 -32
  98. package/dist/chunk-hp4g7wx7.js +0 -46
  99. package/dist/chunk-hp4g7wx7.js.map +0 -10
  100. package/dist/chunk-hwy3n31w.js +0 -21
  101. package/dist/chunk-hwy3n31w.js.map +0 -9
  102. package/dist/chunk-jzz91jwh.js +0 -70
  103. package/dist/chunk-jzz91jwh.js.map +0 -10
  104. package/dist/chunk-k778y16p.js +0 -153
  105. package/dist/chunk-k778y16p.js.map +0 -11
  106. package/dist/chunk-mh5mexsf.js +0 -147
  107. package/dist/chunk-mh5mexsf.js.map +0 -11
  108. package/dist/chunk-mnwaext5.js +0 -318
  109. package/dist/chunk-mnwaext5.js.map +0 -10
  110. package/dist/chunk-nkgs40ch.js +0 -23
  111. package/dist/chunk-nkgs40ch.js.map +0 -10
  112. package/dist/chunk-pz57vwsm.js +0 -250
  113. package/dist/chunk-pz57vwsm.js.map +0 -11
  114. package/dist/chunk-r6kdp7gn.js +0 -252
  115. package/dist/chunk-r6kdp7gn.js.map +0 -10
  116. package/dist/chunk-rkvrkcgx.js +0 -117
  117. package/dist/chunk-rkvrkcgx.js.map +0 -10
  118. package/dist/chunk-s74rdyqe.js +0 -117
  119. package/dist/chunk-s74rdyqe.js.map +0 -12
  120. package/dist/chunk-sa874j5c.js +0 -9
  121. package/dist/chunk-sa874j5c.js.map +0 -10
  122. package/dist/chunk-sffqdkvq.js +0 -122
  123. package/dist/chunk-sffqdkvq.js.map +0 -10
  124. package/dist/chunk-tcs9qjps.js +0 -64
  125. package/dist/chunk-tcs9qjps.js.map +0 -10
  126. package/dist/chunk-wx83ep8e.js +0 -131
  127. package/dist/chunk-wx83ep8e.js.map +0 -10
  128. package/dist/chunk-xag86ng3.js +0 -122
  129. package/dist/chunk-xag86ng3.js.map +0 -10
  130. package/dist/chunk-xfdkep71.js +0 -371
  131. package/dist/chunk-xfdkep71.js.map +0 -11
  132. package/dist/chunk-xhm1rfpt.js +0 -2907
  133. package/dist/chunk-xhm1rfpt.js.map +0 -24
  134. package/dist/chunk-xpcps28p.js +0 -2138
  135. package/dist/chunk-xpcps28p.js.map +0 -29
  136. package/dist/chunk-yb4rbev9.js +0 -214
  137. package/dist/chunk-yb4rbev9.js.map +0 -10
@@ -1,26 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../../packages/core/src/agents/codex-tree-kill.ts", "../../../packages/core/src/security/sensitive-path.ts", "../../../packages/core/src/storage/vault.ts", "../../../packages/core/src/storage/vault-crypto.ts", "../../../packages/core/src/mcp/runtime-spec.ts", "../../../packages/core/src/platform/mcp-config.ts", "../../../packages/core/src/mcp/session-comm/bridge-ipc-config.ts", "../../../packages/core/src/agents/execution-host.ts", "../../../packages/core/src/agents/vault-tool-policy.ts", "../../../packages/core/src/media/file-events.ts", "../../../packages/core/src/platform/error.ts", "../../../packages/core/src/version.ts", "../../../packages/core/src/agents/claude-provider.ts", "../../../packages/core/src/agents/deep-map.ts", "../../../packages/core/src/agents/codex-provider.ts", "../../../packages/core/src/agents/codex-native-multi-agent.ts", "../../../packages/core/src/agents/maestro-provider.ts"],
4
- "sourcesContent": [
5
- "/**\n * Codex process tree kill helper.\n *\n * The @openai/codex-sdk spawns `codex` as a direct child of our bot process but\n * does not expose the resulting PID and does not detach the child into its own\n * process group. So when we call `abortController.abort()`, the SDK sends a\n * single SIGTERM that may or may not reach grandchild tool processes (shells,\n * MCP servers spawned by codex itself). To guarantee abort actually stops\n * activity we identify the codex children we spawned and SIGTERM their whole\n * descendant tree, with a SIGKILL fallback for stragglers.\n *\n * Strategy (post-2026-05-14 fix):\n * 1. Acquire a global spawn lock that's held across the entire window\n * from baseline snapshot through the first SDK event (when codex is\n * actually spawned — `runStreamed()` returns a lazy async generator,\n * so the real `child_process.spawn()` happens on the first iterator\n * `.next()`, not when `runStreamed()` is awaited).\n * 2. Snapshot direct codex children of `process.pid` BEFORE forcing the\n * first iterator step.\n * 3. After the first event lands, diff against a fresh snapshot to\n * identify our PIDs and register them in `globalOwnedCodexPids` so\n * concurrent codex callers don't claim them as their own.\n * 4. On abort, walk each PID's descendant tree via `pgrep -P` and signal\n * every node. Unregister on exit.\n *\n * Platform: relies on `pgrep` and `ps` — macOS/Linux only. Windows is not\n * supported (Otium already requires POSIX for the rest of the stack).\n */\n\nimport { execFileSync } from \"node:child_process\";\nimport { logger } from \"#platform/logger\";\n\n// 5s gives MCP stdio servers (codex spawns these as grandchildren) a realistic\n// shutdown window. 2s was empirically too aggressive: stdio MCP servers in the\n// middle of writing a response would get SIGKILL'd before they finished.\nconst SIGKILL_DELAY_MS = 5_000;\nconst CODEX_PROC_NAME_MATCH = /codex/i;\n// Cap tree-walk depth. Defends against pathological or malicious cycles that\n// slip past the visited-set guard (e.g. via PID reuse), and against deeply\n// nested codex+MCP+shell trees blowing the stack.\nconst TREE_DEPTH_CAP = 16;\n\n/** Return direct child PIDs of `parentPid`. Returns [] on error or no children. */\nfunction getDirectChildren(parentPid: number): number[] {\n try {\n const out = execFileSync(\"pgrep\", [\"-P\", String(parentPid)], {\n encoding: \"utf8\",\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n }).trim();\n if (!out) return [];\n return out\n .split(\"\\n\")\n .map((s) => Number(s))\n .filter((n) => Number.isFinite(n) && n > 0);\n } catch {\n // pgrep exits 1 when no matches; treat as empty.\n return [];\n }\n}\n\n/** Return the executable name (comm) of a process, or \"\" if unavailable. */\nfunction getProcName(pid: number): string {\n try {\n return execFileSync(\"ps\", [\"-p\", String(pid), \"-o\", \"comm=\"], {\n encoding: \"utf8\",\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n }).trim();\n } catch {\n return \"\";\n }\n}\n\n/**\n * Return the start time of `pid` as the raw `ps -o lstart=` string (e.g.\n * \"Tue May 12 10:49:35 2026\"), or \"\" if unavailable. Used as a fingerprint\n * to defend against PID reuse — even if the OS reassigns a baseline PID to\n * a fresh codex spawn, the lstart string will differ.\n *\n * macOS and Linux both support `ps -o lstart=` with the same date format.\n */\nfunction getProcLstart(pid: number): string {\n try {\n return execFileSync(\"ps\", [\"-p\", String(pid), \"-o\", \"lstart=\"], {\n encoding: \"utf8\",\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n }).trim();\n } catch {\n return \"\";\n }\n}\n\n/** (pid, lstart) fingerprint pair — same PID + same lstart = same process. */\nexport type CodexProcStamp = { pid: number; lstart: string };\n\n/**\n * Recursively collect `rootPid` and all its descendants, up to `TREE_DEPTH_CAP`\n * levels deep. Cycle-safe via the `out` Set; depth-cap-safe via the `depth`\n * parameter (defends against pathological trees the Set guard might miss,\n * e.g. PID reuse mid-walk).\n */\nfunction collectTree(rootPid: number, out: Set<number> = new Set(), depth = 0): Set<number> {\n if (out.has(rootPid)) return out;\n out.add(rootPid);\n if (depth >= TREE_DEPTH_CAP) {\n logger.warn(\n { rootPid, depth, cap: TREE_DEPTH_CAP },\n \"codex-tree-kill: tree depth cap reached, descendants beyond this point not collected\",\n );\n return out;\n }\n for (const child of getDirectChildren(rootPid)) {\n collectTree(child, out, depth + 1);\n }\n return out;\n}\n\n/**\n * Snapshot current codex-named direct children of `process.pid` along with\n * each PID's lstart (start time) fingerprint. Returning the lstart map lets\n * `findNewCodexChildren` distinguish \"PID X was in baseline and is the same\n * process\" from \"PID X was in baseline but the OS reassigned that PID to a\n * fresh codex\" — only the latter is novel.\n */\nexport function snapshotCodexChildren(): Map<number, string> {\n const out = new Map<number, string>();\n for (const pid of getDirectChildren(process.pid)) {\n const name = getProcName(pid);\n if (!name || !CODEX_PROC_NAME_MATCH.test(name)) continue;\n const lstart = getProcLstart(pid);\n // If lstart can't be read (race: process died between getDirectChildren\n // and getProcLstart), still record the PID with an empty fingerprint —\n // any later snapshot with a real lstart will compare as \"different\" and\n // count it as novel, which is the safer side to err on.\n out.set(pid, lstart);\n }\n return out;\n}\n\n/**\n * PIDs already owned by an active codex caller (normal provider or fork).\n * `findNewCodexChildren` excludes these so concurrent callers can't claim\n * each other's PIDs when their baselines happen to miss them (e.g. the other\n * caller's spawn raced in between baseline and first-event diff).\n *\n * Callers must `registerOwnedCodexPids` after diff, and `unregisterOwnedCodexPids`\n * in their cleanup `finally` block to avoid leaking entries on long-running bots.\n */\nconst globalOwnedCodexPids = new Set<number>();\n\nexport function registerOwnedCodexPids(pids: Iterable<number>): void {\n for (const p of pids) globalOwnedCodexPids.add(p);\n}\n\nexport function unregisterOwnedCodexPids(pids: Iterable<number>): void {\n for (const p of pids) globalOwnedCodexPids.delete(p);\n}\n\n/**\n * Codex children that are novel relative to `baseline`. A PID is novel if:\n * - it wasn't in baseline, OR\n * - it was in baseline but with a different lstart (PID reuse — old codex\n * died and the OS reassigned the PID to our new spawn)\n * AND it isn't already owned by a concurrent codex caller.\n */\nexport function findNewCodexChildren(baseline: Map<number, string>): number[] {\n const current = snapshotCodexChildren();\n const novel: number[] = [];\n for (const [pid, lstart] of current) {\n const baselineLstart = baseline.get(pid);\n // Same PID + same lstart fingerprint → continuation of the same process,\n // not novel. Same PID + different lstart → PID reuse, treat as novel.\n if (baselineLstart !== undefined && baselineLstart === lstart) continue;\n if (globalOwnedCodexPids.has(pid)) continue;\n novel.push(pid);\n }\n return novel;\n}\n\n/**\n * Serialize the spawn critical section across concurrent codex callers\n * (`codexProvider` and `queryCodexForkSession`). The lock MUST be held from\n * baseline snapshot through the first generator event, because the SDK's\n * `runStreamed()` is lazy — the actual `child_process.spawn()` happens when\n * the iterator advances, not when `runStreamed()` resolves. Without a lock\n * spanning that window, two callers see overlapping codex children and\n * mis-attribute them on abort, leading to cross-kills.\n *\n * Only the spawn phase is serialized (typically a few hundred ms — codex's\n * first event lands quickly). The actual LLM streaming after the first event\n * runs concurrently as before.\n */\nlet codexSpawnChain: Promise<void> = Promise.resolve();\n\n/**\n * Acquire the codex-spawn lock. Returns a release callback. Caller MUST invoke\n * the release callback in a `finally` block (or via the convenience wrapper\n * `withCodexSpawnSerial`) — otherwise the chain stalls indefinitely.\n */\nexport async function acquireCodexSpawnLock(): Promise<() => void> {\n const prev = codexSpawnChain;\n let release!: () => void;\n let released = false;\n codexSpawnChain = new Promise<void>((r) => {\n release = () => {\n if (released) return;\n released = true;\n r();\n };\n });\n await prev;\n return release;\n}\n\n/**\n * Convenience wrapper for short, single-await critical sections. Prefer\n * `acquireCodexSpawnLock` when the lock must span multiple awaits including\n * iterator advancement (the codex spawn case).\n */\nexport async function withCodexSpawnSerial<T>(fn: () => Promise<T>): Promise<T> {\n const release = await acquireCodexSpawnLock();\n try {\n return await fn();\n } finally {\n release();\n }\n}\n\n/** True iff `pid` is still alive. */\nfunction isAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * True iff `pid` is alive and still appears to be the same process captured by\n * `lstart`. An empty lstart means we could not fingerprint the original process,\n * so we refuse to SIGKILL it later rather than risk killing a reused PID.\n */\nfunction isSameProcess(pid: number, lstart: string): boolean {\n return lstart !== \"\" && isAlive(pid) && getProcLstart(pid) === lstart;\n}\n\ntype CodexKillPlan = {\n rootPids: number[];\n targets: Map<number, string>;\n};\n\n/** Capture the complete tree before signalling changes parent/child relationships. */\nfunction signalCodexTrees(rootPids: number[]): CodexKillPlan | null {\n if (rootPids.length === 0) return null;\n\n const targets = new Map<number, string>();\n for (const root of rootPids) {\n for (const pid of collectTree(root)) {\n if (!targets.has(pid)) targets.set(pid, getProcLstart(pid));\n }\n }\n\n logger.warn({ rootPids, totalPids: targets.size }, \"codex-tree-kill: SIGTERM process tree\");\n for (const pid of targets.keys()) {\n try {\n process.kill(pid, \"SIGTERM\");\n } catch {\n // already dead or permission denied\n }\n }\n return { rootPids, targets };\n}\n\nfunction hasSameProcessSurvivors(targets: Map<number, string>): boolean {\n for (const [pid, lstart] of targets) {\n if (isSameProcess(pid, lstart)) return true;\n }\n return false;\n}\n\n/** Kill survivors from a previously fingerprinted plan without risking PID reuse. */\nfunction killCodexStragglers({ rootPids, targets }: CodexKillPlan): void {\n const aliveTargets: number[] = [];\n let droppedAsPossibleReuse = 0;\n for (const [pid, lstart] of targets) {\n if (isSameProcess(pid, lstart)) {\n aliveTargets.push(pid);\n } else if (isAlive(pid)) {\n droppedAsPossibleReuse++;\n }\n }\n if (aliveTargets.length === 0) return;\n\n // PID-reuse defence: re-walk the trees (children may have spawned siblings\n // mid-SIGTERM), but ONLY signal PIDs that were in the SIGTERM-time targets.\n const reachable = new Set<number>(aliveTargets);\n for (const root of rootPids) {\n const rootLstart = targets.get(root);\n if (rootLstart && isSameProcess(root, rootLstart)) {\n for (const pid of collectTree(root)) reachable.add(pid);\n }\n }\n const stragglers: number[] = [];\n for (const pid of reachable) {\n const lstart = targets.get(pid);\n if (lstart && isSameProcess(pid, lstart)) stragglers.push(pid);\n else if (isAlive(pid)) droppedAsPossibleReuse++;\n }\n logger.warn(\n {\n aliveRoots: rootPids.filter((pid) => {\n const lstart = targets.get(pid);\n return lstart ? isSameProcess(pid, lstart) : false;\n }),\n totalStragglers: stragglers.length,\n droppedAsPossibleReuse,\n },\n \"codex-tree-kill: SIGKILL fallback after SIGTERM timeout\",\n );\n for (const pid of stragglers) {\n try {\n process.kill(pid, \"SIGKILL\");\n } catch {\n // already dead\n }\n }\n}\n\n/**\n * SIGTERM every PID in the descendant tree of each root in `rootPids`, then\n * schedule a SIGKILL fallback after `SIGKILL_DELAY_MS` for any survivors.\n * Safe to call multiple times; no-op if all PIDs are already dead.\n */\nexport function killCodexTrees(rootPids: number[]): void {\n const plan = signalCodexTrees(rootPids);\n if (!plan) return;\n\n const killTimer = setTimeout(() => {\n killCodexStragglers(plan);\n }, SIGKILL_DELAY_MS);\n killTimer.unref?.();\n}\n\n/**\n * Reap every Codex tree owned by this node during process shutdown.\n *\n * The direct-child snapshot covers the narrow spawn window before a provider\n * has registered its PID. Unlike the normal abort path, this function awaits\n * the grace period with a referenced timer so node shutdown cannot exit before\n * SIGKILL fallback has had a chance to remove resistant MCP/shell descendants.\n */\nexport async function killOwnedCodexTreesForShutdown(graceMs = 3_000): Promise<void> {\n const roots = new Set(globalOwnedCodexPids);\n for (const pid of snapshotCodexChildren().keys()) roots.add(pid);\n const plan = signalCodexTrees([...roots]);\n if (!plan) return;\n\n const deadline = Date.now() + Math.max(0, graceMs);\n while (Date.now() < deadline && hasSameProcessSurvivors(plan.targets)) {\n await new Promise<void>((resolve) =>\n setTimeout(resolve, Math.min(100, Math.max(1, deadline - Date.now()))),\n );\n }\n killCodexStragglers(plan);\n}\n",
6
- "import { realpathSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\n\n// --- Sensitive path blacklist ---\n\nconst SENSITIVE_PATH_PATTERNS = [\n /\\/\\.env(\\.|$)/i,\n /\\/\\.ssh\\//i,\n /\\/\\.aws\\//i,\n /\\/\\.gnupg\\//i,\n /\\/\\.netrc$/i,\n /\\/\\.npmrc$/i,\n /\\/(id_rsa|id_ed25519|id_ecdsa|id_dsa)(\\.pub)?$/i,\n /\\.(pem|key|p12|pfx|cer|crt)$/i,\n /\\/Library\\/Keychains\\//i,\n // Runtime-owned stores and key material. Vault values are encrypted, but\n // exposing ciphertext or its master key to an agent defeats that boundary.\n /\\/vault\\.db(-wal|-shm|-journal)?$/i,\n /\\/vault-master-key$/i,\n /\\/runtime-mcp-secret$/i,\n /\\/sessions\\.db(-wal|-shm|-journal)?$/i,\n];\n\nexport function isSensitivePath(filePath: string): boolean {\n const normalized = resolve(filePath);\n if (SENSITIVE_PATH_PATTERNS.some((p) => p.test(normalized))) return true;\n try {\n const real = realpathSync(normalized);\n if (real !== normalized) return SENSITIVE_PATH_PATTERNS.some((p) => p.test(real));\n } catch {\n // File doesn't exist — no symlink concern\n }\n return false;\n}\n",
7
- "import { chmodSync, mkdirSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { DATA_DIR, VAULT_MASTER_KEY } from \"#platform/config\";\nimport { Database } from \"#storage/sqlite\";\nimport { decryptVaultValue, encryptVaultValue } from \"#storage/vault-crypto\";\n\nexport type VaultDatabase = Pick<InstanceType<typeof Database>, \"exec\" | \"prepare\">;\n\nexport interface VaultStorageOptions {\n database?: VaultDatabase;\n dataDir?: string;\n masterKey?: string;\n}\n\nlet vaultDb: VaultDatabase | undefined;\nlet vaultMasterKey = VAULT_MASTER_KEY;\n\nfunction initializeVaultDatabase(database: VaultDatabase): void {\n database.exec(\"PRAGMA journal_mode = WAL\");\n database.exec(\"PRAGMA busy_timeout = 5000\");\n database.exec(`\n CREATE TABLE IF NOT EXISTS vault (\n user_id TEXT NOT NULL,\n key TEXT NOT NULL,\n value TEXT NOT NULL,\n description TEXT NOT NULL DEFAULT '',\n PRIMARY KEY (user_id, key)\n )\n `);\n\n // Migrate legacy schema where user_id was INTEGER (Telegram numeric ids only).\n // The Otium API authenticates with string user ids (\"otium-user-…\"), so user_id\n // is now TEXT for every channel. Rebuild + CAST existing rows so old Telegram\n // secrets survive; idempotent (no-op once user_id is already TEXT).\n {\n const cols = database.prepare(\"PRAGMA table_info(vault)\").all() as {\n name: string;\n type: string;\n }[];\n const uid = cols.find((c) => c.name === \"user_id\");\n if (uid && uid.type.toUpperCase() === \"INTEGER\") {\n database.exec(\"BEGIN\");\n database.exec(`\n CREATE TABLE vault_migrated (\n user_id TEXT NOT NULL,\n key TEXT NOT NULL,\n value TEXT NOT NULL,\n description TEXT NOT NULL DEFAULT '',\n PRIMARY KEY (user_id, key)\n )\n `);\n database.exec(\n \"INSERT INTO vault_migrated SELECT CAST(user_id AS TEXT), key, value, description FROM vault\",\n );\n database.exec(\"DROP TABLE vault\");\n database.exec(\"ALTER TABLE vault_migrated RENAME TO vault\");\n database.exec(\"COMMIT\");\n }\n }\n}\n\nfunction openVaultDatabase(dataDir: string): VaultDatabase {\n const path = join(dataDir, \"vault.db\");\n mkdirSync(dataDir, { recursive: true });\n const database = new Database(path, { create: true });\n // Defense in depth: the database and its sidecars are owner-only, while each\n // value is also encrypted independently by vault-crypto.\n chmodSync(path, 0o600);\n initializeVaultDatabase(database);\n return database;\n}\n\nfunction activeVaultDatabase(): VaultDatabase {\n if (!vaultDb) vaultDb = openVaultDatabase(DATA_DIR);\n return vaultDb;\n}\n\n/** Configure process-wide vault storage during embedding-host bootstrap. */\nexport function configureVaultStorage(options: VaultStorageOptions): () => void {\n if (options.database && options.dataDir) {\n throw new Error(\"configureVaultStorage accepts either database or dataDir, not both\");\n }\n const previousDb = vaultDb;\n const previousMasterKey = vaultMasterKey;\n const configuredDb = options.database ?? openVaultDatabase(options.dataDir ?? DATA_DIR);\n if (options.database) initializeVaultDatabase(configuredDb);\n vaultDb = configuredDb;\n vaultMasterKey = options.masterKey ?? VAULT_MASTER_KEY;\n let disposed = false;\n return () => {\n if (disposed) return;\n disposed = true;\n if (!options.database && \"close\" in configuredDb) {\n (configuredDb as VaultDatabase & { close(): void }).close();\n }\n vaultDb = previousDb;\n vaultMasterKey = previousMasterKey;\n };\n}\n\nexport interface VaultEntry {\n key: string;\n description: string;\n}\n\nexport interface VaultEntryWithValue extends VaultEntry {\n value: string;\n}\n\nexport const VAULT_KEY_PATTERN = /^[A-Z][A-Z0-9_]{0,127}$/;\nexport const VAULT_VALUE_MIN_BYTES = 4;\nexport const VAULT_VALUE_MAX_BYTES = 64 * 1024;\nexport const VAULT_DESCRIPTION_MAX_LENGTH = 500;\n\nexport function normalizeVaultKey(key: string): string {\n return key.trim().toUpperCase();\n}\n\nexport function validateVaultKey(key: string): boolean {\n return VAULT_KEY_PATTERN.test(normalizeVaultKey(key));\n}\n\nfunction decryptRow(userId: string, key: string, storedValue: string): string {\n const database = activeVaultDatabase();\n const decoded = decryptVaultValue(userId, key, storedValue, vaultMasterKey);\n if (decoded.legacyPlaintext) {\n database\n .prepare(\"UPDATE vault SET value = ? WHERE user_id = ? AND key = ? AND value = ?\")\n .run(encryptVaultValue(userId, key, decoded.value, vaultMasterKey), userId, key, storedValue);\n }\n return decoded.value;\n}\n\nexport function vaultListWithValues(userId: string): VaultEntryWithValue[] {\n const rows = activeVaultDatabase()\n .prepare(\"SELECT key, description, value FROM vault WHERE user_id = ? ORDER BY key\")\n .all(userId) as VaultEntryWithValue[];\n return rows.map((row) => ({\n key: row.key,\n description: row.description,\n value: decryptRow(userId, row.key, row.value),\n }));\n}\n\nexport function vaultSet(userId: string, key: string, value: string, description = \"\"): void {\n const normalizedKey = normalizeVaultKey(key);\n activeVaultDatabase()\n .prepare(\n `INSERT INTO vault (user_id, key, value, description) VALUES (?, ?, ?, ?)\n ON CONFLICT (user_id, key) DO UPDATE\n SET value = excluded.value, description = excluded.description`,\n )\n .run(\n userId,\n normalizedKey,\n encryptVaultValue(userId, normalizedKey, value, vaultMasterKey),\n description,\n );\n}\n\nexport function vaultHasKey(userId: string, key: string): boolean {\n const row = activeVaultDatabase()\n .prepare(\"SELECT 1 FROM vault WHERE user_id = ? AND key = ?\")\n .get(userId, normalizeVaultKey(key));\n return row != null;\n}\n\nexport function vaultDel(userId: string, key: string): boolean {\n const result = activeVaultDatabase()\n .prepare(\"DELETE FROM vault WHERE user_id = ? AND key = ?\")\n .run(userId, normalizeVaultKey(key)) as { changes: number };\n return result.changes > 0;\n}\n\nexport function vaultDeleteAllForUser(userId: string): number {\n const result = activeVaultDatabase()\n .prepare(\"DELETE FROM vault WHERE user_id = ?\")\n .run(userId) as {\n changes: number;\n };\n return result.changes;\n}\n\nexport function vaultList(userId: string): VaultEntry[] {\n return activeVaultDatabase()\n .prepare(\"SELECT key, description FROM vault WHERE user_id = ? ORDER BY key\")\n .all(userId) as VaultEntry[];\n}\n\nexport function vaultGetValue(userId: string, key: string): string | undefined {\n const normalizedKey = normalizeVaultKey(key);\n const row = activeVaultDatabase()\n .prepare(\"SELECT key, value FROM vault WHERE user_id = ? AND key = ?\")\n .get(userId, normalizedKey) as { key: string; value: string } | undefined;\n return row ? decryptRow(userId, row.key, row.value) : undefined;\n}\n\nexport interface VaultSubstitutionResult {\n text: string;\n usedKeys: string[];\n}\n\n/** Replace {{KEY}} placeholders and report which credentials were consumed. */\nexport function vaultSubstituteDetailed(userId: string, text: string): VaultSubstitutionResult {\n const entries = new Map(vaultListWithValues(userId).map((entry) => [entry.key, entry.value]));\n const usedKeys = new Set<string>();\n const substituted = text.replace(/\\{\\{([^}]+)\\}\\}/g, (match, rawKey: string) => {\n const key = normalizeVaultKey(rawKey);\n const value = entries.get(key);\n if (value === undefined) return match;\n usedKeys.add(key);\n return value;\n });\n return { text: substituted, usedKeys: [...usedKeys] };\n}\n\n/** Detect real {{KEY}} references without decrypting any Vault values. */\nexport function valueReferencesVaultKey(userId: string, value: unknown): boolean {\n const keys = new Set(vaultList(userId).map((entry) => entry.key));\n const visit = (candidate: unknown): boolean => {\n if (typeof candidate === \"string\") {\n for (const match of candidate.matchAll(/\\{\\{([^}]+)\\}\\}/g)) {\n if (keys.has(normalizeVaultKey(match[1] ?? \"\"))) return true;\n }\n return false;\n }\n if (Array.isArray(candidate)) return candidate.some(visit);\n if (candidate && typeof candidate === \"object\") {\n return Object.values(candidate as Record<string, unknown>).some(visit);\n }\n return false;\n };\n return visit(value);\n}\n\nfunction encodedSecretForms(value: string): string[] {\n const forms = new Set<string>([\n value,\n encodeURIComponent(value),\n Buffer.from(value, \"utf8\").toString(\"base64\"),\n Buffer.from(value, \"utf8\").toString(\"base64url\"),\n Buffer.from(value, \"utf8\").toString(\"hex\"),\n ]);\n forms.delete(\"\");\n return [...forms].sort((a, b) => b.length - a.length);\n}\n\n/** Scrub raw and common encoded forms before tool output reaches a model. */\nexport function redactVaultSecrets(userId: string, text: string): string {\n const candidates = vaultListWithValues(userId)\n .flatMap((entry) => encodedSecretForms(entry.value).map((form) => ({ form, key: entry.key })))\n .sort((a, b) => b.form.length - a.form.length || a.key.localeCompare(b.key));\n if (candidates.length === 0) return text;\n const candidatesByFirstCharacter = new Map<string, typeof candidates>();\n for (const candidate of candidates) {\n const first = candidate.form[0];\n if (!first) continue;\n const bucket = candidatesByFirstCharacter.get(first) ?? [];\n bucket.push(candidate);\n candidatesByFirstCharacter.set(first, bucket);\n }\n\n let redacted = \"\";\n let offset = 0;\n while (offset < text.length) {\n const match = candidatesByFirstCharacter\n .get(text[offset] ?? \"\")\n ?.find((candidate) => text.startsWith(candidate.form, offset));\n if (!match) {\n redacted += text[offset];\n offset += 1;\n continue;\n }\n redacted += `[REDACTED:${match.key}]`;\n offset += match.form.length;\n }\n return redacted;\n}\n",
8
- "import { createCipheriv, createDecipheriv, createHash, randomBytes } from \"node:crypto\";\nimport { VAULT_MASTER_KEY } from \"#platform/config\";\n\nconst ENVELOPE_PREFIX = \"otium-vault:v1:\";\nconst IV_BYTES = 12;\nconst KEY_BYTES = 32;\n\nfunction encryptionKey(masterKey = VAULT_MASTER_KEY): Buffer {\n return createHash(\"sha256\")\n .update(\"otium-vault-value-v1\\0\", \"utf8\")\n .update(masterKey, \"utf8\")\n .digest()\n .subarray(0, KEY_BYTES);\n}\n\nfunction aad(userId: string, key: string): Buffer {\n return Buffer.from(`${userId}\\0${key.toUpperCase()}`, \"utf8\");\n}\n\nexport function isEncryptedVaultValue(value: string): boolean {\n return value.startsWith(ENVELOPE_PREFIX);\n}\n\n/** Encrypt one vault row. The user/key binding prevents ciphertext row swapping. */\nexport function encryptVaultValue(\n userId: string,\n key: string,\n value: string,\n masterKey = VAULT_MASTER_KEY,\n): string {\n const iv = randomBytes(IV_BYTES);\n const cipher = createCipheriv(\"aes-256-gcm\", encryptionKey(masterKey), iv);\n cipher.setAAD(aad(userId, key));\n const ciphertext = Buffer.concat([cipher.update(value, \"utf8\"), cipher.final()]);\n const tag = cipher.getAuthTag();\n return `${ENVELOPE_PREFIX}${iv.toString(\"base64url\")}.${ciphertext.toString(\"base64url\")}.${tag.toString(\"base64url\")}`;\n}\n\n/**\n * Decrypt a stored value. Plaintext rows are accepted for rolling upgrades and\n * are re-encrypted by the storage layer immediately after a successful read.\n */\nexport function decryptVaultValue(\n userId: string,\n key: string,\n storedValue: string,\n masterKey = VAULT_MASTER_KEY,\n): { value: string; legacyPlaintext: boolean } {\n if (!isEncryptedVaultValue(storedValue)) {\n return { value: storedValue, legacyPlaintext: true };\n }\n\n const encoded = storedValue.slice(ENVELOPE_PREFIX.length);\n const [ivPart, ciphertextPart, tagPart, ...extra] = encoded.split(\".\");\n if (!ivPart || ciphertextPart === undefined || !tagPart || extra.length > 0) {\n throw new Error(\"Invalid encrypted vault value\");\n }\n\n const iv = Buffer.from(ivPart, \"base64url\");\n const ciphertext = Buffer.from(ciphertextPart, \"base64url\");\n const tag = Buffer.from(tagPart, \"base64url\");\n if (iv.length !== IV_BYTES || tag.length !== 16) {\n throw new Error(\"Invalid encrypted vault value\");\n }\n\n const decipher = createDecipheriv(\"aes-256-gcm\", encryptionKey(masterKey), iv);\n decipher.setAAD(aad(userId, key));\n decipher.setAuthTag(tag);\n const plaintext = Buffer.concat([decipher.update(ciphertext), decipher.final()]);\n return { value: plaintext.toString(\"utf8\"), legacyPlaintext: false };\n}\n",
9
- "/**\n * Runtime-MCP wiring shared between core (which injects the MCP into agent\n * sessions) and @negotium/mcp (which serves the endpoint).\n *\n * The runtime process exposes one HTTP MCP endpoint; every agent turn gets a\n * per-turn signed token carrying its full execution context, so the MCP layer\n * never trusts the agent to say who it is. Ported from otium runtime-api\n * `mcp/runtime-server.ts` (transport-agnostic parts only).\n */\n\nimport { createHmac, timingSafeEqual } from \"node:crypto\";\nimport { NEGOTIUM_PORT, RUNTIME_MCP_SECRET } from \"#platform/config\";\nimport { type AgentKind, isAgentKind, type PeerRuntimeBridgeContext } from \"#types\";\n\nexport const RUNTIME_MCP_KEY = \"runtime\";\n\nexport const RUNTIME_MCP_BASE_PATH = \"/mcp/runtime\";\nconst TOKEN_TTL_MS = 4 * 60 * 60 * 1000;\nconst CLAUDE_MCP_TOOL_TIMEOUT_MS = 600_000;\n\nexport interface RuntimeMcpContext {\n userId: string;\n topicId: string;\n topicTitle: string;\n queryId?: string;\n cwd: string;\n agent: AgentKind;\n model?: string;\n currentUserPrompt?: string;\n autoContinue?: boolean;\n /** Capability minted by the adapter. Visual tools are absent unless true. */\n visualTools?: boolean;\n peerBridge?: PeerRuntimeBridgeContext;\n}\n\ntype RuntimeTokenPayload = {\n v: 1;\n exp: number;\n ctx: RuntimeMcpContext;\n};\n\nlet runtimePort = NEGOTIUM_PORT;\n\n/** The runtime host calls this once it knows which port it actually bound. */\nexport function setRuntimeMcpPort(port: number): void {\n runtimePort = port;\n}\n\nexport function getRuntimeMcpPort(): number {\n return runtimePort;\n}\n\nfunction encodeTokenPart(value: unknown): string {\n return Buffer.from(JSON.stringify(value), \"utf-8\").toString(\"base64url\");\n}\n\nfunction decodeTokenPart(part: string): unknown {\n return JSON.parse(Buffer.from(part, \"base64url\").toString(\"utf-8\")) as unknown;\n}\n\nfunction signTokenPayload(payloadPart: string): string {\n return createHmac(\"sha256\", RUNTIME_MCP_SECRET).update(payloadPart).digest(\"base64url\");\n}\n\nfunction safeEqual(a: string, b: string): boolean {\n const aa = Buffer.from(a);\n const bb = Buffer.from(b);\n return aa.length === bb.length && timingSafeEqual(aa, bb);\n}\n\nfunction isRuntimeMcpContext(value: unknown): value is RuntimeMcpContext {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n const ctx = value as Partial<RuntimeMcpContext>;\n return (\n typeof ctx.userId === \"string\" &&\n typeof ctx.topicId === \"string\" &&\n typeof ctx.topicTitle === \"string\" &&\n typeof ctx.cwd === \"string\" &&\n typeof ctx.agent === \"string\" &&\n isAgentKind(ctx.agent) &&\n (ctx.queryId === undefined || typeof ctx.queryId === \"string\") &&\n (ctx.model === undefined || typeof ctx.model === \"string\") &&\n (ctx.currentUserPrompt === undefined || typeof ctx.currentUserPrompt === \"string\") &&\n (ctx.autoContinue === undefined || typeof ctx.autoContinue === \"boolean\") &&\n (ctx.visualTools === undefined || typeof ctx.visualTools === \"boolean\") &&\n (ctx.peerBridge === undefined ||\n (typeof ctx.peerBridge.hubCellId === \"string\" &&\n typeof ctx.peerBridge.hostTopicId === \"string\" &&\n typeof ctx.peerBridge.hostQueryId === \"string\" &&\n typeof ctx.peerBridge.canSpawnSubagents === \"boolean\"))\n );\n}\n\nexport function issueRuntimeMcpToken(ctx: RuntimeMcpContext): string {\n const payloadPart = encodeTokenPart({\n v: 1,\n exp: Date.now() + TOKEN_TTL_MS,\n ctx,\n } satisfies RuntimeTokenPayload);\n return `${payloadPart}.${signTokenPayload(payloadPart)}`;\n}\n\nexport function resolveRuntimeMcpToken(token: string | null): RuntimeMcpContext | null {\n if (!token) return null;\n const [payloadPart, signature, extra] = token.split(\".\");\n if (!payloadPart || !signature || extra !== undefined) return null;\n if (!safeEqual(signature, signTokenPayload(payloadPart))) return null;\n\n try {\n const payload = decodeTokenPart(payloadPart) as Partial<RuntimeTokenPayload>;\n if (payload.v !== 1 || typeof payload.exp !== \"number\" || payload.exp <= Date.now())\n return null;\n if (!isRuntimeMcpContext(payload.ctx)) return null;\n return payload.ctx;\n } catch {\n return null;\n }\n}\n\n/**\n * MCP server spec injected into an agent session's MCP config so the agent\n * connects back to this node's runtime endpoint with its per-turn token.\n */\nexport function buildRuntimeMcpSpec(\n agent: AgentKind,\n ctx: RuntimeMcpContext,\n): Record<string, unknown> {\n const token = issueRuntimeMcpToken(ctx);\n const base = `http://127.0.0.1:${runtimePort}${RUNTIME_MCP_BASE_PATH}`;\n const query = `token=${encodeURIComponent(token)}`;\n if (agent === \"codex\") return { url: `${base}/mcp?${query}` };\n return {\n type: \"sse\" as const,\n url: `${base}/sse?${query}`,\n timeout: CLAUDE_MCP_TOOL_TIMEOUT_MS,\n };\n}\n",
10
- "import { createHmac } from \"node:crypto\";\nimport { canonicalMcpBridgeEnv } from \"#mcp/canonical-bridge-config\";\nimport { buildRuntimeMcpSpec, RUNTIME_MCP_KEY } from \"#mcp/runtime-spec\";\nimport { peerSessionBridgeIpcEnv } from \"#mcp/session-comm/bridge-ipc-config\";\nimport {\n AGENT_HEALTH_SERVER,\n CANONICAL_MCP_PROXY_SERVER,\n FALLBACK_AGENT,\n PADDLEOCR_SERVER,\n resolveTopicWorkspaceDir,\n SESSION_COMM_SERVER,\n SYSTEM_HEALTH_SERVER,\n TASK_SERVER,\n TOKEN_STATS_SERVER,\n TSCONFIG_PATH,\n TSX_BIN,\n VAULT_SERVER,\n WIKI_SERVER,\n} from \"#platform/config\";\nimport { logger } from \"#platform/logger\";\nimport type { AgentKind, AgentQueryOptions, PeerRuntimeBridgeContext } from \"#types\";\n\n/**\n * Build the stdio transport spec for a Otium MCP server entry.\n *\n * claude/maestro launch the .ts server directly with `bun run` (fast, native\n * TypeScript + bun:sqlite). codex CANNOT — codex 0.135's rmcp stdio client\n * fails to handshake with bun-spawned servers (initialize is dropped/raced, so\n * no tools reach the model), while pure-node servers connect reliably. So for\n * the `codex` agent we launch the SAME server file via node + tsx, passing the\n * tsconfig explicitly (servers run with cwd ≠ PROJECT_ROOT, so tsx can't find\n * it on its own) so `@/*` path aliases resolve. Per-turn agent-aware config\n * means switching agents mid-topic just works: each turn re-spawns with the\n * right runtime.\n */\nexport function buildStdioMcpServer(\n agent: AgentKind | undefined,\n serverFile: string,\n serverArgs: string[],\n env?: Record<string, string>,\n): Record<string, unknown> {\n if (agent === \"codex\") {\n return {\n command: \"node\",\n args: [TSX_BIN, serverFile, ...serverArgs],\n // Merged onto codex's inherited env (not a replacement) — verified.\n env: { TSX_TSCONFIG_PATH: TSCONFIG_PATH, ...env },\n };\n }\n return {\n command: \"bun\",\n args: [\"run\", serverFile, ...serverArgs],\n ...(env ? { env } : {}),\n };\n}\n\n// --- Playwright unavailable notifier + per-turn state ---\n//\n// When the playwright manager fails to allocate a long-lived MCP port,\n// the catalog used to fall back to a per-turn stdio chromium that ran as\n// a child of the agent CLI subprocess — which meant Chromium was bound\n// to the agent's process tree and died on cascade-kill. We now skip the\n// browser entry entirely (the playwright entry is omitted from the\n// catalog for that turn) AND surface the gap two ways:\n//\n// 1. `notifyPlaywrightUnavailable` — fire-and-forget callback for the host\n// (telegram bot) to push an alert to the current topic. Throttled\n// per (userId, topic) with a 5-minute cooldown so a flaky\n// manager doesn't spam the chat. Per-process state — restart clears.\n//\n// 2. `consumePlaywrightUnavailable` — the system-prompt builder reads\n// this flag to add an explicit \"Playwright unavailable this turn\"\n// reminder to the agent's user message, so the model knows to\n// route around browser tools instead of hallucinating a call to a\n// tool that was silently removed from the schema list.\n\ntype PlaywrightUnavailableContext = {\n userId: string;\n topic: string | undefined;\n agent: AgentKind | undefined;\n};\n\ntype PlaywrightUnavailableNotifier = (ctx: PlaywrightUnavailableContext) => void;\n\nlet _playwrightUnavailableNotifier: PlaywrightUnavailableNotifier | undefined;\nconst _playwrightUnavailableLastNotifiedAt = new Map<string, number>();\nconst _PLAYWRIGHT_UNAVAILABLE_COOLDOWN_MS = 5 * 60_000;\n\nconst _playwrightUnavailableThisTurn = new Set<string>();\n\nfunction _playwrightUnavailableKey(userId: string, topic: string | undefined): string {\n return `${userId}:${topic ?? \"\"}`;\n}\n\n/**\n * Register the host's \"playwright unavailable\" alert sink. Called once at bot\n * startup. Idempotent — last writer wins.\n */\nexport function setPlaywrightUnavailableNotifier(cb: PlaywrightUnavailableNotifier): void {\n _playwrightUnavailableNotifier = cb;\n}\n\n/**\n * Mark the current turn as missing long-lived Playwright and notify the host.\n * The playwright catalog entry calls this when it is built without a port, but\n * route-level callers can call it earlier after ensurePlaywright fails so the\n * system prompt for the same turn can include the unavailable reminder.\n */\nexport function markPlaywrightUnavailable(ctx: PlaywrightUnavailableContext): void {\n _markPlaywrightUnavailable(ctx);\n}\n\nfunction _markPlaywrightUnavailable(ctx: PlaywrightUnavailableContext): void {\n // Mark unavailable for the next system-prompt build, regardless of\n // notifier presence (the model-side reminder must always fire so the\n // agent doesn't try to call a missing tool).\n _playwrightUnavailableThisTurn.add(_playwrightUnavailableKey(ctx.userId, ctx.topic));\n\n if (!_playwrightUnavailableNotifier) return;\n const key = _playwrightUnavailableKey(ctx.userId, ctx.topic);\n const now = Date.now();\n const last = _playwrightUnavailableLastNotifiedAt.get(key) ?? 0;\n if (now - last < _PLAYWRIGHT_UNAVAILABLE_COOLDOWN_MS) return;\n _playwrightUnavailableLastNotifiedAt.set(key, now);\n try {\n _playwrightUnavailableNotifier(ctx);\n } catch (err) {\n logger.warn({ err }, \"playwright unavailable notifier threw\");\n }\n}\n\n/**\n * Read + clear the \"playwright unavailable this turn\" flag for a\n * (user, group, topic). Used by the system-prompt builder right before\n * the agent query starts. Single consumer pattern — calling more than\n * once per turn returns `false` for the second caller (intended; the\n * reminder only needs to ride one prompt).\n */\nexport function consumePlaywrightUnavailable(userId: string, topic: string | undefined): boolean {\n const key = _playwrightUnavailableKey(userId, topic);\n if (!_playwrightUnavailableThisTurn.has(key)) return false;\n _playwrightUnavailableThisTurn.delete(key);\n return true;\n}\n\n/**\n * Single source of truth for MCP server registration.\n *\n * Each entry declares which scopes it participates in (`dm`, `forum`, `fork`, `cron`)\n * and how to build its spawn config given a context. Public helpers\n * (`getDmMcpServers`, `getForumMcpServers`, `getForkMcpServers`) and the\n * derived `ALL_FORUM_MCP_SERVER_NAMES` / `REQUIRED_FORUM_MCP_SERVERS`\n * constants all read from this catalog, so adding a new MCP server is a\n * one-line append here instead of touching three places.\n *\n * Conventions:\n * - `scopes` lists every scope the server should appear in by default.\n * - `forumRequired: true` keeps the server even when a forum topic\n * restricts the enabled list via `configure_mcp` (forum scope only).\n * - `build(ctx)` returns the raw transport config (Claude-SDK shape).\n * Codex callers funnel through `toCodexMcpServers` separately.\n *\n * Insertion order is preserved by `Object.entries`, which determines the\n * order of server names in user-facing displays.\n */\n\nexport type RuntimeMcpScope = \"dm\" | \"forum\" | \"fork\" | \"manager\" | \"cron\";\n\nexport interface RuntimeMcpBuildContext {\n userId: string;\n /** \"dm\" for DM scope, topic/session name for forum/fork. */\n session: string;\n /** REST/WS topic id when known. Prefer for authorization/scope checks. */\n topicId?: string;\n /** REST/WS query id when known. */\n queryId?: string;\n /** Topic id whose wiki memory should be read/written. */\n wikiTopicId?: string;\n agent?: AgentKind;\n cwd?: string;\n model?: string;\n currentUserPrompt?: string;\n depth?: number;\n playwrightPort?: number;\n playwrightCapability?: string;\n bgBashPort?: number;\n autoContinue?: boolean;\n visualTools?: boolean;\n silent?: boolean;\n peerBridge?: PeerRuntimeBridgeContext;\n}\n\nexport interface RuntimeMcpCatalogEntry {\n scopes: readonly RuntimeMcpScope[];\n /** Forum scope only: cannot be removed via the enabled whitelist. */\n forumRequired?: boolean;\n /**\n * Returns the raw transport spec (Claude-SDK shape), or `null` to\n * signal \"this server is unavailable for this turn — omit it from the\n * catalog entirely.\" Used by the playwright entry when the manager\n * cannot provide a long-lived port.\n */\n build(ctx: RuntimeMcpBuildContext): Record<string, unknown> | null;\n}\n\n// --- Playwright transport builders ---\n\nexport const CODEX_BROWSER_CAPABILITY_ENV = \"NEGOTIUM_BROWSER_CAPABILITY\";\n\nexport function browserOwnerCapability(capability: string, owner: string): string {\n return createHmac(\"sha256\", capability).update(owner).digest(\"hex\");\n}\n\nexport function browserOwnerForContext(ctx: {\n userId?: string;\n session?: string;\n topicId?: string;\n}): string | undefined {\n if (ctx.topicId) return `topic:${ctx.topicId}`;\n if (ctx.userId && ctx.session) return `user:${ctx.userId}:${ctx.session}`;\n return undefined;\n}\n\nfunction playwrightTransport(port: number, owner: string, capability: string, agent?: AgentKind) {\n const ownerCapability = browserOwnerCapability(capability, owner);\n if (agent === \"codex\") {\n return {\n url: `http://127.0.0.1:${port}/mcp`,\n http_headers: { \"X-Browser-Owner\": owner },\n env_http_headers: { \"X-Browser-Capability\": CODEX_BROWSER_CAPABILITY_ENV },\n };\n }\n if (agent === \"maestro\") {\n const query = new URLSearchParams({ owner, capability: ownerCapability });\n return {\n type: \"sse\" as const,\n url: `http://127.0.0.1:${port}/sse?${query}`,\n };\n }\n return {\n type: \"sse\" as const,\n url: `http://127.0.0.1:${port}/sse`,\n headers: { \"X-Browser-Owner\": owner, \"X-Browser-Capability\": ownerCapability },\n };\n}\n\nfunction longLivedHttpMcp(agent: AgentKind | undefined, port: number) {\n return agent === \"codex\"\n ? { url: `http://127.0.0.1:${port}/mcp` }\n : { type: \"sse\" as const, url: `http://127.0.0.1:${port}/sse` };\n}\n\n// --- Catalog ---\n\nconst MCP_CATALOG: Record<string, RuntimeMcpCatalogEntry> = {\n playwright: {\n scopes: [\"dm\", \"forum\", \"fork\", \"cron\"],\n build({ userId, session, topicId, playwrightPort, playwrightCapability, agent }) {\n // Codex uses streamable HTTP while Claude and Maestro use SSE. Both\n // transports terminate at the same long-lived browser/profile server.\n if (playwrightPort && playwrightCapability) {\n const owner = browserOwnerForContext({ userId, session, topicId });\n if (!owner) return null;\n return playwrightTransport(playwrightPort, owner, playwrightCapability, agent);\n }\n // No port available — the playwright manager could not allocate one\n // for this turn. The previous behavior was to fall back to a per-turn\n // stdio chromium, but that made Chromium a child of the agent CLI\n // process tree, so cascade-kill on agent exit took the browser down\n // with it (visible in pm2 as \"Chromium died with claude\"). We now\n // omit the playwright entry from this turn's catalog AND fire two\n // side-effects:\n // 1. notify the host so it can push an alert into the current\n // topic (rate-limited 5min per scope key);\n // 2. mark the (user, topic) as \"playwright unavailable\n // this turn\" so the system-prompt builder can tell the model\n // explicitly, instead of letting the model hallucinate a call\n // to a tool whose schema silently vanished.\n _markPlaywrightUnavailable({\n userId,\n topic: session,\n agent,\n });\n return null;\n },\n },\n [RUNTIME_MCP_KEY]: {\n scopes: [\"forum\", \"manager\", \"fork\", \"cron\"],\n forumRequired: true,\n build({\n userId,\n session,\n topicId,\n queryId,\n agent,\n cwd,\n model,\n currentUserPrompt,\n autoContinue,\n visualTools,\n peerBridge,\n }) {\n if (!topicId || !agent) return null;\n return buildRuntimeMcpSpec(agent, {\n userId,\n topicId,\n topicTitle: session,\n queryId,\n cwd: cwd ?? resolveTopicWorkspaceDir(topicId),\n agent,\n model,\n currentUserPrompt,\n autoContinue,\n visualTools,\n peerBridge,\n });\n },\n },\n paddleocr: {\n scopes: [\"dm\", \"forum\", \"fork\", \"cron\"],\n build({ agent }) {\n return buildStdioMcpServer(agent, PADDLEOCR_SERVER, []);\n },\n },\n \"token-stats\": {\n scopes: [\"dm\", \"forum\", \"manager\", \"cron\"],\n forumRequired: true,\n build({ userId, agent }) {\n return buildStdioMcpServer(agent, TOKEN_STATS_SERVER, [`--user-id=${userId}`]);\n },\n },\n // Otium-owned shared task system. This is the only authoritative task/todo\n // surface across claude/codex/maestro; provider-native task stores are\n // blocked or ignored because they do not survive agent switches.\n task: {\n scopes: [\"dm\", \"forum\", \"manager\", \"cron\"],\n forumRequired: true,\n build({ userId, session, topicId, queryId, agent, peerBridge }) {\n if (peerBridge) {\n if (!topicId || !queryId) return null;\n const env = canonicalMcpBridgeEnv({\n surface: \"task\",\n userId,\n topicId,\n queryId,\n peerBridge,\n });\n return env\n ? buildStdioMcpServer(agent, CANONICAL_MCP_PROXY_SERVER, [\"--surface=task\"], env)\n : null;\n }\n const args = [`--user-id=${userId}`, `--topic=${session}`];\n if (topicId) args.push(`--topic-id=${topicId}`);\n return buildStdioMcpServer(agent, TASK_SERVER, args);\n },\n },\n \"session-comm\": {\n // Exposed in `manager` scope as well so the General-topic manager agent\n // can wake fresh-created topics via tell_session/ask_session right after\n // create_topic. Without this, a newly-created topic would stay in the\n // \"fresh-start ready\" state until the user manually visits it.\n scopes: [\"forum\", \"fork\", \"manager\"],\n forumRequired: true,\n build({ userId, session, topicId, agent, depth = 0, silent, peerBridge }) {\n const effectiveAgent = agent ?? FALLBACK_AGENT;\n const args = [\n `--user-id=${userId}`,\n `--topic=${session}`,\n ...(topicId ? [`--topic-id=${topicId}`] : []),\n `--depth=${depth}`,\n `--agent=${effectiveAgent}`,\n ...(silent ? [\"--reply-only=true\"] : []),\n ...(peerBridge ? [`--peer-host-query-id=${peerBridge.hostQueryId}`] : []),\n ];\n return buildStdioMcpServer(\n effectiveAgent,\n SESSION_COMM_SERVER,\n args,\n peerBridge ? peerSessionBridgeIpcEnv() : undefined,\n );\n },\n },\n wiki: {\n scopes: [\"dm\", \"forum\", \"manager\", \"cron\"],\n forumRequired: true,\n build({ userId, session, topicId, queryId, wikiTopicId, agent, peerBridge }) {\n if (peerBridge) {\n if (!topicId || !queryId) return null;\n const env = canonicalMcpBridgeEnv({\n surface: \"wiki\",\n userId,\n topicId,\n queryId,\n peerBridge,\n });\n return env\n ? buildStdioMcpServer(agent, CANONICAL_MCP_PROXY_SERVER, [\"--surface=wiki\"], env)\n : null;\n }\n const args = [`--user-id=${userId}`];\n // Prefer the REST topic id so save_wiki_entry writes filenames and SQLite\n // briefs keyed the same way the topic wiki API reads them.\n const resolvedWikiTopicId =\n wikiTopicId ?? topicId ?? (session !== \"dm\" ? session : undefined);\n if (resolvedWikiTopicId) args.push(`--topic-id=${resolvedWikiTopicId}`);\n args.push(\"--surface=wiki\");\n return buildStdioMcpServer(agent, WIKI_SERVER, args);\n },\n },\n skills: {\n scopes: [\"dm\", \"forum\", \"manager\", \"cron\"],\n forumRequired: true,\n build({ userId, topicId, agent }) {\n const args = [`--user-id=${userId}`, \"--surface=skills\"];\n if (topicId) args.push(`--topic-id=${topicId}`);\n return buildStdioMcpServer(agent, WIKI_SERVER, args);\n },\n },\n \"system-health\": {\n scopes: [\"dm\", \"forum\", \"manager\", \"cron\"],\n forumRequired: true,\n build({ agent }) {\n return buildStdioMcpServer(agent, SYSTEM_HEALTH_SERVER, []);\n },\n },\n \"background-bash\": {\n scopes: [\"forum\"],\n build({ agent, bgBashPort }) {\n if (bgBashPort === undefined) return null;\n return longLivedHttpMcp(agent, bgBashPort);\n },\n },\n \"agent-health\": {\n scopes: [\"forum\", \"manager\", \"cron\"],\n forumRequired: true,\n build({ userId, agent }) {\n const args = [`--user-id=${userId}`];\n return buildStdioMcpServer(agent, AGENT_HEALTH_SERVER, args);\n },\n },\n vault: {\n scopes: [\"dm\", \"forum\", \"manager\", \"cron\"],\n // Credential references must never dead-end because a topic whitelist\n // omitted the broker while provider hooks correctly block raw expansion.\n forumRequired: true,\n build({ userId, agent }) {\n const args = [`--user-id=${userId}`];\n // Codex has no host-side PostToolUse redaction. Keep its Vault surface\n // broker-only and non-persistent: HTTPS responses are scrubbed before the\n // MCP result reaches Codex, while arbitrary shell could write a secret to\n // disk and reveal it through a later Read.\n if (agent === \"codex\") args.push(\"--http-only=true\");\n return buildStdioMcpServer(agent, VAULT_SERVER, args);\n },\n },\n};\n\n// --- Derived catalog views ---\n\nfunction namesInScope(scope: RuntimeMcpScope): string[] {\n return Object.entries(MCP_CATALOG)\n .filter(([, e]) => e.scopes.includes(scope))\n .map(([name]) => name);\n}\n\n/** All forum-eligible MCP server names, in display order. */\nconst allForumMcpServerNames: string[] = [];\nexport const ALL_FORUM_MCP_SERVER_NAMES: readonly string[] = allForumMcpServerNames;\n\n/** Forum servers that cannot be removed via the enabled whitelist. */\nconst requiredForumMcpServers: string[] = [];\nexport const REQUIRED_FORUM_MCP_SERVERS: readonly string[] = requiredForumMcpServers;\n\n/** Forum servers that can be toggled via the enabled whitelist (not required). */\nconst optionalForumMcpServers: string[] = [];\nexport const OPTIONAL_FORUM_MCP_SERVERS: readonly string[] = optionalForumMcpServers;\n\nfunction refreshForumCatalogViews(): void {\n const all = namesInScope(\"forum\");\n const required = Object.entries(MCP_CATALOG)\n .filter(([, entry]) => entry.scopes.includes(\"forum\") && entry.forumRequired)\n .map(([name]) => name);\n allForumMcpServerNames.splice(0, allForumMcpServerNames.length, ...all);\n requiredForumMcpServers.splice(0, requiredForumMcpServers.length, ...required);\n optionalForumMcpServers.splice(\n 0,\n optionalForumMcpServers.length,\n ...all.filter((name) => !required.includes(name)),\n );\n}\n\nrefreshForumCatalogViews();\n\n/**\n * Mount one MCP capability supplied by an optional node module.\n *\n * Registration happens once at node startup, never in the per-event hot path.\n * The returned cleanup closure only removes the exact entry installed by this\n * call, making module stop/restart safe.\n */\nexport function registerRuntimeMcpServer(name: string, entry: RuntimeMcpCatalogEntry): () => void {\n const key = name.trim();\n if (!key || !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(key)) {\n throw new Error(`invalid runtime MCP server name: ${name}`);\n }\n if (MCP_CATALOG[key]) throw new Error(`runtime MCP server already registered: ${key}`);\n MCP_CATALOG[key] = entry;\n refreshForumCatalogViews();\n return () => {\n if (MCP_CATALOG[key] !== entry) return;\n delete MCP_CATALOG[key];\n refreshForumCatalogViews();\n };\n}\n\n/**\n * Format the active MCP config for display (used by get_mcp_config /\n * get_topic_mcp / configure_mcp response).\n *\n * In whitelist mode the DB stores only the user-chosen optional servers;\n * required servers are always active but never written to the whitelist.\n * This helper surfaces that split so the model never confuses \"not in\n * whitelist\" with \"not active\".\n */\nexport function formatMcpStatus(config: {\n enabled: string[] | null;\n extra?: Record<string, unknown>;\n}): string[] {\n const extraNames = Object.keys(config.extra ?? {});\n\n if (config.enabled === null) {\n const total = ALL_FORUM_MCP_SERVER_NAMES.length + extraNames.length;\n return [\n `설정 방식: 기본값 (전체 활성)`,\n `활성 서버 (${total}개): ${[...ALL_FORUM_MCP_SERVER_NAMES, ...extraNames].join(\", \")}`,\n `추가 서버: ${extraNames.length > 0 ? extraNames.join(\", \") : \"없음\"}`,\n ];\n }\n\n // whitelist mode: stored list may or may not include required servers\n // (old entries might have them; new entries won't). Either way, split\n // by required vs optional for display.\n const optionalActive = config.enabled.filter((n) => !REQUIRED_FORUM_MCP_SERVERS.includes(n));\n const total = REQUIRED_FORUM_MCP_SERVERS.length + optionalActive.length + extraNames.length;\n return [\n `설정 방식: whitelist`,\n `필수 서버 (항상 활성, ${REQUIRED_FORUM_MCP_SERVERS.length}개): ${REQUIRED_FORUM_MCP_SERVERS.join(\", \")}`,\n `선택 서버 (whitelist, ${optionalActive.length}개): ${optionalActive.length > 0 ? optionalActive.join(\", \") : \"없음\"}`,\n `실제 활성 합계: ${total}개`,\n `추가 서버: ${extraNames.length > 0 ? extraNames.join(\", \") : \"없음\"}`,\n ``,\n `선택 가능 서버 전체 (${OPTIONAL_FORUM_MCP_SERVERS.length}개): ${OPTIONAL_FORUM_MCP_SERVERS.join(\", \")}`,\n ];\n}\n\n// --- Builders for each scope ---\n\n// ── Node-assigned MCP servers (mcp-host manifest) ───────────────────\n//\n// The per-node MCP manifest (`negotium mcp add`) lives in @negotium/mcp-host,\n// which depends on core — so core cannot read it directly. Instead the host\n// process resolves the manifest at node start (ensuring long-lived http\n// servers are running and have ports) and installs the result here. Entries\n// then ride every eligible scope's catalog, subject to the same per-topic\n// `enabled` whitelist as optional built-ins.\n\nexport type NodeMcpEntry =\n | { key: string; kind: \"http\"; port: number }\n | { key: string; kind: \"stdio\"; command: string; args?: string[]; env?: Record<string, string> };\n\nlet nodeMcpEntries: NodeMcpEntry[] = [];\n\n/** Install the node's assigned MCP servers. Last writer wins (host restart-safe). */\nexport function setNodeMcpServers(entries: NodeMcpEntry[]): void {\n nodeMcpEntries = entries.filter((entry) => !(entry.key in MCP_CATALOG));\n const dropped = entries.length - nodeMcpEntries.length;\n if (dropped > 0) {\n logger.warn({ dropped }, \"setNodeMcpServers: entries shadowing built-in catalog keys ignored\");\n }\n}\n\nexport function getNodeMcpServers(): readonly NodeMcpEntry[] {\n return nodeMcpEntries;\n}\n\nfunction buildNodeMcpSpecs(\n agent: AgentKind | undefined,\n filter: (name: string) => boolean,\n): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const entry of nodeMcpEntries) {\n if (!filter(entry.key)) continue;\n out[entry.key] =\n entry.kind === \"http\"\n ? longLivedHttpMcp(agent, entry.port)\n : {\n command: entry.command,\n args: entry.args ?? [],\n ...(entry.env ? { env: entry.env } : {}),\n };\n }\n return out;\n}\n\nfunction buildScope(\n scope: RuntimeMcpScope,\n ctx: RuntimeMcpBuildContext,\n filter: (name: string) => boolean = () => true,\n): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const [name, entry] of Object.entries(MCP_CATALOG)) {\n if (!entry.scopes.includes(scope)) continue;\n if (!filter(name)) continue;\n // `null` from build() means \"skip this server for this turn\" —\n // currently used by the playwright entry when no long-lived port\n // is available.\n const spec = entry.build(ctx);\n if (spec === null) continue;\n out[name] = spec;\n }\n // Node-assigned MCPs join every scope except cron (scheduled runs keep the\n // deliberately narrow built-in set).\n if (scope !== \"cron\") {\n Object.assign(out, buildNodeMcpSpecs(ctx.agent, filter));\n }\n return out;\n}\n\n/** DM session: catalog entries with `dm` scope, no whitelist. */\nexport function getDmMcpServers(opts: {\n userId: string;\n agent?: AgentKind;\n playwrightPort?: number;\n playwrightCapability?: string;\n}) {\n return buildScope(\"dm\", {\n userId: opts.userId,\n session: \"dm\",\n agent: opts.agent,\n playwrightPort: opts.playwrightPort,\n playwrightCapability: opts.playwrightCapability,\n });\n}\n\n/**\n * Manager session: lives in the caller's private General API topic. Owns topic CRUD,\n * invite/user admin, and cross-topic MCP toggling through `topic-admin`,\n * plus general utilities. Browser/OCR work belongs in dedicated topics, so\n * heavyweight Playwright/PaddleOCR tools are intentionally excluded here.\n * No whitelist — manager-scope catalog entries are loaded as-is.\n */\nexport function getManagerMcpServers(opts: {\n userId: string;\n session?: string;\n topicId?: string;\n queryId?: string;\n wikiTopicId?: string;\n agent?: AgentKind;\n cwd?: string;\n model?: string;\n currentUserPrompt?: string;\n playwrightPort?: number;\n playwrightCapability?: string;\n autoContinue?: boolean;\n visualTools?: boolean;\n}) {\n if (!opts.topicId) {\n throw new Error(\"getManagerMcpServers: private General topicId is required\");\n }\n const topicId = opts.topicId;\n return buildScope(\"manager\", {\n userId: opts.userId,\n session: opts.session ?? \"General\",\n topicId,\n queryId: opts.queryId,\n wikiTopicId: opts.wikiTopicId ?? topicId,\n agent: opts.agent,\n cwd: opts.cwd,\n model: opts.model,\n currentUserPrompt: opts.currentUserPrompt,\n playwrightPort: opts.playwrightPort,\n playwrightCapability: opts.playwrightCapability,\n autoContinue: opts.autoContinue,\n visualTools: opts.visualTools,\n });\n}\n\n/**\n * Forum session: catalog entries with `forum` scope.\n * - `enabled === null` → all forum servers.\n * - `enabled` is an array → whitelist; required servers are always included.\n * - `extra` is merged on top, allowing one-off injections per topic.\n */\nexport function getForumMcpServers(opts: {\n userId: string;\n session: string;\n topicId?: string;\n queryId?: string;\n wikiTopicId?: string;\n agent: AgentKind;\n cwd?: string;\n model?: string;\n currentUserPrompt?: string;\n playwrightPort?: number;\n playwrightCapability?: string;\n bgBashPort?: number;\n autoContinue?: boolean;\n visualTools?: boolean;\n depth?: number;\n enabled?: string[] | null;\n extra?: Record<string, unknown>;\n silent?: boolean;\n peerBridge?: PeerRuntimeBridgeContext;\n}) {\n const {\n userId,\n session,\n topicId,\n queryId,\n wikiTopicId,\n agent,\n cwd,\n model,\n currentUserPrompt,\n playwrightPort,\n playwrightCapability,\n depth = 0,\n enabled = null,\n extra = {},\n silent = false,\n bgBashPort,\n autoContinue,\n visualTools,\n peerBridge,\n } = opts;\n\n const filter = (name: string) => {\n if (silent && name === \"task\") return false;\n if (enabled === null) return true;\n return (\n enabled.includes(name) || (REQUIRED_FORUM_MCP_SERVERS as readonly string[]).includes(name)\n );\n };\n\n const base = buildScope(\n \"forum\",\n {\n userId,\n session,\n topicId,\n queryId,\n wikiTopicId,\n agent,\n cwd,\n model,\n currentUserPrompt,\n depth,\n playwrightPort,\n playwrightCapability,\n bgBashPort,\n autoContinue,\n visualTools,\n silent,\n peerBridge,\n },\n filter,\n );\n\n return { ...base, ...extra };\n}\n\n/**\n * Cron session: scheduled background run for a concrete API topic. Keep the\n * catalog narrower than forum scope: runtime delivery, topic memory/status,\n * OCR/vault utilities, and a caller-provided disposable Playwright port.\n */\nexport function getCronMcpServers(opts: {\n userId: string;\n session: string;\n topicId: string;\n queryId?: string;\n wikiTopicId?: string;\n agent: AgentKind;\n cwd?: string;\n model?: string;\n currentUserPrompt?: string;\n playwrightPort?: number;\n playwrightCapability?: string;\n visualTools?: boolean;\n}) {\n return buildScope(\"cron\", {\n userId: opts.userId,\n session: opts.session,\n topicId: opts.topicId,\n queryId: opts.queryId,\n wikiTopicId: opts.wikiTopicId ?? opts.topicId,\n agent: opts.agent,\n cwd: opts.cwd,\n model: opts.model,\n currentUserPrompt: opts.currentUserPrompt,\n playwrightPort: opts.playwrightPort,\n playwrightCapability: opts.playwrightCapability,\n autoContinue: false,\n visualTools: opts.visualTools,\n });\n}\n\n/**\n * Pick the right MCP server bundle for an agent query. DM/ephemeral sessions\n * get the DM bundle; forum sessions get the forum bundle with full options\n * forwarded. Returned shape is the Claude-SDK shape; Codex callers funnel it\n * through their own translator (`toCodexMcpServers`).\n */\nexport function getMcpServersForQuery(opts: AgentQueryOptions): Record<string, unknown> {\n if (opts.sessionType === \"cron\") {\n if (!opts.topicId) throw new Error(\"getMcpServersForQuery: cron sessionType requires topicId\");\n return getCronMcpServers({\n userId: opts.userId || \"default\",\n session: opts.session || \"cron\",\n topicId: opts.topicId,\n queryId: opts.queryId,\n wikiTopicId: opts.wikiTopicId,\n agent: opts.agent,\n cwd: opts.cwd,\n model: opts.model,\n currentUserPrompt: opts.prompt,\n playwrightPort: opts.playwrightPort,\n playwrightCapability: opts.playwrightCapability,\n visualTools: opts.visualTools,\n });\n }\n if (opts.sessionType === \"dm\" || opts.sessionType === \"ephemeral\") {\n return getDmMcpServers({\n userId: opts.userId || \"default\",\n agent: opts.agent,\n playwrightPort: opts.playwrightPort,\n playwrightCapability: opts.playwrightCapability,\n });\n }\n if (opts.sessionType === \"manager\") {\n return getManagerMcpServers({\n userId: opts.userId || \"default\",\n session: opts.session,\n topicId: opts.topicId,\n queryId: opts.queryId,\n wikiTopicId: opts.wikiTopicId,\n agent: opts.agent,\n cwd: opts.cwd,\n model: opts.model,\n currentUserPrompt: opts.prompt,\n playwrightPort: opts.playwrightPort,\n playwrightCapability: opts.playwrightCapability,\n autoContinue: opts.autoContinue,\n visualTools: opts.visualTools,\n });\n }\n return getForumMcpServers({\n userId: opts.userId || \"default\",\n session: opts.session || \"default\",\n topicId: opts.topicId,\n queryId: opts.queryId,\n wikiTopicId: opts.wikiTopicId,\n agent: opts.agent,\n cwd: opts.cwd,\n model: opts.model,\n currentUserPrompt: opts.prompt,\n playwrightPort: opts.playwrightPort,\n playwrightCapability: opts.playwrightCapability,\n bgBashPort: opts.bgBashPort,\n autoContinue: opts.autoContinue,\n visualTools: opts.visualTools,\n depth: opts.depth,\n enabled: opts.mcpEnabled,\n extra: opts.mcpExtra,\n silent: opts.silent,\n peerBridge: opts.peerBridge,\n });\n}\n",
11
- "export interface PeerSessionBridgeIpcConfig {\n url: string;\n token: string;\n}\n\nconst registrations: Array<{ id: symbol; config: PeerSessionBridgeIpcConfig }> = [];\n\nexport function registerPeerSessionBridgeIpcConfig(config: PeerSessionBridgeIpcConfig): () => void {\n const registration = { id: Symbol(\"peer-session-bridge-ipc\"), config: { ...config } };\n registrations.push(registration);\n let disposed = false;\n return () => {\n if (disposed) return;\n disposed = true;\n const index = registrations.findIndex((entry) => entry.id === registration.id);\n if (index >= 0) registrations.splice(index, 1);\n };\n}\n\nexport function peerSessionBridgeIpcEnv(): Record<string, string> | undefined {\n const active = registrations.at(-1)?.config;\n if (!active) return undefined;\n return {\n NEGOTIUM_PEER_SESSION_BRIDGE_URL: active.url,\n NEGOTIUM_PEER_SESSION_BRIDGE_TOKEN: active.token,\n };\n}\n",
12
- "import { AsyncLocalStorage } from \"node:async_hooks\";\nimport {\n referencesRuntimeSecretStorage as defaultReferencesRuntimeSecretStorage,\n shouldRedirectVaultTool as defaultShouldRedirectVaultTool,\n} from \"#agents/vault-tool-policy\";\nimport { CLAUDE_EXECUTABLE, codexAuthFilePath } from \"#platform/config\";\nimport { getMcpServersForQuery as defaultGetMcpServersForQuery } from \"#platform/mcp-config\";\nimport { redactVaultSecrets as defaultRedactVaultSecrets } from \"#storage/vault\";\nimport type { AgentQueryOptions } from \"#types\";\n\n/**\n * Host-owned services used by the provider execution layer.\n *\n * The default implementation preserves standalone Negotium behaviour. An\n * embedding host may replace these callbacks once during process bootstrap so\n * providers use that host's MCP catalog and device-local secret store without\n * importing any host-specific runtime code into Negotium.\n */\nexport interface AgentExecutionHost {\n getMcpServersForQuery(opts: AgentQueryOptions): Record<string, unknown>;\n redactVaultSecrets(userId: string, value: string): string;\n referencesRuntimeSecretStorage(value: unknown): boolean;\n shouldRedirectVaultTool(userId: string, toolName: string, input: unknown): boolean;\n claudeCodeExecutablePath(): string | undefined;\n codexAuthFilePath(): string;\n transformQueryOptions?(opts: AgentQueryOptions): AgentQueryOptions;\n}\n\nconst defaultHost: AgentExecutionHost = {\n getMcpServersForQuery: defaultGetMcpServersForQuery,\n redactVaultSecrets: defaultRedactVaultSecrets,\n referencesRuntimeSecretStorage: defaultReferencesRuntimeSecretStorage,\n shouldRedirectVaultTool: defaultShouldRedirectVaultTool,\n claudeCodeExecutablePath: () => CLAUDE_EXECUTABLE,\n codexAuthFilePath,\n};\n\nconst hostRegistrations: Array<{\n id: symbol;\n overrides: Partial<AgentExecutionHost>;\n}> = [];\n\nconst scopedHost = new AsyncLocalStorage<AgentExecutionHost>();\n\nfunction activeHost(): AgentExecutionHost {\n const scoped = scopedHost.getStore();\n if (scoped) return scoped;\n const host = { ...defaultHost };\n for (const registration of hostRegistrations) Object.assign(host, registration.overrides);\n return host;\n}\n\n/** Resolve call-local overrides against the currently configured process host. */\nexport function resolveAgentExecutionHost(\n overrides: Partial<AgentExecutionHost> = {},\n): AgentExecutionHost {\n return { ...activeHost(), ...overrides };\n}\n\n/** Run one async provider operation with an isolated call-local host. */\nexport function withAgentExecutionHost<T>(\n host: AgentExecutionHost,\n operation: () => Promise<T>,\n): Promise<T> {\n return scopedHost.run(host, operation);\n}\n\n/** Configure provider host services. Returns a disposer useful for tests. */\nexport function configureAgentExecutionHost(overrides: Partial<AgentExecutionHost>): () => void {\n const registration = { id: Symbol(\"agent-execution-host\"), overrides };\n hostRegistrations.push(registration);\n let disposed = false;\n return () => {\n if (disposed) return;\n disposed = true;\n const index = hostRegistrations.findIndex((entry) => entry.id === registration.id);\n if (index >= 0) hostRegistrations.splice(index, 1);\n };\n}\n\nexport function hostedMcpServers(opts: AgentQueryOptions): Record<string, unknown> {\n return activeHost().getMcpServersForQuery(opts);\n}\n\nexport function redactHostedSecrets(userId: string, value: string): string {\n return activeHost().redactVaultSecrets(userId, value);\n}\n\nexport function referencesHostedSecretStorage(value: unknown): boolean {\n return activeHost().referencesRuntimeSecretStorage(value);\n}\n\nexport function shouldRedirectHostedVaultTool(\n userId: string,\n toolName: string,\n input: unknown,\n): boolean {\n return activeHost().shouldRedirectVaultTool(userId, toolName, input);\n}\n\nexport function transformHostedQueryOptions(opts: AgentQueryOptions): AgentQueryOptions {\n return activeHost().transformQueryOptions?.(opts) ?? opts;\n}\n\nexport function hostedClaudeCodeExecutablePath(): string | undefined {\n return activeHost().claudeCodeExecutablePath();\n}\n\nexport function hostedCodexAuthFilePath(): string {\n return activeHost().codexAuthFilePath();\n}\n",
13
- "import { isSensitivePath } from \"#security/sensitive-path\";\nimport { valueReferencesVaultKey } from \"#storage/vault\";\n\nconst SENSITIVE_RUNTIME_NAMES = [\n \"vault.db\",\n \"vault-master-key\",\n \"runtime-mcp-secret\",\n \"sessions.db\",\n] as const;\n\nexport const VAULT_BROKER_REDIRECT_ERROR =\n \"Vault placeholders must be executed through mcp__vault__vault_run (shell/CLI) or mcp__vault__vault_http_request (HTTP) so secret values cannot enter the model transcript.\";\n\nexport function isVaultBrokerTool(toolName: string): boolean {\n return toolName.includes(\"vault_run\") || toolName.includes(\"vault_http_request\");\n}\n\nexport function referencesRuntimeSecretStorage(value: unknown): boolean {\n if (typeof value === \"string\") {\n const lower = value.toLowerCase();\n if (SENSITIVE_RUNTIME_NAMES.some((name) => lower.includes(name))) return true;\n return value.startsWith(\"/\") && isSensitivePath(value);\n }\n if (Array.isArray(value)) return value.some(referencesRuntimeSecretStorage);\n if (value && typeof value === \"object\") {\n return Object.values(value as Record<string, unknown>).some(referencesRuntimeSecretStorage);\n }\n return false;\n}\n\nexport function shouldRedirectVaultTool(userId: string, toolName: string, input: unknown): boolean {\n return !isVaultBrokerTool(toolName) && valueReferencesVaultKey(userId, input);\n}\n",
14
- "import { FILE_TAG_REGEX } from \"#platform/config\";\nimport type { UnifiedEvent } from \"#types\";\n\n/**\n * Yield `file` events for explicit [FILE:...] tags in `text`.\n * Shared between provider implementations (claude.ts, codex.ts, maestro) so the\n * fallback tag recognition rule stays in one place.\n */\nexport function* extractFileEvents(text: string, source: string): Generator<UnifiedEvent> {\n const tagRegex = new RegExp(FILE_TAG_REGEX.source, \"gi\");\n let match: RegExpExecArray | null = tagRegex.exec(text);\n while (match !== null) {\n yield { type: \"file\", path: match[1], source, origin: \"tag\" };\n match = tagRegex.exec(text);\n }\n}\n\n/** Absolute paths referenced by explicit `[FILE:/abs/path]` tags, deduped,\n * in order of first appearance. Channel adapters use this to send produced\n * files alongside the text. */\nexport function extractFileTagPaths(text: string): string[] {\n const seen = new Set<string>();\n for (const event of extractFileEvents(text, \"tag\")) {\n if (event.type === \"file\") seen.add(event.path);\n }\n return [...seen];\n}\n\n/** Remove `[FILE:...]` tags from outbound text — the files are delivered as\n * real attachments by the channel, so the raw tags are just noise. */\nexport function stripFileTags(text: string): string {\n return text.replace(new RegExp(FILE_TAG_REGEX.source, \"gi\"), \"\").trim();\n}\n",
15
- "/**\n * Stringify an unknown thrown value for logging or user-visible messages.\n * Default fallback is `String(e)`. Pass an explicit fallback (e.g. \"unknown\")\n * to override what non-Error throws turn into.\n */\nexport function errMsg(e: unknown, fallback?: string): string {\n if (e instanceof Error) return e.message;\n return fallback ?? String(e);\n}\n",
16
- "export const NEGOTIUM_VERSION = \"0.1.12\";\n",
17
- "import { spawn } from \"node:child_process\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport type {\n HookInput,\n Options,\n PostToolUseHookInput,\n PreToolUseHookInput,\n SDKAssistantMessage,\n SDKPartialAssistantMessage,\n SDKResultMessage,\n SDKSystemMessage,\n SDKTaskStartedMessage,\n SDKToolProgressMessage,\n SDKToolUseSummaryMessage,\n SDKUserMessage,\n SDKUserMessageReplay,\n} from \"@anthropic-ai/claude-agent-sdk\";\nimport { query } from \"@anthropic-ai/claude-agent-sdk\";\nimport type {\n ContentBlockParam,\n ImageBlockParam,\n} from \"@anthropic-ai/sdk/resources/messages/messages.mjs\";\nimport { claudeRegistry } from \"#agents/claude-registry\";\nimport { deepMapStrings } from \"#agents/deep-map\";\nimport {\n hostedClaudeCodeExecutablePath,\n hostedMcpServers,\n redactHostedSecrets,\n referencesHostedSecretStorage,\n shouldRedirectHostedVaultTool,\n} from \"#agents/execution-host\";\nimport { VAULT_BROKER_REDIRECT_ERROR } from \"#agents/vault-tool-policy\";\nimport { extractFileEvents } from \"#media/file-events\";\nimport { errMsg } from \"#platform/error\";\nimport { logger } from \"#platform/logger\";\nimport type { AgentInputAttachment, AgentQueryOptions, EffortLevel, UnifiedEvent } from \"#types\";\n\nconst CLAUDE_DEFAULT_DISALLOWED_TOOLS = [\n \"AskUserQuestion\",\n \"Workflow\",\n \"TodoWrite\",\n \"TaskCreate\",\n \"TaskUpdate\",\n \"TaskList\",\n \"TaskGet\",\n \"Task\",\n \"Agent\",\n \"TaskOutput\",\n \"TaskStop\",\n] as const;\n\nexport function buildClaudeDisallowedTools(\n extra: readonly string[] | undefined = undefined,\n): string[] {\n return [...new Set([...CLAUDE_DEFAULT_DISALLOWED_TOOLS, ...(extra ?? [])])];\n}\n\n/**\n * Narrow our shared `EffortLevel` to the subset claude-agent-sdk accepts.\n * Claude SDK rejects \"minimal\" (codex-only); we drop it silently rather than\n * coercing, matching our policy for unrecognized model strings.\n */\ntype ClaudeEffort = Exclude<EffortLevel, \"minimal\">;\nfunction toClaudeEffort(e: EffortLevel | undefined): ClaudeEffort | undefined {\n if (!e || !claudeRegistry.validateEffort(e)) return undefined;\n return e as ClaudeEffort;\n}\n\ntype ClaudeImageMimeType = \"image/jpeg\" | \"image/png\" | \"image/gif\" | \"image/webp\";\n\nconst CLAUDE_IMAGE_MAX_BYTES = 10 * 1024 * 1024;\nconst CLAUDE_IMAGE_MIME_TYPES = new Set<string>([\n \"image/jpeg\",\n \"image/png\",\n \"image/gif\",\n \"image/webp\",\n]);\n\nfunction isClaudeImageAttachment(\n attachment: AgentInputAttachment,\n): attachment is AgentInputAttachment & { mimeType: ClaudeImageMimeType } {\n return attachment.type === \"image\" && CLAUDE_IMAGE_MIME_TYPES.has(attachment.mimeType);\n}\n\nasync function* singleUserMessage(message: SDKUserMessage): AsyncGenerator<SDKUserMessage> {\n yield message;\n}\n\nfunction buildClaudePrompt(opts: AgentQueryOptions): string | AsyncIterable<SDKUserMessage> {\n const attachments = opts.attachments ?? [];\n if (attachments.length === 0) return opts.prompt;\n\n const imageBlocks: ImageBlockParam[] = [];\n for (const attachment of attachments) {\n if (!isClaudeImageAttachment(attachment)) continue;\n if (attachment.sizeBytes > CLAUDE_IMAGE_MAX_BYTES) {\n logger.info(\n {\n path: attachment.path,\n mimeType: attachment.mimeType,\n sizeBytes: attachment.sizeBytes,\n maxBytes: CLAUDE_IMAGE_MAX_BYTES,\n },\n \"claudeProvider: skipping oversized image attachment content block\",\n );\n continue;\n }\n\n try {\n imageBlocks.push({\n type: \"image\",\n source: {\n type: \"base64\",\n media_type: attachment.mimeType,\n data: readFileSync(attachment.path).toString(\"base64\"),\n },\n });\n } catch (err) {\n logger.warn(\n {\n path: attachment.path,\n mimeType: attachment.mimeType,\n err,\n },\n \"claudeProvider: failed to read image attachment for content block\",\n );\n }\n }\n\n if (imageBlocks.length === 0) return opts.prompt;\n\n const content: ContentBlockParam[] = [{ type: \"text\", text: opts.prompt }, ...imageBlocks];\n return singleUserMessage({\n type: \"user\",\n message: {\n role: \"user\",\n content,\n },\n parent_tool_use_id: null,\n });\n}\n\n// --- Stream event sub-types (from @anthropic-ai/sdk, not directly importable) ---\ninterface ContentBlockDelta {\n type: \"content_block_delta\";\n delta: { type: string; partial_json?: string; text?: string };\n}\ntype StreamEvent = ContentBlockDelta | { type: string };\n\n// --- Assistant message content block types (from BetaMessage.content) ---\ninterface TextBlock {\n type: \"text\";\n text: string;\n}\ninterface ToolUseBlock {\n type: \"tool_use\";\n id: string;\n name: string;\n input: Record<string, unknown>;\n}\ninterface ToolResultBlock {\n type: \"tool_result\";\n tool_use_id: string;\n content: string | unknown;\n}\ntype ContentBlock = TextBlock | ToolUseBlock | ToolResultBlock | { type: string };\n\n// --- Process tree kill on abort ---\n//\n// The Claude Agent SDK spawns a `claude` CLI subprocess, which in turn spawns\n// MCP servers (playwright-mcp, python OCR servers, …) which themselves spawn\n// browsers / interpreters. The SDK's default abort path only signals the\n// direct child, leaving grandchildren orphaned — over time they accumulate as\n// zombies, holding ports (Playwright DevTools 9222) and leaking memory\n// (Chrome ~hundreds of MB per orphan). Single-user Mac deployments notice\n// this within a day of repeated /abort.\n//\n// We override `spawnClaudeCodeProcess` to:\n// 1. spawn with `detached: true` → child becomes the leader of a new\n// process group with the same pgid as its pid;\n// 2. on abort, send the signal to `-pid` (the whole group) instead of the\n// single pid, so all transitive descendants receive it;\n// 3. escalate to SIGKILL after a 2.5s grace if SIGTERM didn't take.\n\ntype SpawnClaudeCodeProcess = NonNullable<Options[\"spawnClaudeCodeProcess\"]>;\ntype SpawnClaudeCodeOptions = Parameters<SpawnClaudeCodeProcess>[0];\ntype SpawnClaudeCodeResult = ReturnType<SpawnClaudeCodeProcess>;\n\nconst CLAUDE_ABORT_SIGKILL_DELAY_MS = 2500;\n\nfunction signalProcessTree(pid: number, signal: NodeJS.Signals): boolean {\n // Negative pid = \"signal every process in this process group\". Falls back\n // to single-pid signaling if the group call fails (e.g. on platforms where\n // `detached` didn't materialize a new group).\n try {\n process.kill(-pid, signal);\n return true;\n } catch (groupErr) {\n try {\n process.kill(pid, signal);\n return true;\n } catch (pidErr) {\n logger.debug({ groupErr, pidErr, pid, signal }, \"Failed to signal Claude process tree\");\n return false;\n }\n }\n}\n\nexport function spawnClaudeCodeProcessWithTreeKill(\n options: SpawnClaudeCodeOptions,\n): SpawnClaudeCodeResult {\n const child = spawn(options.command, options.args, {\n cwd: options.cwd,\n detached: true,\n env: options.env as NodeJS.ProcessEnv,\n stdio: [\"pipe\", \"pipe\", \"inherit\"],\n });\n if (!child.stdin || !child.stdout) {\n child.kill(\"SIGKILL\");\n throw new Error(\"Failed to spawn Claude Code process with piped stdin/stdout\");\n }\n\n let exited = false;\n let killTimer: NodeJS.Timeout | undefined;\n const clearKillTimer = () => {\n if (killTimer) clearTimeout(killTimer);\n killTimer = undefined;\n };\n\n const kill = (signal: NodeJS.Signals): boolean => {\n if (!child.pid) return child.kill(signal);\n const ok = signalProcessTree(child.pid, signal);\n if (signal !== \"SIGKILL\") {\n // Soft signal: schedule a SIGKILL fallback so a stuck process tree\n // can't survive abort indefinitely.\n clearKillTimer();\n killTimer = setTimeout(() => {\n if (!exited && child.pid) {\n logger.warn({ pid: child.pid }, \"Claude process tree still alive after SIGTERM; SIGKILL\");\n signalProcessTree(child.pid, \"SIGKILL\");\n }\n }, CLAUDE_ABORT_SIGKILL_DELAY_MS);\n killTimer.unref?.();\n }\n return ok;\n };\n\n const onAbort = () => {\n logger.warn({ pid: child.pid, command: options.command }, \"Aborting Claude Code process tree\");\n kill(\"SIGTERM\");\n };\n\n if (options.signal.aborted) onAbort();\n else options.signal.addEventListener(\"abort\", onAbort, { once: true });\n\n child.once(\"exit\", (code, signal) => {\n exited = true;\n clearKillTimer();\n options.signal.removeEventListener(\"abort\", onAbort);\n logger.debug({ pid: child.pid, code, signal }, \"Claude Code process exited\");\n });\n\n // Consume the child's 'error' event. Without a listener, a spawn-level error\n // propagates into the SDK's readline-over-stdout teardown and crashes the\n // whole process with \"this.input.pause is not a function\" (node:readline\n // close→pause on a stream that never initialized). Handling it here keeps the\n // failure local and surfaces a clean diagnostic.\n child.once(\"error\", (err) => {\n exited = true;\n clearKillTimer();\n options.signal.removeEventListener(\"abort\", onAbort);\n logger.error(\n {\n pid: child.pid,\n command: options.command,\n err: err instanceof Error ? err.message : String(err),\n },\n \"Claude Code process error event\",\n );\n });\n\n return {\n stdin: child.stdin,\n stdout: child.stdout,\n get killed() {\n return child.killed || exited;\n },\n get exitCode() {\n return child.exitCode;\n },\n kill,\n on(event, listener) {\n child.on(event, listener);\n },\n once(event, listener) {\n child.once(event, listener);\n },\n off(event, listener) {\n child.off(event, listener);\n },\n };\n}\n\n/**\n * Recognize the multiple shapes Node + WHATWG fetch use when a request is\n * cancelled via `AbortController`. Mirrors `isAbortError` in maestro/provider\n * — both files keep their own copy so neither has to import the other (the\n * agent providers are deliberately siblings, no shared error helpers).\n */\nfunction isAbortError(err: unknown): boolean {\n if (!err || typeof err !== \"object\") return false;\n const e = err as { name?: unknown; code?: unknown };\n if (e.name === \"AbortError\") return true;\n if (e.code === 20 || e.code === \"ABORT_ERR\") return true;\n return false;\n}\n\n/**\n * Core Claude provider.\n * Wraps the @anthropic-ai/claude-agent-sdk into a UnifiedEvent stream so any\n * caller can consume it identically to other providers such as codexProvider.\n * The dispatch entry point is `runAgent` in agents/index.ts.\n *\n * Failure handling: any throw escaping the SDK iteration (missing Claude CLI\n * binary, OAuth not configured, transient network) is caught and yielded as\n * a `{type:\"error\"}` UnifiedEvent so the dispatcher never sees a synthetic\n * crash and event-processor's `error` case classifies it with the right\n * provider name. Matches the graceful pattern maestroProvider already uses.\n * Abort signals are swallowed silently (the user moved on) so they don't\n * surface as ghost error messages.\n */\nexport async function* claudeProvider(opts: AgentQueryOptions): AsyncGenerator<UnifiedEvent> {\n const claudeExecutable = hostedClaudeCodeExecutablePath();\n // Up-front existence check — gives the user a clean, actionable error\n // instead of waiting for the SDK to spawn the binary and fail mid-stream\n // with an opaque ENOENT. The SDK's own resolution path runs after spawn,\n // so if CLAUDE_EXECUTABLE points nowhere we want to surface it now.\n if (claudeExecutable && !existsSync(claudeExecutable)) {\n yield {\n type: \"error\",\n content: `Claude CLI not found at ${claudeExecutable}. Install Claude Code or configure the executable path.`,\n };\n return;\n }\n\n const cleanEnv = { ...process.env };\n delete cleanEnv.NEGOTIUM_PEER_SESSION_BRIDGE_URL;\n delete cleanEnv.NEGOTIUM_PEER_SESSION_BRIDGE_TOKEN;\n delete cleanEnv.CLAUDECODE;\n cleanEnv.CLAUDE_CODE_STREAM_CLOSE_TIMEOUT ??= process.env.PADDLEOCR_TIMEOUT_MS ?? \"300000\";\n // Workflow is a feature flag, not a disallowedTools-addressable tool name.\n // The env var is the version-robust kill switch (works on any CLI the SDK\n // spawns); the `settings` flag layer below covers it a second time.\n cleanEnv.CLAUDE_CODE_DISABLE_WORKFLOWS = \"1\";\n\n const queryOptions: Options = {\n ...(claudeExecutable ? { pathToClaudeCodeExecutable: claudeExecutable } : {}),\n spawnClaudeCodeProcess: spawnClaudeCodeProcessWithTreeKill,\n cwd: opts.cwd,\n permissionMode: \"bypassPermissions\",\n allowDangerouslySkipPermissions: true,\n includePartialMessages: true,\n env: cleanEnv,\n mcpServers: hostedMcpServers(opts) as Options[\"mcpServers\"],\n abortController: opts.abortController,\n // `AskUserQuestion` is Claude Code's built-in clarification tool, but it\n // expects the SDK CLI to render a TUI prompt and read stdin for the\n // answer — neither exists in this headless Telegram bridge. Without\n // disallowing it, the model would call AskUserQuestion, the SDK would\n // wait for a TUI response that never comes, and the turn would hang\n // until abort. Forbidding the tool nudges the model to ask the same\n // clarification as plain text (see topic-system prompt), which routes\n // through the normal next-user-message path and the user just answers\n // in the topic.\n //\n // Claude Code's private task store, Workflow, and native subagent tools are\n // not Negotium state. They stay disabled even when a caller supplies custom\n // agent definitions: delegation must go through runtime.spawn_subagent and\n // task state must go through the required shared task MCP.\n disallowedTools: buildClaudeDisallowedTools(opts.disallowedTools),\n ...(opts.model ? { model: opts.model } : {}),\n ...(opts.maxBudgetUsd ? { maxBudgetUsd: opts.maxBudgetUsd } : {}),\n ...(opts.agents\n ? {\n agents: Object.fromEntries(\n Object.entries(opts.agents).map(([name, def]) => {\n const { effort, ...rest } = def;\n const narrowed = typeof effort === \"string\" ? toClaudeEffort(effort) : effort;\n return [name, narrowed !== undefined ? { ...rest, effort: narrowed } : rest];\n }),\n ),\n }\n : {}),\n ...(toClaudeEffort(opts.effort) ? { effort: toClaudeEffort(opts.effort) } : {}),\n hooks: {\n PreToolUse: [\n {\n hooks: [\n async (input: HookInput) => {\n const { tool_name, tool_input } = input as PreToolUseHookInput;\n if (referencesHostedSecretStorage(tool_input)) {\n return {\n hookSpecificOutput: {\n hookEventName: \"PreToolUse\" as const,\n permissionDecision: \"deny\" as const,\n permissionDecisionReason: \"Runtime secret storage access is not permitted\",\n },\n };\n }\n\n // Block built-in run_in_background: the bash runs inside the CLI\n // subprocess and dies when the turn ends (SIGTERM on IPC close).\n // Direct the model to the MCP tool that survives across turns and\n // auto-injects a completion notification via session-inbox.\n if (\n tool_name === \"Bash\" &&\n (tool_input as Record<string, unknown>)?.run_in_background === true\n ) {\n return {\n hookSpecificOutput: {\n hookEventName: \"PreToolUse\" as const,\n permissionDecision: \"deny\" as const,\n permissionDecisionReason:\n \"run_in_background is not supported in headless mode — the bash process dies when the agent turn ends. Use mcp__background-bash__background_bash_run instead: it survives across turns and automatically injects the result into the session when done.\",\n },\n };\n }\n\n // Detect real Vault placeholders but never inject plaintext into\n // provider-visible tool input. The Vault MCP broker expands them.\n const userId = opts.userId ?? \"\";\n if (!shouldRedirectHostedVaultTool(userId, tool_name, tool_input)) {\n return { continue: true };\n }\n return {\n hookSpecificOutput: {\n hookEventName: \"PreToolUse\" as const,\n permissionDecision: \"deny\" as const,\n permissionDecisionReason: VAULT_BROKER_REDIRECT_ERROR,\n },\n };\n },\n ],\n },\n ],\n PostToolUse: [\n {\n hooks: [\n async (input: HookInput) => {\n const { tool_response } = input as PostToolUseHookInput;\n const userId = opts.userId ?? \"\";\n const redacted = deepMapStrings(tool_response, (value) =>\n redactHostedSecrets(userId, value),\n );\n if (JSON.stringify(redacted) === JSON.stringify(tool_response)) {\n return { continue: true };\n }\n return {\n hookSpecificOutput: {\n hookEventName: \"PostToolUse\" as const,\n updatedToolOutput: redacted,\n },\n };\n },\n ],\n },\n ],\n },\n settingSources: [\"project\"] as Options[\"settingSources\"],\n // Disable the multi-agent Workflow feature: a headless backend query has\n // no business fanning out orchestration subagents, and the \"ultracode\"\n // keyword trigger would let user-authored message text opt into it.\n settings: {\n disableWorkflows: true,\n workflowKeywordTriggerEnabled: false,\n },\n systemPrompt: opts.systemPrompt,\n };\n\n if (opts.sessionId) {\n queryOptions.resume = opts.sessionId;\n }\n\n // Wrap the SDK iteration so init failures (missing claude CLI, OAuth not\n // configured, transient network errors before the first event) surface as\n // a normal error UnifiedEvent. Without this, an unconfigured Claude\n // install would crash the dispatcher with a synthetic exception and the\n // user-facing classifyError would still fire — but only via the handler\n // catch path, which means cleanup ordering differed from maestro/codex.\n // Keeping the failure shape consistent across providers simplifies the\n // upstream error code.\n // Thinking heartbeat: long extended-thinking stretches (minutes on fable /\n // high effort) emit no text or tool events, so the room UI goes silent and\n // the user can't tell whether the turn is still alive. The SDK does stream\n // thinking signals (`thinking_delta` content deltas, `system/thinking_tokens`\n // pings during redacted thinking) — digest them into a throttled\n // `tool_progress` heartbeat that the client already renders as a live status\n // chip (its handler also re-asserts the typing indicator).\n const THINKING_BEAT_MS = 5000;\n let thinkingStart: number | null = null;\n let lastThinkingBeat = 0;\n let lastContextTokens: number | undefined;\n let lastContextModel: string | undefined;\n const thinkingBeat = (): { type: \"tool_progress\"; toolName: string; elapsed: number } | null => {\n const now = Date.now();\n if (thinkingStart === null) {\n thinkingStart = now;\n lastThinkingBeat = now;\n return { type: \"tool_progress\", toolName: \"thinking\", elapsed: 0 };\n }\n if (now - lastThinkingBeat < THINKING_BEAT_MS) return null;\n lastThinkingBeat = now;\n return { type: \"tool_progress\", toolName: \"thinking\", elapsed: (now - thinkingStart) / 1000 };\n };\n\n try {\n const prompt = buildClaudePrompt(opts);\n for await (const message of query({\n prompt,\n options: queryOptions,\n })) {\n // --- Thinking heartbeat (see above) ---\n // A thinking \"stretch\" ends at the first non-thinking signal so elapsed\n // restarts cleanly on the next thinking phase within the same turn.\n if (\n message.type === \"system\" &&\n (message as { subtype?: string }).subtype === \"thinking_tokens\"\n ) {\n const beat = thinkingBeat();\n if (beat) yield beat;\n continue;\n }\n\n // --- Stream events (token-by-token) ---\n // tool_use is NOT emitted from the stream path: the completed assistant\n // message below carries the same block with its input already parsed,\n // and tools only start executing after the message completes — so the\n // stream copy added no timeliness, only a duplicate tool_use per turn\n // in the unified log (doubling `<!-- Tool: ... -->` comments when\n // bridging to another agent).\n if (message.type === \"stream_event\") {\n const streamMsg = message as SDKPartialAssistantMessage;\n const evt = (streamMsg as { event?: StreamEvent }).event;\n if (!evt) continue;\n\n if (evt.type === \"content_block_delta\") {\n const delta = evt as ContentBlockDelta;\n if (delta.delta.type === \"thinking_delta\") {\n const beat = thinkingBeat();\n if (beat) yield beat;\n } else if (delta.delta.type === \"text_delta\" && delta.delta.text) {\n // Claude only exposes tool_use blocks on the completed assistant\n // message below. Forwarding text deltas here would place all text\n // before those tools, making the original block order impossible\n // for consumers to reconstruct. The completed message emits text\n // and tool blocks in their canonical order.\n thinkingStart = null;\n } else {\n // Tool-args streaming (partial_json) etc. — thinking stretch over.\n thinkingStart = null;\n }\n }\n\n continue;\n }\n\n // Any completed message (assistant text, tool events, results) ends the\n // current thinking stretch.\n thinkingStart = null;\n\n // --- Tool progress ---\n if (message.type === \"tool_progress\") {\n const m = message as SDKToolProgressMessage;\n yield {\n type: \"tool_progress\",\n toolName: m.tool_name,\n elapsed: m.elapsed_time_seconds,\n };\n continue;\n }\n\n // --- Tool use summary ---\n if (message.type === \"tool_use_summary\") {\n const m = message as SDKToolUseSummaryMessage;\n yield { type: \"tool_use_summary\", summary: m.summary };\n continue;\n }\n\n // --- System init ---\n if (message.type === \"system\") {\n const m = message as SDKSystemMessage;\n if (m.subtype === \"init\") {\n yield { type: \"session\", sessionId: m.session_id };\n } else if (m.subtype === \"task_started\") {\n const t = m as unknown as SDKTaskStartedMessage;\n if (t.subagent_type && !t.skip_transcript) {\n const desc = t.description ? ` ${t.description.slice(0, 60)}` : \"\";\n yield { type: \"status\", content: `▶ [${t.subagent_type}]${desc}` };\n }\n } else {\n // Log all other system messages (task_updated, task_progress,\n // task_notification, etc.) so we can observe lifecycle events.\n logger.debug(\n { subtype: m.subtype, msg: m },\n \"claudeProvider: system message (unhandled subtype)\",\n );\n }\n continue;\n }\n\n // --- Result (terminal) ---\n // SDK occasionally yields stray messages after a `result`; consuming them\n // surfaces as ghost messages in the topic (\"어? 뭐가 더 나오네?\"). Close\n // the generator immediately on terminal so the SDK stream is dropped and\n // any trailing payloads can't leak through.\n if (message.type === \"result\") {\n const m = message as SDKResultMessage;\n if (m.subtype === \"success\") {\n const contextWindow =\n (lastContextModel ? m.modelUsage?.[lastContextModel]?.contextWindow : undefined) ??\n Object.values(m.modelUsage ?? {})[0]?.contextWindow;\n yield {\n type: \"result\",\n content: m.result,\n stopReason: m.stop_reason ?? \"end_turn\",\n usage: m.usage\n ? {\n inputTokens: m.usage.input_tokens,\n outputTokens: m.usage.output_tokens,\n cacheCreationInputTokens: m.usage.cache_creation_input_tokens ?? undefined,\n cacheReadInputTokens: m.usage.cache_read_input_tokens ?? undefined,\n costUsd: m.total_cost_usd,\n ...(lastContextTokens !== undefined && contextWindow\n ? { contextTokens: lastContextTokens, contextWindow }\n : {}),\n }\n : undefined,\n };\n yield* extractFileEvents(m.result, \"result\");\n return;\n }\n // Error result\n const budgetExceeded = m.subtype === \"error_max_budget_usd\";\n const errorMsg = budgetExceeded\n ? \"The job reached its cost limit\"\n : m.errors?.join(\"; \") || \"Unknown error\";\n yield {\n type: \"error\",\n content: errorMsg,\n ...(budgetExceeded ? { code: \"budget_exceeded\" as const } : {}),\n ...(m.usage\n ? {\n usage: {\n inputTokens: m.usage.input_tokens,\n outputTokens: m.usage.output_tokens,\n cacheCreationInputTokens: m.usage.cache_creation_input_tokens ?? undefined,\n cacheReadInputTokens: m.usage.cache_read_input_tokens ?? undefined,\n costUsd: m.total_cost_usd,\n },\n }\n : {}),\n };\n return;\n }\n\n // --- Assistant message ---\n if (message.type === \"assistant\") {\n const m = message as SDKAssistantMessage;\n const content = (m.message?.content ?? []) as ContentBlock[];\n const usage = m.message?.usage;\n if (usage) {\n lastContextTokens =\n (usage.input_tokens ?? 0) +\n (usage.cache_creation_input_tokens ?? 0) +\n (usage.cache_read_input_tokens ?? 0) +\n (usage.output_tokens ?? 0);\n lastContextModel = m.message.model;\n }\n\n for (const block of content) {\n if (block.type === \"text\") {\n const textBlock = block as TextBlock;\n yield { type: \"text\", content: textBlock.text };\n // Surface mid-turn [FILE:/abs/path] tags right away, matching codex/\n // maestro providers — without this, a model that narrates a file\n // before its next tool call (rather than emitting the tag in the\n // final `result` text) wouldn't trigger send-file at all. The file\n // event handler dedups on normalized path so the same tag appearing\n // again in `result` won't double-send.\n yield* extractFileEvents(textBlock.text, \"text\");\n } else if (block.type === \"tool_use\") {\n const tb = block as ToolUseBlock;\n yield {\n type: \"tool_use\",\n name: tb.name,\n input: tb.input || {},\n toolUseId: tb.id,\n };\n }\n }\n continue;\n }\n\n // --- User message (tool results ride on user-role messages) ---\n // The Anthropic message protocol puts tool_result blocks in USER\n // messages, never assistant ones — without this branch the unified log\n // records tool calls but no results, losing information codex topics\n // keep (visible when bridging a claude topic to another agent).\n if (message.type === \"user\") {\n const um = message as SDKUserMessage | SDKUserMessageReplay;\n // Replays re-deliver transcript history on resume; mapping them would\n // duplicate every past tool_result into the unified log.\n if (\"isReplay\" in um && um.isReplay) continue;\n const content = um.message?.content;\n if (!Array.isArray(content)) continue;\n for (const block of content as ContentBlock[]) {\n if (block.type !== \"tool_result\") continue;\n const trBlock = block as ToolResultBlock;\n const trContent =\n typeof trBlock.content === \"string\" ? trBlock.content.slice(0, 200) : \"\";\n yield {\n type: \"tool_result\",\n toolUseId: trBlock.tool_use_id || \"\",\n content: trContent,\n };\n }\n }\n }\n } catch (e) {\n // Abort = user moved on; don't surface as an error message. The handler\n // catches the abort signal separately via abortReason, so swallowing\n // here matches both maestro and codex behavior.\n if (isAbortError(e) || opts.abortController?.signal.aborted) return;\n logger.error({ err: e }, \"claudeProvider: SDK iteration failed\");\n yield { type: \"error\", content: errMsg(e) };\n }\n}\n",
18
- "/** Recursively apply fn to every string value in a nested object/array. */\nexport function deepMapStrings(value: unknown, fn: (s: string) => string): unknown {\n if (typeof value === \"string\") return fn(value);\n if (Array.isArray(value)) return value.map((v) => deepMapStrings(v, fn));\n if (value && typeof value === \"object\") {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) {\n out[k] = deepMapStrings(v, fn);\n }\n return out;\n }\n return value;\n}\n",
19
- "import { existsSync } from \"node:fs\";\nimport type {\n FileChangeItem,\n McpToolCallItem,\n ModelReasoningEffort,\n SandboxMode,\n ThreadOptions,\n} from \"@openai/codex-sdk\";\nimport { Codex } from \"@openai/codex-sdk\";\nimport {\n ensureCodexModelCache,\n writeCodexCatalogWithNativeMultiAgentDisabled,\n} from \"#agents/codex-native-multi-agent\";\nimport {\n acquireCodexSpawnLock,\n findNewCodexChildren,\n killCodexTrees,\n registerOwnedCodexPids,\n snapshotCodexChildren,\n unregisterOwnedCodexPids,\n} from \"#agents/codex-tree-kill\";\nimport { hostedCodexAuthFilePath, hostedMcpServers } from \"#agents/execution-host\";\nimport {\n migrateCodexRolloutNativeMultiAgentMetadata,\n readLatestCodexContextUsage,\n} from \"#agents/rollout/codex\";\nimport { extractFileEvents } from \"#media/file-events\";\nimport { errMsg } from \"#platform/error\";\nimport { logger } from \"#platform/logger\";\nimport {\n browserOwnerCapability,\n browserOwnerForContext,\n CODEX_BROWSER_CAPABILITY_ENV,\n} from \"#platform/mcp-config\";\nimport type { AgentQueryOptions, EffortLevel, UnifiedEvent } from \"#types\";\n\n/**\n * Pass Otium's EffortLevel through to Codex's ModelReasoningEffort.\n *\n * Storage validation (`getRegistry(\"codex\").validateEffort` in the repository\n * setters) guarantees that any effort persisted on a codex topic is one of\n * codex's accepted set (`low | medium | high | xhigh`), so the SDK shape and\n * the stored shape are identical for codex topics. A `max` or `minimal`\n * reaching this function means storage validation was bypassed — we throw\n * instead of silently demoting so the bug surfaces rather than masking itself.\n */\nfunction mapEffort(effort?: EffortLevel): ModelReasoningEffort | undefined {\n if (!effort) return undefined;\n if (effort === \"max\" || (effort as string) === \"minimal\") {\n throw new Error(\n `codexProvider received effort='${effort}', which codex does not support — storage validation was bypassed`,\n );\n }\n return effort as ModelReasoningEffort;\n}\n\n/**\n * Convert Otium's mcp-config output (Claude SDK shape) to Codex's\n * `config.mcp_servers` shape. Codex supports two transports:\n * - stdio: `{ command, args?, env? }`\n * - streamable HTTP: `{ url }` (verified via `codex mcp add --url`)\n *\n * Entries with the SSE transport shape (`{ type: \"sse\", url }`) are dropped:\n * codex doesn't speak SSE. Callers must produce the streamable HTTP shape\n * for codex by passing `agent: \"codex\"` into the `playwright.build()` arm\n * in `mcp-config.ts` (which switches `/sse` → `/mcp`).\n */\ntype CodexMcpTimeouts = {\n enabled?: boolean;\n startup_timeout_sec?: number;\n tool_timeout_sec?: number;\n};\ntype CodexStdioServer = {\n command: string;\n args?: string[];\n env?: Record<string, string>;\n} & CodexMcpTimeouts;\ntype CodexHttpServer = {\n url: string;\n http_headers?: Record<string, string>;\n env_http_headers?: Record<string, string>;\n} & CodexMcpTimeouts;\ntype CodexMcpServer = CodexStdioServer | CodexHttpServer;\n\nconst CODEX_MCP_SERVER_NAME_OVERRIDES: Record<string, string> = {\n // Codex merges per-turn `--config mcp_servers.<name>.*` overrides with the\n // user's global ~/.codex/config.toml. `playwright` is a common global stdio\n // server name, and adding Otium's per-topic HTTP `url` to that same table\n // makes Codex fail config parsing with \"url is not supported for stdio\".\n playwright: \"otium_playwright\",\n};\n\nfunction codexMcpServerName(name: string): string {\n return CODEX_MCP_SERVER_NAME_OVERRIDES[name] ?? name;\n}\n\nfunction parsePositiveInt(value: string | undefined, fallback: number): number {\n if (!value) return fallback;\n const parsed = Number.parseInt(value, 10);\n return Number.isInteger(parsed) && parsed > 0 ? parsed : fallback;\n}\n\nfunction withCodexMcpServerOverrides(name: string, server: CodexMcpServer): CodexMcpServer {\n if (name === \"paddleocr\") {\n return {\n ...server,\n startup_timeout_sec: parsePositiveInt(process.env.PADDLEOCR_MCP_STARTUP_TIMEOUT_SEC, 30),\n tool_timeout_sec: parsePositiveInt(process.env.PADDLEOCR_MCP_TOOL_TIMEOUT_SEC, 300),\n };\n }\n // For codex, Otium launches MCP servers via node + tsx (see serverLaunch in\n // mcp-config.ts), which transpiles the .ts on the fly — cold start is slower\n // than `bun run`, so give the handshake a generous startup window. codex's\n // default startup timeout is short enough that a heavier server can miss it.\n return {\n startup_timeout_sec: parsePositiveInt(process.env.CODEX_MCP_STARTUP_TIMEOUT_SEC, 30),\n ...server,\n };\n}\n\nexport function toCodexMcpServers(\n claudeShape: Record<string, unknown>,\n): Record<string, CodexMcpServer> {\n // Codex merges turn config with ~/.codex/config.toml instead of replacing it.\n // Disable common global browser stdio servers so browser state can only flow\n // through Negotium's long-lived, owner-scoped HTTP server.\n const disabledBrowserStdio = (): CodexStdioServer => ({\n command: process.execPath,\n args: [\"-e\", \"process.exit(0)\"],\n enabled: false,\n });\n const out: Record<string, CodexMcpServer> = {\n playwright: disabledBrowserStdio(),\n \"browser-rs\": disabledBrowserStdio(),\n patchright: disabledBrowserStdio(),\n };\n for (const [name, srv] of Object.entries(claudeShape)) {\n if (!srv || typeof srv !== \"object\") continue;\n const s = srv as Record<string, unknown>;\n const codexName = codexMcpServerName(name);\n if (typeof s.command === \"string\") {\n out[codexName] = withCodexMcpServerOverrides(name, {\n command: s.command,\n ...(Array.isArray(s.args) ? { args: s.args as string[] } : {}),\n ...(s.env && typeof s.env === \"object\" ? { env: s.env as Record<string, string> } : {}),\n });\n continue;\n }\n if (typeof s.url === \"string\" && s.type !== \"sse\") {\n out[codexName] = withCodexMcpServerOverrides(name, {\n url: s.url,\n ...(s.http_headers && typeof s.http_headers === \"object\"\n ? { http_headers: s.http_headers as Record<string, string> }\n : {}),\n ...(s.env_http_headers && typeof s.env_http_headers === \"object\"\n ? { env_http_headers: s.env_http_headers as Record<string, string> }\n : {}),\n });\n }\n }\n return out;\n}\n\nfunction isMissingCodexRolloutError(err: unknown): boolean {\n const msg = errMsg(err);\n return /no rollout found|thread\\/resume failed/i.test(msg);\n}\n\n/**\n * Render an `mcp_tool_call` item's terminal payload into a short string for\n * the unified `tool_result` event. The SDK shape is\n * `result?: { content: ContentBlock[]; structured_content: unknown }` on\n * success, or `error?: { message: string }` on failure — neither is a raw\n * string, which is why the previous `typeof result === \"string\"` branch was\n * unreachable. Truncate to 200 chars to match command_execution behavior.\n */\nfunction summarizeMcpToolCallResult(item: McpToolCallItem): string {\n if (item.error) return item.error.message.slice(0, 200);\n if (!item.result) return \"\";\n const blocks = Array.isArray(item.result.content) ? item.result.content : [];\n const text = blocks\n .map((b) => {\n if (b && typeof b === \"object\" && \"type\" in b && b.type === \"text\" && \"text\" in b) {\n return String((b as { text?: unknown }).text ?? \"\");\n }\n return \"\";\n })\n .filter(Boolean)\n .join(\"\\n\");\n if (text) return text.slice(0, 200);\n // Fall back to a JSON dump of structured_content for non-text content blocks.\n return JSON.stringify(item.result.structured_content ?? \"\").slice(0, 200);\n}\n\nfunction fileChangeEvents(item: FileChangeItem): UnifiedEvent[] {\n return item.changes.flatMap((change, index) => {\n const name = change.kind === \"add\" ? \"Write\" : change.kind === \"delete\" ? \"Delete\" : \"Edit\";\n const toolUseId = `${item.id}:${index}`;\n const success = item.status === \"completed\";\n return [\n {\n type: \"tool_use\" as const,\n name,\n input: { file_path: change.path, change_kind: change.kind },\n toolUseId,\n },\n {\n type: \"tool_result\" as const,\n toolUseId,\n content: success\n ? `${change.kind} applied: ${change.path}`\n : `${change.kind} failed: ${change.path}`,\n },\n ];\n });\n}\n\nfunction promptForThread(opts: AgentQueryOptions, includeSystemPrompt: boolean): string {\n return includeSystemPrompt && opts.systemPrompt\n ? `[System Instructions]\\n${opts.systemPrompt}\\n\\n${opts.prompt}`\n : opts.prompt;\n}\n\n/**\n * Start a streamed turn and identify the codex PIDs we spawned, holding the\n * global spawn lock across the full window from baseline → first event.\n *\n * Why hold the lock across iteration: `@openai/codex-sdk`'s `runStreamed()`\n * returns a lazy async generator object. The actual `child_process.spawn()`\n * call happens on the first `iterator.next()`, not when `runStreamed()` is\n * awaited (see `node_modules/@openai/codex-sdk/dist/index.js:51-93,238`).\n * If we released the lock after `await runStreamed(...)`, a concurrent\n * codex caller's baseline would race against our actual spawn and one\n * caller would mis-attribute the other's PID.\n *\n * Returns the iterator (positioned just past the first event) plus the\n * first event itself, so the streaming loop can re-emit it before\n * resuming `iterator.next()`.\n */\ntype StartResult = {\n iter: AsyncIterator<unknown>;\n firstEvent: unknown;\n done: boolean;\n};\n\nasync function closeIterator(iter: AsyncIterator<unknown>): Promise<void> {\n try {\n await iter.return?.();\n } catch (err) {\n logger.warn({ err }, \"codexProvider: failed to close codex event iterator\");\n }\n}\n\n/**\n * Bound the spawn→first-event window. `thread.started` normally arrives within\n * a few seconds, so if NOTHING comes back in this window the codex turn is\n * genuinely stuck at startup (the bare-`/codex` hang symptom). We surface a\n * clear error fast instead of waiting out the much longer mid-stream heartbeat\n * (8 min) — a stuck startup never recovers, and retrying it is futile. Once the\n * first event arrives, the normal heartbeat governs long-running work.\n */\nconst CODEX_STARTUP_TIMEOUT_MS = 90_000;\n\nasync function startStreamedWithTracking(\n thread: ReturnType<Codex[\"startThread\"]>,\n prompt: string,\n abortSignal: AbortSignal | undefined,\n trackedPids: { pids: number[] },\n): Promise<StartResult> {\n const release = await acquireCodexSpawnLock();\n try {\n const baseline = snapshotCodexChildren();\n const runResult = await thread.runStreamed(prompt, {\n ...(abortSignal ? { signal: abortSignal } : {}),\n });\n const iter = (runResult.events as AsyncIterable<unknown>)[Symbol.asyncIterator]();\n // Force the first iterator step — this is when the SDK actually\n // child_process.spawn()s codex. After this awaits, the codex PID is\n // visible to pgrep as a child of our process.\n let first: IteratorResult<unknown>;\n // Startup watchdog: race the first event against CODEX_STARTUP_TIMEOUT_MS so\n // a codex that spawns but never emits anything can't hang the turn. On\n // timeout the iter.next() promise loses the race and we fall into the catch\n // below, which kills the spawned tree, closes the iterator, and rethrows the\n // clear error — surfaced to the user as an `error` event (no infinite wait).\n let startupTimer: ReturnType<typeof setTimeout> | undefined;\n try {\n const startupTimeout = new Promise<never>((_, reject) => {\n startupTimer = setTimeout(\n () =>\n reject(\n new Error(\n `Codex가 ${CODEX_STARTUP_TIMEOUT_MS / 1000}초 내 응답을 시작하지 않아 중단했습니다. 다시 시도해주세요.`,\n ),\n ),\n CODEX_STARTUP_TIMEOUT_MS,\n );\n });\n // Swallow a late rejection from the losing promise: if the startup\n // timeout wins the race, this dangling next() may settle later with\n // nobody awaiting it (would surface as an unhandledRejection).\n const nextP = iter.next();\n nextP.catch(() => {});\n first = await Promise.race([nextP, startupTimeout]);\n } catch (err) {\n // Abort OR startup-timeout after the SDK spawned codex but before the\n // first event resolves: the normal abort listener still sees no tracked\n // PID, so diff the baseline here and kill anything attributable before\n // propagating.\n const novel = findNewCodexChildren(baseline);\n if (novel.length > 0) {\n killCodexTrees(novel);\n }\n await closeIterator(iter);\n throw err;\n } finally {\n if (startupTimer) clearTimeout(startupTimer);\n }\n const novel = findNewCodexChildren(baseline);\n trackedPids.pids = novel;\n registerOwnedCodexPids(novel);\n return { iter, firstEvent: first.value, done: !!first.done };\n } finally {\n release();\n }\n}\n\n/**\n * Wrap an iterator into an AsyncIterable that first yields a pre-captured\n * `firstEvent` and then drains the underlying iterator. Lets the streaming\n * `for await` loop keep its existing switch over events without special-casing\n * the first iteration we already consumed during PID tracking.\n */\nfunction prependFirstEvent(\n iter: AsyncIterator<unknown>,\n firstEvent: unknown,\n alreadyDone: boolean,\n): AsyncIterable<unknown> {\n return {\n [Symbol.asyncIterator]() {\n let emittedFirst = false;\n let exhausted = alreadyDone;\n return {\n async next(): Promise<IteratorResult<unknown>> {\n if (!emittedFirst) {\n emittedFirst = true;\n if (alreadyDone) return { value: undefined, done: true };\n return { value: firstEvent, done: false };\n }\n if (exhausted) return { value: undefined, done: true };\n const r = await iter.next();\n if (r.done) exhausted = true;\n return r;\n },\n async return(value?: unknown): Promise<IteratorResult<unknown>> {\n exhausted = true;\n if (iter.return) return iter.return(value);\n return { value, done: true };\n },\n };\n },\n };\n}\n\n/**\n * Core Codex provider.\n * Same UnifiedEvent contract as claudeProvider. Uses @openai/codex-sdk.\n *\n * Notes:\n * - Codex has no `systemPrompt` option; prepend the current topic/system\n * instructions on every invocation, including resumed synthetic threads.\n * - Per-turn MCP isolation is achieved via CodexOptions.config.mcp_servers,\n * so the global ~/.codex/config.toml stays untouched.\n * - Streaming token-by-token text deltas are not exposed by the SDK; only\n * final agent_message and per-item updates. Callers that rely on\n * text_delta should still work because we yield a single text/result\n * event when the assistant message completes.\n */\nexport async function* codexProvider(opts: AgentQueryOptions): AsyncGenerator<UnifiedEvent> {\n // Up-front auth file check — gives the user an actionable message\n // (\"`codex login` 으로 다시 로그인해주세요\") immediately instead of waiting\n // for the @openai/codex-sdk to spawn the codex binary and surface an\n // opaque OAuth failure on the first turn. Path is the default codex\n // location unless NEGOTIUM_CODEX_AUTH_FILE relocates it for this host.\n const codexAuthPath = hostedCodexAuthFilePath();\n if (!existsSync(codexAuthPath)) {\n yield {\n type: \"error\",\n content: `Codex auth file not found at ${codexAuthPath}. Run \\`codex login\\` to authenticate.`,\n };\n return;\n }\n\n let codexModelCatalogPath: string;\n try {\n await ensureCodexModelCache(codexAuthPath);\n codexModelCatalogPath = writeCodexCatalogWithNativeMultiAgentDisabled(codexAuthPath);\n if (opts.sessionId) migrateCodexRolloutNativeMultiAgentMetadata(opts.sessionId);\n } catch (err) {\n yield {\n type: \"error\",\n content: `Failed to enforce the Codex native multi-agent policy: ${errMsg(err)}`,\n };\n return;\n }\n\n const codexMcpServers = toCodexMcpServers(hostedMcpServers(opts));\n const browserOwner = browserOwnerForContext(opts);\n const scopedBrowserCapability =\n opts.playwrightCapability && browserOwner\n ? browserOwnerCapability(opts.playwrightCapability, browserOwner)\n : undefined;\n\n // Startup trace: codexProvider was otherwise silent until its first error or\n // heartbeat (8 min), so a stuck turn left \"0 lines of codex\" in the logs and\n // was impossible to localize (bug B). Record the resolved model/effort/cwd +\n // whether this is a fresh thread or a resume, so a future hang is pinpointed\n // to setup vs. the first stream step.\n logger.info(\n {\n model: opts.model ?? \"(sdk default)\",\n effort: opts.effort ?? \"(off)\",\n cwd: opts.cwd,\n cwdExists: existsSync(opts.cwd),\n resume: Boolean(opts.sessionId),\n mcpServerCount: Object.keys(codexMcpServers).length,\n },\n \"codexProvider: starting turn\",\n );\n\n const codex = new Codex({\n ...(scopedBrowserCapability\n ? {\n env: {\n ...Object.fromEntries(\n Object.entries(process.env).filter(\n (entry): entry is [string, string] => typeof entry[1] === \"string\",\n ),\n ),\n [CODEX_BROWSER_CAPABILITY_ENV]: scopedBrowserCapability,\n },\n }\n : {}),\n config: {\n // Otium exposes delegation through runtime.spawn_subagent so child work\n // gets its own room/card and its result is routed back to the parent.\n // Codex enables its provider-native collaboration tools from the user's\n // global config by default; explicitly turn that feature off so tools\n // such as spawn_agent/send_message cannot bypass Otium's orchestration\n // and so subagent rooms cannot recursively fan out through Codex.\n // Codex 0.144 lets model metadata override these flags. The authoritative\n // catalog above sets multi_agent_version=disabled as the hard stop; keep\n // all feature switches off as a second layer and for future CLI versions.\n features: { multi_agent: false, multi_agent_v2: false, enable_fanout: false },\n model_catalog_json: codexModelCatalogPath,\n mcp_servers: codexMcpServers,\n },\n });\n\n const threadOptions: ThreadOptions = {\n workingDirectory: opts.cwd,\n skipGitRepoCheck: true,\n // Codex sandbox is intentionally disabled: Otium already assigns a managed\n // workspace cwd for the turn, and the bot is expected to act on it freely on\n // the user's behalf. SDK-level sandboxing would only constrain reach inside\n // that already-owned directory, which is not the threat model.\n sandboxMode: \"danger-full-access\" as SandboxMode,\n approvalPolicy: \"never\",\n ...(opts.model ? { model: opts.model } : {}),\n ...(opts.effort ? { modelReasoningEffort: mapEffort(opts.effort) } : {}),\n };\n\n let currentSessionId = opts.sessionId;\n\n // Codex SDK has no systemPrompt option. A resumed thread may have been\n // synthesized from a captured shell, so always refresh the current runtime\n // instructions instead of trusting historical developer/environment data.\n let thread = currentSessionId\n ? codex.resumeThread(currentSessionId, threadOptions)\n : codex.startThread(threadOptions);\n let prompt = promptForThread(opts, true);\n\n let agentTextSoFar = \"\";\n let currentAgentMessageId: string | undefined;\n let finalText = \"\";\n let stopReason = \"end_turn\";\n\n // Tree-kill instrumentation. The codex SDK spawns the `codex` binary as a\n // direct child of our process but does not expose the PID or place it in\n // its own process group. We identify our PIDs by diffing pgrep snapshots\n // around the SDK's first iterator step (when codex is actually spawned),\n // and SIGTERM the whole tree on abort with SIGKILL fallback inside\n // killCodexTrees().\n const trackedPids: { pids: number[] } = { pids: [] };\n const abortSignal = opts.abortController?.signal;\n const onAbortKill = () => {\n if (trackedPids.pids.length > 0) {\n killCodexTrees(trackedPids.pids);\n }\n };\n abortSignal?.addEventListener(\"abort\", onAbortKill, { once: true });\n\n // Heartbeat: if the Codex API emits no events within the window, abort the\n // current stream and resume the thread with a short continuation prompt.\n // The interval doubles each attempt (up to HEARTBEAT_MAX_MS) to avoid\n // interrupting genuinely long-running work on the first timeout.\n let heartbeatMs = 8 * 60 * 1000;\n let heartbeatAttempts = 0;\n const HEARTBEAT_MAX_MS = 16 * 60 * 1000;\n const HEARTBEAT_MAX_ATTEMPTS = 2;\n const HEARTBEAT_CONTINUATION = \"계속 진행해줘.\";\n\n try {\n while (true) {\n if (abortSignal?.aborted) return;\n\n // Per-attempt abort controller: lets the heartbeat timer abort only\n // this attempt's stream without touching the user-facing outer signal.\n const attemptAbort = new AbortController();\n const propagateOuter = () => attemptAbort.abort();\n abortSignal?.addEventListener(\"abort\", propagateOuter, { once: true });\n\n trackedPids.pids = [];\n let heartbeatTriggered = false;\n let attemptCompleted = false;\n let heartbeatTimer: ReturnType<typeof setTimeout> | null = null;\n\n const scheduleHeartbeat = () => {\n if (heartbeatTimer !== null) clearTimeout(heartbeatTimer);\n if (abortSignal?.aborted || attemptAbort.signal.aborted) return;\n heartbeatTimer = setTimeout(() => {\n heartbeatTriggered = true;\n if (trackedPids.pids.length > 0) killCodexTrees(trackedPids.pids);\n attemptAbort.abort();\n }, heartbeatMs);\n };\n\n try {\n scheduleHeartbeat();\n\n let startResult!: StartResult;\n try {\n startResult = await startStreamedWithTracking(\n thread,\n prompt,\n attemptAbort.signal,\n trackedPids,\n );\n } catch (err) {\n if (err instanceof Error && err.name === \"AbortError\") throw err;\n if (!currentSessionId || !isMissingCodexRolloutError(err)) throw err;\n logger.warn(\n { staleSessionId: currentSessionId, err: errMsg(err) },\n \"codexProvider: stale/missing rollout, restarting fresh thread\",\n );\n thread = codex.startThread(threadOptions);\n prompt = promptForThread(opts, true);\n currentSessionId = undefined;\n startResult = await startStreamedWithTracking(\n thread,\n prompt,\n attemptAbort.signal,\n trackedPids,\n );\n }\n\n // Cover the narrow window where abort fired between PID registration\n // and the abort listener actually running.\n if (attemptAbort.signal.aborted) {\n killCodexTrees(trackedPids.pids);\n await closeIterator(startResult.iter);\n throw Object.assign(new Error(\"heartbeat abort\"), { name: \"AbortError\" });\n }\n\n const eventStream = prependFirstEvent(\n startResult.iter,\n startResult.firstEvent,\n startResult.done,\n );\n\n for await (const rawEvent of eventStream) {\n scheduleHeartbeat();\n\n const event = rawEvent as {\n type: string;\n thread_id?: string;\n item?: {\n type: string;\n command?: string;\n tool?: string;\n arguments?: unknown;\n text?: string;\n id?: string;\n aggregated_output?: string;\n message?: string;\n };\n usage?: {\n input_tokens: number;\n output_tokens: number;\n cached_input_tokens?: number;\n };\n error?: { message?: string };\n };\n\n switch (event.type) {\n case \"thread.started\": {\n if (event.thread_id) {\n currentSessionId = event.thread_id;\n yield { type: \"session\", sessionId: event.thread_id };\n }\n break;\n }\n\n case \"item.started\": {\n const item = event.item;\n if (!item) break;\n if (item.type === \"command_execution\") {\n yield {\n type: \"tool_use\",\n name: \"Bash\",\n input: { command: String(item.command ?? \"\") },\n toolUseId: String(item.id ?? \"\"),\n };\n } else if (item.type === \"mcp_tool_call\") {\n yield {\n type: \"tool_use\",\n name: String(item.tool ?? \"unknown\"),\n input:\n item.arguments && typeof item.arguments === \"object\"\n ? (item.arguments as Record<string, unknown>)\n : {},\n toolUseId: String(item.id ?? \"\"),\n };\n }\n break;\n }\n\n case \"item.updated\": {\n const item = event.item;\n if (!item) break;\n if (item.type === \"agent_message\") {\n const messageId = item.id != null ? String(item.id) : undefined;\n if (messageId !== currentAgentMessageId) {\n currentAgentMessageId = messageId;\n agentTextSoFar = \"\";\n }\n const text = String(item.text ?? \"\");\n const newChars = text.slice(agentTextSoFar.length);\n if (newChars) {\n yield { type: \"text_delta\", content: newChars };\n agentTextSoFar = text;\n }\n }\n break;\n }\n\n case \"item.completed\": {\n const item = event.item;\n if (!item) break;\n if (item.type === \"agent_message\") {\n finalText = String(item.text ?? \"\");\n agentTextSoFar = finalText;\n yield { type: \"text\", content: finalText };\n yield* extractFileEvents(finalText, \"text\");\n } else if (item.type === \"reasoning\") {\n const reasoning = String(item.text ?? \"\").trim();\n if (reasoning) yield { type: \"reasoning\", content: reasoning };\n } else if (item.type === \"mcp_tool_call\") {\n yield {\n type: \"tool_result\",\n toolUseId: String(item.id ?? \"\"),\n content: summarizeMcpToolCallResult(item as unknown as McpToolCallItem),\n };\n } else if (item.type === \"command_execution\") {\n yield {\n type: \"tool_result\",\n toolUseId: String(item.id ?? \"\"),\n content: String(item.aggregated_output ?? \"\").slice(0, 200),\n };\n } else if (item.type === \"file_change\") {\n for (const fileEvent of fileChangeEvents(item as unknown as FileChangeItem)) {\n yield fileEvent;\n }\n } else if (item.type === \"error\") {\n yield { type: \"error\", content: String(item.message ?? \"\") };\n }\n break;\n }\n\n case \"turn.completed\": {\n const usage = event.usage;\n if (!usage) break;\n attemptCompleted = true;\n const contextUsage = currentSessionId\n ? readLatestCodexContextUsage(currentSessionId)\n : undefined;\n yield {\n type: \"result\",\n content: finalText,\n stopReason,\n usage: {\n inputTokens: usage.input_tokens,\n outputTokens: usage.output_tokens,\n cacheReadInputTokens: usage.cached_input_tokens,\n ...contextUsage,\n },\n };\n if (finalText) yield* extractFileEvents(finalText, \"result\");\n break;\n }\n\n case \"turn.failed\": {\n stopReason = \"error\";\n yield {\n type: \"error\",\n content: event.error?.message || \"Codex turn failed\",\n };\n break;\n }\n\n default:\n break;\n }\n }\n } catch (err) {\n if (abortSignal?.aborted) return;\n if (err instanceof Error && err.name === \"AbortError\") {\n if (!heartbeatTriggered) return;\n // Heartbeat abort — fall through to retry logic below\n } else {\n logger.error({ err }, \"codexProvider: attempt failed\");\n yield { type: \"error\", content: errMsg(err) };\n break;\n }\n } finally {\n if (heartbeatTimer !== null) clearTimeout(heartbeatTimer);\n abortSignal?.removeEventListener(\"abort\", propagateOuter);\n if (trackedPids.pids.length > 0) unregisterOwnedCodexPids(trackedPids.pids);\n }\n\n if (attemptCompleted || abortSignal?.aborted) break;\n if (!heartbeatTriggered) break;\n\n heartbeatAttempts++;\n if (heartbeatAttempts > HEARTBEAT_MAX_ATTEMPTS) {\n logger.warn(\n { attempts: heartbeatAttempts },\n \"codexProvider: max heartbeat attempts reached\",\n );\n yield {\n type: \"error\",\n content: `Codex가 ${HEARTBEAT_MAX_ATTEMPTS}회 재시도 후에도 응답하지 않았습니다.`,\n };\n break;\n }\n\n heartbeatMs = Math.min(heartbeatMs * 2, HEARTBEAT_MAX_MS);\n logger.info(\n { attempt: heartbeatAttempts, nextIntervalMs: heartbeatMs },\n \"codexProvider: heartbeat fired, resuming thread with continuation prompt\",\n );\n\n // The resumed turn's agent_message grows from \"\" again. Stale lengths\n // from the aborted attempt would mis-slice deltas (silence until the new\n // text outgrows the old, then an arbitrary mid-string fragment), and a\n // resumed turn that ends without an agent_message would ship the\n // previous attempt's finalText as its result.\n agentTextSoFar = \"\";\n finalText = \"\";\n\n thread = currentSessionId\n ? codex.resumeThread(currentSessionId, threadOptions)\n : codex.startThread(threadOptions);\n prompt = currentSessionId ? HEARTBEAT_CONTINUATION : promptForThread(opts, true);\n }\n } catch (err) {\n if (err instanceof Error && err.name === \"AbortError\") return;\n if (abortSignal?.aborted) return;\n logger.error({ err }, \"codexProvider: setup failed\");\n yield { type: \"error\", content: errMsg(err) };\n } finally {\n abortSignal?.removeEventListener(\"abort\", onAbortKill);\n if (trackedPids.pids.length > 0) unregisterOwnedCodexPids(trackedPids.pids);\n }\n}\n",
20
- "import { spawn } from \"node:child_process\";\nimport {\n chmodSync,\n existsSync,\n readFileSync,\n renameSync,\n unlinkSync,\n writeFileSync,\n} from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { dirname, join } from \"node:path\";\nimport { NEGOTIUM_VERSION } from \"#version\";\n\ntype CodexModel = Record<string, unknown>;\ntype CodexModelCache = {\n models?: unknown;\n};\n\nconst NEGOTIUM_MODEL_CATALOG = \"negotium-model-catalog.json\";\nconst moduleRequire = createRequire(import.meta.url);\n\nfunction codexCliScriptPath(): string {\n const sdkPackagePath = moduleRequire.resolve(\"@openai/codex-sdk/package.json\");\n const sdkRequire = createRequire(sdkPackagePath);\n return join(dirname(sdkRequire.resolve(\"@openai/codex/package.json\")), \"bin\", \"codex.js\");\n}\n\nasync function bootstrapCodexModelCache(codexHome: string, cachePath: string): Promise<void> {\n const child = spawn(process.execPath, [codexCliScriptPath(), \"app-server\", \"--stdio\"], {\n env: { ...process.env, CODEX_HOME: codexHome },\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n });\n\n await new Promise<void>((resolve, reject) => {\n let settled = false;\n let stdoutBuffer = \"\";\n let stderr = \"\";\n const timer = setTimeout(\n () => finish(new Error(\"timed out while refreshing the Codex model catalog\")),\n 15_000,\n );\n\n const finish = (error?: Error) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n try {\n child.stdin.end();\n child.kill();\n } catch {\n // The app server may already have exited after stdin closed.\n }\n if (error) reject(error);\n else if (!existsSync(cachePath)) reject(new Error(\"Codex did not create its model cache\"));\n else resolve();\n };\n\n const send = (message: Record<string, unknown>) => {\n child.stdin.write(`${JSON.stringify(message)}\\n`);\n };\n\n child.stderr.on(\"data\", (chunk) => {\n if (stderr.length < 4_096) stderr += String(chunk);\n });\n child.on(\"error\", (error) => finish(error));\n child.on(\"exit\", (code, signal) => {\n if (!settled) {\n finish(\n new Error(\n `Codex model catalog refresh exited with ${signal ? `signal ${signal}` : `code ${code ?? 1}`}${stderr.trim() ? `: ${stderr.trim()}` : \"\"}`,\n ),\n );\n }\n });\n child.stdout.on(\"data\", (chunk) => {\n stdoutBuffer += String(chunk);\n for (;;) {\n const newline = stdoutBuffer.indexOf(\"\\n\");\n if (newline < 0) break;\n const line = stdoutBuffer.slice(0, newline);\n stdoutBuffer = stdoutBuffer.slice(newline + 1);\n let message: { id?: number; error?: { message?: string } };\n try {\n message = JSON.parse(line) as typeof message;\n } catch {\n continue;\n }\n if (message.id === 1) {\n if (message.error) {\n finish(new Error(message.error.message || \"Codex initialization failed\"));\n return;\n }\n send({ method: \"initialized\" });\n send({ id: 2, method: \"model/list\", params: { includeHidden: true } });\n } else if (message.id === 2) {\n if (message.error) {\n finish(new Error(message.error.message || \"Codex model listing failed\"));\n } else {\n finish();\n }\n return;\n }\n }\n });\n\n send({\n id: 1,\n method: \"initialize\",\n params: {\n clientInfo: { name: \"negotium\", version: NEGOTIUM_VERSION },\n capabilities: { experimentalApi: true },\n },\n });\n });\n}\n\nexport async function ensureCodexModelCache(\n authFilePath: string,\n bootstrap: (codexHome: string, cachePath: string) => Promise<void> = bootstrapCodexModelCache,\n): Promise<void> {\n const codexHome = dirname(authFilePath);\n const cachePath =\n process.env.NEGOTIUM_CODEX_MODELS_CACHE_FILE ?? join(codexHome, \"models_cache.json\");\n const hardenedCatalogPath = join(codexHome, NEGOTIUM_MODEL_CATALOG);\n if (existsSync(cachePath) || existsSync(hardenedCatalogPath)) return;\n if (process.env.NEGOTIUM_CODEX_MODELS_CACHE_FILE) {\n throw new Error(`Configured Codex model cache does not exist: ${cachePath}`);\n }\n await bootstrap(codexHome, cachePath);\n}\n\n/**\n * Codex 0.144 resolves model metadata before `features.multi_agent=false`, so\n * a model-advertised v1/v2 value still registers native collaboration tools.\n * Feed Codex an authoritative copy of its own catalog with only that field\n * disabled. Runtime MCP delegation remains available independently.\n */\nexport function writeCodexCatalogWithNativeMultiAgentDisabled(authFilePath: string): string {\n const codexHome = dirname(authFilePath);\n const sourcePath =\n process.env.NEGOTIUM_CODEX_MODELS_CACHE_FILE ??\n (existsSync(join(codexHome, \"models_cache.json\"))\n ? join(codexHome, \"models_cache.json\")\n : join(codexHome, NEGOTIUM_MODEL_CATALOG));\n const outputPath = join(codexHome, NEGOTIUM_MODEL_CATALOG);\n\n const parsed = JSON.parse(readFileSync(sourcePath, \"utf8\")) as CodexModelCache;\n if (!Array.isArray(parsed.models) || parsed.models.length === 0) {\n throw new Error(`Codex model cache has no models: ${sourcePath}`);\n }\n\n const models = parsed.models.map((model, index): CodexModel => {\n if (!model || typeof model !== \"object\" || Array.isArray(model)) {\n throw new Error(`Codex model cache entry ${index} is invalid: ${sourcePath}`);\n }\n return { ...(model as CodexModel), multi_agent_version: \"disabled\" };\n });\n const contents = `${JSON.stringify({ models }, null, 2)}\\n`;\n\n if (existsSync(outputPath) && readFileSync(outputPath, \"utf8\") === contents) {\n return outputPath;\n }\n\n const tempPath = `${outputPath}.${process.pid}.${Date.now()}.tmp`;\n try {\n writeFileSync(tempPath, contents, { encoding: \"utf8\", mode: 0o600 });\n renameSync(tempPath, outputPath);\n chmodSync(outputPath, 0o600);\n } finally {\n try {\n unlinkSync(tempPath);\n } catch {\n // renameSync normally consumed the temporary file.\n }\n }\n return outputPath;\n}\n",
21
- "/**\n * Maestro agent provider — thin local adapter over `maestro-agent-sdk`.\n *\n * Mirrors the pattern of claude-provider.ts / codex-provider.ts so that\n * agents/index.ts can import all three providers from sibling `@/agents/*`\n * paths rather than mixing package and local imports. The wrapper layer is\n * the natural extension point for Otium-specific overrides — anything\n * we want every maestro call to inherit gets stamped here before reaching\n * the SDK.\n *\n * v0.1.19 host overrides:\n * - `enableBackgroundBash: false` — the SDK's Claude-Code-style triad\n * (`Bash(run_in_background:true)` + `BashOutput` + `KillBash`) is OFF.\n * It was briefly always-on, but in this headless setup a background\n * bash's completion never triggers a new model turn — the process runs\n * in the bot but nobody polls it once the turn ends. Topics use\n * `mcp__background-bash__background_bash_run` instead, which injects a\n * session-inbox tell entry on exit so the loop actually closes.\n *\n * v0.1.21 host overrides:\n * - `maxTokens: 32_768` — global default for the per-API-call output\n * ceiling. Pre-v0.1.21 the SDK silently fell back to 4096, which\n * truncated long-form generation mid-string and broke Write/Edit\n * tool input JSON for multi-K file bodies (see the v0.1.21\n * changelog for the bug write-up). 32K is the Otium-wide\n * default because:\n * - long-form legal reports (슈퍼로이어, 기일보고) routinely\n * exceed 4K and have been the load-bearing failure surface;\n * - 32K is generous enough that ~99% of realistic single-turn\n * outputs fit without truncation;\n * - keeps cost / latency bounded relative to the SDK's own\n * model-catalog defaults (deepseek-pro 64K, deepseek-flash 32K)\n * which can be expensive for accidental long outputs.\n * Callers that need more (or less) override per-call via\n * `AgentQueryOptions.maxTokens` — the caller-supplied value wins\n * because `...opts` spreads AFTER the defaults below.\n *\n * v0.1.22 host overrides:\n * - `enableToolSearch: true` — deferred-tool / ToolSearch pattern is ON.\n * The pattern adds a round-trip every time a new tool is first reached\n * for (turn N: model calls `ToolSearch` → turn N+1: model calls the\n * actual tool), but that extra round-trip is now cheap relative to the\n * reminder-token savings across Otium's MCP server count, so the\n * tradeoff flipped in favor of deferral. Stamped as a literal `true`\n * (not omitted) so a code-reader sees the decision instead of guessing\n * intent. Caller-supplied `enableToolSearch: false` still wins because\n * `...opts` spreads AFTER this default; a future dispatcher / topic\n * config can flip it per topic if a specific topic's MCP server count\n * ever makes deferral not worth it.\n *\n * v0.1.42 host overrides:\n * - `disallowedTools` removes provider-native AskUserQuestion, Agent, and\n * Task* tools from the schema/catalog. Otium owns those surfaces via\n * runtime ask_user_question/spawn_subagent and the shared task MCP server\n * so state survives agent switches.\n *\n * If a future override becomes per-call (cwd-aware, topic-aware, etc.)\n * we lift the static spread into a per-call wrapper. For now the\n * overrides are uniform across every maestro turn, so a single\n * Object.assign keeps the surface trivial.\n */\n\nimport \"#platform/maestro-bootstrap-env\";\nimport type { HookRegistration, McpResolver } from \"maestro-agent-sdk\";\nimport { maestroProvider as sdkMaestroProvider, setMcpResolver } from \"maestro-agent-sdk\";\nimport {\n hostedMcpServers,\n redactHostedSecrets,\n referencesHostedSecretStorage,\n shouldRedirectHostedVaultTool,\n} from \"#agents/execution-host\";\nimport { VAULT_BROKER_REDIRECT_ERROR } from \"#agents/vault-tool-policy\";\nimport type { AgentQueryOptions, UnifiedEvent } from \"#types\";\n\n/**\n * Default per-API-call max output tokens for every Otium maestro turn.\n * See the file-level docstring for the rationale; callers override per call\n * via `AgentQueryOptions.maxTokens`.\n */\nconst MAESTRO_DEFAULT_MAX_TOKENS = 32_768;\nconst PROVIDER_ASK_USER_TOOL = \"AskUserQuestion\";\nconst PROVIDER_SUBAGENT_TOOL = \"Agent\";\nconst MAESTRO_NATIVE_TASK_TOOLS = [\n \"TaskCreate\",\n \"TaskUpdate\",\n \"TaskList\",\n \"TaskGet\",\n \"TaskOutput\",\n \"TaskStop\",\n] as const;\nconst MAESTRO_PROVIDER_OWNED_TOOL_SET = new Set<string>([\n PROVIDER_ASK_USER_TOOL,\n PROVIDER_SUBAGENT_TOOL,\n ...MAESTRO_NATIVE_TASK_TOOLS,\n]);\nconst DEFAULT_MAESTRO_DISALLOWED_TOOLS = [\n PROVIDER_ASK_USER_TOOL,\n PROVIDER_SUBAGENT_TOOL,\n ...MAESTRO_NATIVE_TASK_TOOLS,\n] as const;\n\nexport function buildMaestroDisallowedTools(\n callerDisallowedTools: readonly string[] = [],\n): readonly string[] {\n return [...new Set([...DEFAULT_MAESTRO_DISALLOWED_TOOLS, ...callerDisallowedTools])];\n}\n\n/**\n * Build per-call tool hooks:\n *\n * Pre hook — two responsibilities in one pass:\n * 1. Block direct vault.db filesystem access (security guard).\n * 2. Block direct placeholder substitution and redirect the model to the\n * Vault MCP credential broker, where expanded input stays outside the\n * provider process.\n *\n * Post hook — scrub raw/common encoded secret forms before tool output is sent\n * back to the model. HTTP credentials should still prefer vault_http_request,\n * whose broker never exposes the expanded request to the provider at all.\n */\nfunction buildVaultHook(userId: string): HookRegistration {\n return {\n name: \"vault-guard\",\n pre({ toolName, input }) {\n if (referencesHostedSecretStorage(input)) {\n return { decision: \"block\", error: \"Runtime secret storage access is not permitted\" };\n }\n\n // Detect key references from metadata only. No Vault value is decrypted\n // or injected into the provider/tool registry on this path.\n if (shouldRedirectHostedVaultTool(userId, toolName, input)) {\n return { decision: \"block\", error: VAULT_BROKER_REDIRECT_ERROR };\n }\n return { decision: \"allow\" };\n },\n post({ output }) {\n const redacted = redactHostedSecrets(userId, output);\n return redacted === output ? {} : { output: redacted };\n },\n };\n}\n\nexport function buildMaestroToolHooks(userId: string): HookRegistration[] {\n return [buildVaultHook(userId), buildProviderOwnedToolBlockHook()];\n}\n\nfunction providerOwnedToolRedirect(toolName: string): string {\n if (toolName === PROVIDER_ASK_USER_TOOL) {\n return \"Use the runtime ask_user_question MCP tool instead.\";\n }\n if (toolName === PROVIDER_SUBAGENT_TOOL) {\n return \"Use the runtime spawn_subagent MCP tool instead.\";\n }\n return (\n \"Use the shared task MCP tools instead \" +\n \"(mcp__task__task_create / task_update / task_list / task_get / task_delete).\"\n );\n}\n\nfunction buildProviderOwnedToolBlockHook(): HookRegistration {\n return {\n name: \"provider-owned-tool-redirect\",\n pre({ toolName }) {\n if (!MAESTRO_PROVIDER_OWNED_TOOL_SET.has(toolName)) return { decision: \"allow\" };\n return {\n decision: \"block\",\n error: `${toolName} is disabled in this environment. ${providerOwnedToolRedirect(toolName)}`,\n };\n },\n };\n}\n\nexport function maestroProvider(opts: AgentQueryOptions): AsyncGenerator<UnifiedEvent> {\n // Dispatcher guarantees agent === \"maestro\" before routing here; throw early\n // so routing bugs surface at the call site rather than silently overwriting.\n if (opts.agent !== undefined && opts.agent !== \"maestro\") {\n throw new Error(`maestroProvider: unexpected agent \"${opts.agent}\", expected \"maestro\"`);\n }\n const userId = opts.userId ?? \"\";\n // The SDK deliberately ships with an empty MCP resolver. Keep this wiring in\n // the provider adapter rather than every host bootstrap so a new Negotium\n // channel cannot accidentally run Maestro with zero runtime/wiki/task MCPs.\n setMcpResolver(hostedMcpServers as McpResolver);\n const callerDisallowedTools = opts.disallowedTools ?? [];\n const callerToolHooks = (opts as { toolHooks?: HookRegistration[] }).toolHooks ?? [];\n // maestro-agent-sdk's type does not yet include Otium's \"cron\" sessionType;\n // keep the runtime value intact so the host MCP resolver can choose cron scope.\n const sdkOpts = {\n // Built-in background bash (Bash/BashOutput/KillBash triad) is disabled\n // because its completion never triggers a new model turn in this headless\n // setup — the bash runs in the bot process but when the turn ends nobody\n // polls it. Use mcp__background-bash__background_bash_run instead, which\n // injects a session-inbox tell entry on exit so the loop closes properly.\n enableBackgroundBash: false,\n maxTokens: MAESTRO_DEFAULT_MAX_TOKENS,\n enableToolSearch: true,\n ...opts,\n // v0.1.39: SDK AgentQueryOptions.agent is narrowed to \"maestro\" only.\n // Otium's AgentKind is wider (\"claude\"|\"codex\"|\"maestro\"), so stamp\n // the literal to satisfy the SDK type.\n agent: \"maestro\",\n disallowedTools: buildMaestroDisallowedTools(callerDisallowedTools),\n toolHooks: [...buildMaestroToolHooks(userId), ...callerToolHooks],\n } as unknown as Parameters<typeof sdkMaestroProvider>[0];\n return sdkMaestroProvider(sdkOpts);\n}\n"
22
- ],
23
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA;AAMA,IAAM,mBAAmB;AACzB,IAAM,wBAAwB;AAI9B,IAAM,iBAAiB;AAGvB,SAAS,iBAAiB,CAAC,WAA6B;AAAA,EACtD,IAAI;AAAA,IACF,MAAM,MAAM,aAAa,SAAS,CAAC,MAAM,OAAO,SAAS,CAAC,GAAG;AAAA,MAC3D,UAAU;AAAA,MACV,OAAO,CAAC,UAAU,QAAQ,QAAQ;AAAA,IACpC,CAAC,EAAE,KAAK;AAAA,IACR,KAAK;AAAA,MAAK,OAAO,CAAC;AAAA,IAClB,OAAO,IACJ,MAAM;AAAA,CAAI,EACV,IAAI,CAAC,MAAM,OAAO,CAAC,CAAC,EACpB,OAAO,CAAC,MAAM,OAAO,SAAS,CAAC,KAAK,IAAI,CAAC;AAAA,IAC5C,MAAM;AAAA,IAEN,OAAO,CAAC;AAAA;AAAA;AAKZ,SAAS,WAAW,CAAC,KAAqB;AAAA,EACxC,IAAI;AAAA,IACF,OAAO,aAAa,MAAM,CAAC,MAAM,OAAO,GAAG,GAAG,MAAM,OAAO,GAAG;AAAA,MAC5D,UAAU;AAAA,MACV,OAAO,CAAC,UAAU,QAAQ,QAAQ;AAAA,IACpC,CAAC,EAAE,KAAK;AAAA,IACR,MAAM;AAAA,IACN,OAA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