negotium 0.2.2 → 0.2.4

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 (70) hide show
  1. package/dist/agent-helpers.js +3117 -2915
  2. package/dist/agent-helpers.js.map +38 -37
  3. package/dist/background-bash.js.map +1 -1
  4. package/dist/browser-runtime.js +137 -21
  5. package/dist/browser-runtime.js.map +10 -9
  6. package/dist/{chunk-kc5kmr95.js → chunk-1s9ryz8g.js} +1195 -21
  7. package/dist/chunk-1s9ryz8g.js.map +35 -0
  8. package/dist/hosted-agent.js +60 -48
  9. package/dist/hosted-agent.js.map +10 -10
  10. package/dist/main.js +3038 -3357
  11. package/dist/main.js.map +35 -35
  12. package/dist/mcp-factories.js +6227 -6021
  13. package/dist/mcp-factories.js.map +40 -39
  14. package/dist/prompts.js.map +1 -1
  15. package/dist/query-runtime.js +22 -2
  16. package/dist/query-runtime.js.map +4 -4
  17. package/dist/registry.js +169 -213
  18. package/dist/registry.js.map +8 -9
  19. package/dist/rollout.js +1 -1
  20. package/dist/runtime/src/agents/codex-app-server.ts +136 -0
  21. package/dist/runtime/src/agents/codex-native-multi-agent.ts +1 -1
  22. package/dist/runtime/src/agents/codex-provider.ts +21 -11
  23. package/dist/runtime/src/agents/codex-registry.ts +9 -17
  24. package/dist/runtime/src/agents/contracts.ts +2 -0
  25. package/dist/runtime/src/agents/execution-host.ts +6 -0
  26. package/dist/runtime/src/agents/fork.ts +24 -18
  27. package/dist/runtime/src/agents/idle-archiver.ts +7 -2
  28. package/dist/runtime/src/agents/index.ts +2 -1
  29. package/dist/runtime/src/agents/maestro-registry.ts +26 -7
  30. package/dist/runtime/src/agents/memory-archive-policy.ts +20 -0
  31. package/dist/runtime/src/agents/rollout/codex.ts +6 -5
  32. package/dist/runtime/src/agents/rollout/shared.ts +3 -5
  33. package/dist/runtime/src/mcp/factories/session-comm.ts +12 -0
  34. package/dist/runtime/src/mcp/session-comm/default-host.ts +16 -0
  35. package/dist/runtime/src/mcp/session-comm/server.ts +25 -0
  36. package/dist/runtime/src/platform/config.ts +4 -1
  37. package/dist/runtime/src/platform/playwright/manager.ts +57 -1
  38. package/dist/runtime/src/platform/playwright/profile-management.ts +33 -0
  39. package/dist/runtime/src/platform/playwright/public-runtime.ts +5 -0
  40. package/dist/runtime/src/platform/playwright/vault-broker.ts +9 -10
  41. package/dist/runtime/src/storage/browser-profiles.ts +35 -10
  42. package/dist/runtime/src/storage/storage-host.ts +31 -5
  43. package/dist/runtime/src/storage/vault.ts +30 -2
  44. package/dist/runtime/src/topics/derive.ts +38 -2
  45. package/dist/runtime/src/topics/lifecycle.ts +12 -2
  46. package/dist/runtime/src/version.ts +1 -1
  47. package/dist/runtime-helpers.js +22 -2
  48. package/dist/runtime-helpers.js.map +4 -4
  49. package/dist/storage.js +22 -2
  50. package/dist/storage.js.map +4 -4
  51. package/dist/types/packages/core/src/agents/codex-app-server.d.ts +13 -0
  52. package/dist/types/packages/core/src/agents/codex-native-multi-agent.d.ts +1 -0
  53. package/dist/types/packages/core/src/agents/contracts.d.ts +2 -0
  54. package/dist/types/packages/core/src/agents/execution-host.d.ts +2 -0
  55. package/dist/types/packages/core/src/agents/fork.d.ts +8 -7
  56. package/dist/types/packages/core/src/agents/memory-archive-policy.d.ts +10 -0
  57. package/dist/types/packages/core/src/agents/rollout/codex.d.ts +4 -2
  58. package/dist/types/packages/core/src/mcp/factories/session-comm.d.ts +1 -0
  59. package/dist/types/packages/core/src/platform/playwright/manager.d.ts +15 -0
  60. package/dist/types/packages/core/src/platform/playwright/profile-management.d.ts +8 -0
  61. package/dist/types/packages/core/src/platform/playwright/public-runtime.d.ts +2 -1
  62. package/dist/types/packages/core/src/storage/browser-profiles.d.ts +3 -1
  63. package/dist/types/packages/core/src/storage/storage-host.d.ts +1 -0
  64. package/dist/types/packages/core/src/storage/vault.d.ts +8 -0
  65. package/dist/types/packages/core/src/version.d.ts +1 -1
  66. package/dist/vault.js +19 -3
  67. package/dist/vault.js.map +4 -4
  68. package/package.json +2 -2
  69. package/dist/chunk-kc5kmr95.js.map +0 -19
  70. package/dist/runtime/src/migration/single-user.ts +0 -805
@@ -0,0 +1,35 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../packages/core/src/agents/rollout/shared.ts", "../../../packages/core/src/platform/config.ts", "../../../packages/core/src/platform/config-helpers.ts", "../../../packages/core/src/platform/logger.ts", "../../../packages/core/src/types.ts", "../../../packages/core/src/runtime/user-turn-envelope.ts", "../../../packages/core/src/agents/rollout/claude.ts", "../../../packages/core/src/platform/jsonl.ts", "../../../packages/core/src/platform/file-utils.ts", "../../../packages/core/src/agents/rollout/codex.ts", "../../../packages/core/src/agents/execution-host.ts", "../../../packages/core/src/security/sensitive-path.ts", "../../../packages/core/src/agents/vault-tool-policy.ts", "../../../packages/core/src/mcp/canonical-bridge-config.ts", "../../../packages/core/src/mcp/runtime-spec.ts", "../../../packages/core/src/mcp/session-comm/bridge-ipc-config.ts", "../../../packages/core/src/platform/background-bash/manager.ts", "../../../packages/core/src/platform/delay.ts", "../../../packages/core/src/platform/background-bash/context.ts", "../../../packages/core/src/platform/mcp-catalog-policy.ts", "../../../packages/core/src/platform/playwright/capability.ts", "../../../packages/core/src/platform/mcp-config.ts", "../../../packages/core/src/storage/vault.ts", "../../../packages/core/src/storage/sqlite.ts", "../../../packages/core/src/storage/vault-crypto-core.ts", "../../../packages/core/src/storage/vault-crypto.ts"],
4
+ "sourcesContent": [
5
+ "/**\n * Helpers shared by every agent's rollout encoder.\n *\n * Each rollout file under `agents/rollout/<agent>.ts` materializes a\n * synthetic SDK-native JSONL from a provider-agnostic `ConversationEntry`\n * stream. The cwd validation, UUID shape check, and chat-pair extraction\n * are identical regardless of agent, so they live here.\n */\n\nimport { mkdirSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport {\n DM_WORKSPACE_DIR,\n PROJECT_ROOT,\n SESSION_WORKSPACE_DIR,\n TOPIC_WORKSPACE_DIR,\n WORKSPACE_DIR,\n} from \"#platform/config\";\nimport { logger } from \"#platform/logger\";\nimport { renderUserPromptBatch } from \"#runtime/user-turn-envelope\";\nimport type { ConversationEntry } from \"#storage/conversations\";\n\nexport interface RolloutHostOptions {\n /** Absolute workspace roots under which synthetic provider sessions may be written. */\n workspaceRoots?: readonly string[];\n /** Directory containing the provider rollout fixture JSONL files. */\n fixturesDir?: string;\n}\n\nlet trustedWorkspaceRoots = [\n WORKSPACE_DIR,\n DM_WORKSPACE_DIR,\n SESSION_WORKSPACE_DIR,\n TOPIC_WORKSPACE_DIR,\n].map((root) => resolve(root));\n\n/** Configure the embedding host's trusted workspace roots. */\nexport function configureRolloutHost(options: RolloutHostOptions): () => void {\n if (!options.workspaceRoots && !options.fixturesDir) {\n throw new Error(\"configureRolloutHost requires workspaceRoots or fixturesDir\");\n }\n if (options.workspaceRoots?.length === 0) {\n throw new Error(\"configureRolloutHost requires at least one workspace root\");\n }\n const previousRoots = trustedWorkspaceRoots;\n const previousFixturesDir = FIXTURES_DIR;\n if (options.workspaceRoots) {\n trustedWorkspaceRoots = options.workspaceRoots.map((root) => resolve(root));\n }\n if (options.fixturesDir) FIXTURES_DIR = resolve(options.fixturesDir);\n let disposed = false;\n return () => {\n if (disposed) return;\n disposed = true;\n trustedWorkspaceRoots = previousRoots;\n FIXTURES_DIR = previousFixturesDir;\n };\n}\n\n/**\n * Captured fixture snapshots — `claude-attachments.jsonl`, `codex-shell.jsonl`,\n * etc. — live one level above the per-agent rollout files (under\n * `agents/fixtures/`) so each agent can pull from the same directory without\n * duplicating fixtures.\n *\n * To refresh fixtures: run any live Codex/Claude session, copy the first few\n * non-conversational entries from the resulting rollout file, and update\n * `src/agents/fixtures/{codex-shell,claude-attachments}.jsonl`.\n */\nexport let FIXTURES_DIR = resolve(PROJECT_ROOT, \"src\", \"agents\", \"fixtures\");\n\n/** Deep-clone to avoid mutating cached fixture objects. */\nexport function clone<T>(obj: T): T {\n return structuredClone(obj);\n}\n\n/**\n * UUID v4/v7 shape — both 36 chars with the standard 8-4-4-4-12 hex layout.\n * We do not enforce the version nibble because randomUUID (v4) and uuidv7\n * coexist; the only requirement for our caller is that the value is safe to\n * embed in a path component and that the SDK accepts it as a session/thread\n * identifier.\n */\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\nexport function assertUuidLike(label: string, value: string): void {\n if (!UUID_RE.test(value)) {\n throw new Error(`rollout: ${label} is not a UUID-shaped string: ${value}`);\n }\n}\n\n/**\n * Reject cwds that escape Otium-managed workspace roots. We use `path.resolve`\n * to normalize `..` traversal; symlink-based escapes are out of scope (the\n * workspace roots are not expected to contain attacker-controlled symlinks).\n */\nfunction assertCwdInWorkspace(cwd: string): void {\n const abs = resolve(cwd);\n // Synthetic rollouts for spawn/fork must be written under the same root as\n // live topic turns or provider resume looks in a different cwd hash than the\n // one we generated.\n const ok = trustedWorkspaceRoots.some((root) => abs === root || abs.startsWith(`${root}/`));\n if (!ok) {\n throw new Error(`rollout: cwd outside trusted workspace roots: ${cwd} (resolved=${abs})`);\n }\n}\n\n/** Best-effort guarantee that the resumed cwd will exist when the SDK stats it. */\nexport function ensureCwdExists(cwd: string): void {\n assertCwdInWorkspace(cwd);\n try {\n mkdirSync(cwd, { recursive: true });\n } catch (err) {\n logger.warn({ err, cwd }, \"rollout: ensureCwdExists failed — caller should pre-create cwd\");\n }\n}\n\n/**\n * Length-bound a string by Unicode code points rather than UTF-16 units, so a\n * truncation never lands in the middle of a multi-byte sequence and produces\n * a malformed character. Used for in-line tool annotations where we only need\n * a rough preview, not the full payload.\n */\nfunction truncate(text: string, n: number): string {\n const cps = Array.from(text);\n return cps.length > n ? `${cps.slice(0, n).join(\"\")}…` : text;\n}\n\n/**\n * Reduce a UnifiedEvent stream to user/assistant message pairs. Tool calls and\n * tool results are inlined as bracketed annotations on the surrounding\n * assistant turn so the historical narrative is preserved when synthesizing a\n * native rollout for a different SDK. Streaming text deltas are folded into\n * their final consolidated `text` event to avoid double-counting partial\n * tokens.\n */\nexport type ChatPair = { userText: string; assistantText: string };\n\ninterface ExtractOptions {\n includeToolAnnotations: boolean;\n}\n\nexport function extractChatPairs(\n entries: ConversationEntry[],\n opts: ExtractOptions = { includeToolAnnotations: true },\n): ChatPair[] {\n const pairs: ChatPair[] = [];\n let pendingUsers: string[] = [];\n let pendingBatchSize: number | null = null;\n let pendingBatchNextIndex = 0;\n let pendingAssistantParts: string[] = [];\n let toolBuffer: string[] = [];\n\n const flushAssistant = () => {\n if (pendingUsers.length === 0) return;\n const tools =\n opts.includeToolAnnotations && toolBuffer.length > 0 ? `\\n\\n${toolBuffer.join(\"\\n\")}` : \"\";\n const assistantText = pendingAssistantParts.join(\"\").trim() + tools;\n if (assistantText.trim()) {\n pairs.push({ userText: renderUserPromptBatch(pendingUsers), assistantText });\n }\n pendingUsers = [];\n pendingBatchSize = null;\n pendingBatchNextIndex = 0;\n pendingAssistantParts = [];\n toolBuffer = [];\n };\n\n for (const entry of entries) {\n const ev = entry.event;\n switch (ev.type) {\n case \"user_message\": {\n const userEvent = ev as {\n content: string;\n consecutiveBatchSize?: number;\n consecutiveBatchIndex?: number;\n };\n if (pendingAssistantParts.length > 0 || toolBuffer.length > 0) {\n flushAssistant();\n }\n const batchSize = userEvent.consecutiveBatchSize;\n const batchIndex = userEvent.consecutiveBatchIndex;\n const marked =\n Number.isInteger(batchSize) &&\n Number.isInteger(batchIndex) &&\n (batchSize ?? 0) > 1 &&\n (batchIndex ?? -1) >= 0 &&\n (batchIndex ?? 0) < (batchSize ?? 0);\n if (!marked) {\n if (pendingUsers.length > 0) flushAssistant();\n pendingUsers.push(userEvent.content);\n pendingBatchSize = null;\n pendingBatchNextIndex = 0;\n break;\n }\n if (batchIndex === 0) {\n if (pendingUsers.length > 0) flushAssistant();\n pendingBatchSize = batchSize ?? null;\n pendingBatchNextIndex = 0;\n } else if (\n !(\n (pendingBatchSize !== null &&\n (batchSize ?? 0) >= pendingBatchSize &&\n pendingBatchNextIndex === batchIndex) ||\n (pendingBatchSize === null && pendingUsers.length === batchIndex)\n )\n ) {\n flushAssistant();\n }\n pendingUsers.push(userEvent.content);\n pendingBatchSize = batchSize ?? null;\n pendingBatchNextIndex = (batchIndex ?? 0) + 1;\n break;\n }\n case \"session\":\n // Session-id metadata. Provider sessions can change mid-conversation\n // (e.g. agent flip after rollout reconstruction), but the SDK normally\n // emits this *during* a turn — after the user prompt was already\n // recorded, before the assistant text arrives. Only flush when there\n // is actual assistant content in flight; otherwise we'd discard the\n // staged user prompt and the next text event would synthesize a bogus\n // \"(continued)\" pair.\n if (pendingAssistantParts.length > 0 || toolBuffer.length > 0) {\n flushAssistant();\n }\n break;\n case \"text\": {\n // Per-block assistant text. claudeProvider emits one of these per text\n // content block, so a single turn can yield multiple `text` events\n // interleaved with tool_use. Accumulate (do NOT flush yet) — the\n // turn's `result` event below carries the final concatenation and\n // is the proper boundary.\n if (pendingUsers.length === 0) {\n pendingUsers = [\"(continued)\"];\n }\n pendingAssistantParts.push((ev as { content: string }).content);\n break;\n }\n case \"result\": {\n // End-of-turn marker. `result.content` is the canonical final answer\n // produced by the provider, so prefer it over the accumulated `text`\n // chunks (which may be partial or out of order across SDKs).\n if (pendingUsers.length === 0) {\n pendingUsers = [\"(continued)\"];\n }\n pendingAssistantParts = [(ev as { content: string }).content];\n flushAssistant();\n break;\n }\n case \"text_delta\":\n // Skip — final `text`/`result` event carries the complete content.\n break;\n case \"tool_use\": {\n const u = ev as { name: string; input: Record<string, unknown> };\n toolBuffer.push(`<!-- Tool: ${u.name} ${truncate(JSON.stringify(u.input), 200)} -->`);\n break;\n }\n case \"tool_result\": {\n const u = ev as { content: string };\n toolBuffer.push(`<!-- Tool result: ${truncate(u.content, 200)} -->`);\n break;\n }\n case \"error\": {\n const u = ev as { content: string };\n toolBuffer.push(`[Error: ${truncate(u.content, 200)}]`);\n break;\n }\n // Other UnifiedEvent variants (`tool_progress`, `tool_use_summary`,\n // `file`, `text_delta` already handled above) carry no conversational\n // content, so they do not contribute to a chat pair. We intentionally\n // omit a default branch — the explicit user_message variant introduced\n // by the recorder makes the previous \"treat unrecognized as user\" hack\n // unnecessary, and adding new UnifiedEvent variants in the future\n // should require an explicit decision here, not silent inheritance.\n case \"tool_progress\":\n case \"tool_use_summary\":\n case \"file\":\n case \"status\":\n break;\n }\n }\n flushAssistant();\n return pairs;\n}\n",
6
+ "import { execFileSync } from \"node:child_process\";\nimport { randomBytes } from \"node:crypto\";\nimport {\n accessSync,\n chmodSync,\n constants,\n existsSync,\n mkdirSync,\n readFileSync,\n writeFileSync,\n} from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { homedir } from \"node:os\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { parseRuntimePort, readEnvText, safeRuntimePathSegment } from \"#platform/config-helpers\";\nimport { logger } from \"#platform/logger\";\nimport { type AgentKind, isAgentKind } from \"#types\";\n\nexport function envText(envKey: string): string | undefined {\n return readEnvText(process.env, envKey);\n}\n\nfunction resolveAgentEnv(envKey: string, fallback: AgentKind, legacyEnvKey?: string): AgentKind {\n const value = envText(envKey) ?? (legacyEnvKey ? envText(legacyEnvKey) : undefined);\n return isAgentKind(value) ? value : fallback;\n}\n\nconst HOME = homedir();\n\n// new URL(\"../..\", import.meta.url) causes webpack to treat \"../..\" as a module import.\n// Split into fileURLToPath → dirname → resolve to avoid that.\nfunction resolveProjectRoot(): string {\n const moduleDir = dirname(fileURLToPath(import.meta.url));\n const packagedRuntime = resolve(moduleDir, \"runtime\");\n if (existsSync(resolve(packagedRuntime, \"src\"))) return packagedRuntime;\n return resolve(moduleDir, \"../..\");\n}\n\nexport const PROJECT_ROOT = resolveProjectRoot();\n\n/** Resolve a dependency executable from either a package-local or hoisted install. */\nfunction resolveDependencyBin(name: string): string {\n let dir = PROJECT_ROOT;\n while (true) {\n const candidate = resolve(dir, \"node_modules\", \".bin\", name);\n if (existsSync(candidate)) return candidate;\n const parent = dirname(dir);\n if (parent === dir) return candidate;\n dir = parent;\n }\n}\n\n// Each machine is one negotium node; all node state lives in one dotdir.\n// NEGOTIUM_STATE_DIR overrides (useful for tests and multi-node-on-one-box).\nconst STATE_DIR_ENV = envText(\"NEGOTIUM_STATE_DIR\");\nexport const STATE_DIR = STATE_DIR_ENV ? resolve(STATE_DIR_ENV) : resolve(HOME, \".negotium\");\n\nfunction resolveLocalStateDir(envKey: string, stateName: string): string {\n const envValue = envText(envKey);\n if (envValue) return resolve(envValue);\n return resolve(STATE_DIR, stateName);\n}\n\nfunction parsePortEnv(envValue: string | undefined, fallback: number): number {\n return parseRuntimePort(envValue, fallback);\n}\n\nexport const WORKSPACE_DIR = resolveLocalStateDir(\"NEGOTIUM_WORKSPACE_DIR\", \"workspace\");\nexport const TOPIC_WORKSPACE_DIR = resolve(WORKSPACE_DIR, \"topics\");\nexport const SHARED_WIKI_DIR = resolve(WORKSPACE_DIR, \"wiki\");\nexport const CRON_WORKSPACE_DIR = resolve(WORKSPACE_DIR, \"cron\");\nexport const BROWSER_DIR = resolveLocalStateDir(\"NEGOTIUM_BROWSER_DIR\", \"browser\");\nexport const BROWSER_PROFILES_DIR = resolve(BROWSER_DIR, \"profiles\");\nexport const BINARIES_DIR = resolve(STATE_DIR, \"binaries\");\nexport const SECRETS_DIR = resolve(STATE_DIR, \"secrets\");\n// Legacy names remain public, but their durable contents now live under data.\nexport const CONTEXTS_DIR = resolve(STATE_DIR, \"data\", \"contexts\");\nexport const DM_WORKSPACE_DIR = resolve(STATE_DIR, \"data\", \"dm\");\nexport const SESSION_WORKSPACE_DIR = resolve(STATE_DIR, \"data\", \"sessions\");\n// The Claude Agent SDK ships a platform-matched Claude Code binary. Keep that\n// SDK/CLI pair together by default; only use an external executable when an\n// operator explicitly opts in. This avoids silently pairing an older SDK with\n// a newer globally installed Claude Code release.\nconst CLAUDE_EXECUTABLE_ENV = envText(\"NEGOTIUM_CLAUDE_EXECUTABLE\");\nexport const CLAUDE_EXECUTABLE = CLAUDE_EXECUTABLE_ENV ? resolve(CLAUDE_EXECUTABLE_ENV) : undefined;\n\n// Fallback output language for model-generated prose (topic/channel/manager\n// replies and the archiver's summaries, briefs, articles, completion reply).\n// Defaults to English; set `NEGOTIUM_LANG` to the user's mother tongue (e.g.\n// `Korean`, `ko`). The assistant still mirrors whatever language the user\n// writes in; `NEGOTIUM_MEMORY_LANG` can narrow just the archiver. Fixed system\n// chrome / degraded-path strings emitted by code stay English (can't translate\n// an arbitrary value at runtime).\nexport const DEFAULT_OUTPUT_LANGUAGE = \"English\";\n\nexport function resolveOutputLanguage(): string {\n const raw = envText(\"NEGOTIUM_LANG\")?.trim();\n return raw && raw.length > 0 ? raw : DEFAULT_OUTPUT_LANGUAGE;\n}\n\n/** Browser.rs release tested with this Negotium version. */\nexport const BROWSER_RS_VERSION = \"v0.1.16\";\n/** Require the authenticated listener and the current Browser.rs tool contract. */\nexport const BROWSER_RS_MIN_SECURE_VERSION = \"0.1.15\";\n\nfunction versionAtLeast(actualVersion: string, minimumVersion: string): boolean {\n const actual = actualVersion.split(\".\").map(Number);\n const minimum = minimumVersion.split(\".\").map(Number);\n if (actual.some(Number.isNaN) || minimum.some(Number.isNaN)) return false;\n for (let index = 0; index < minimum.length; index += 1) {\n if ((actual[index] ?? 0) > (minimum[index] ?? 0)) return true;\n if ((actual[index] ?? 0) < (minimum[index] ?? 0)) return false;\n }\n return true;\n}\n\nfunction browserRsMeetsMinimumVersion(candidate: string): boolean {\n try {\n const output = execFileSync(candidate, [\"--version\"], {\n encoding: \"utf8\",\n timeout: 2_000,\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n }).trim();\n const match = output.match(/^browser-rs (\\d+)\\.(\\d+)\\.(\\d+)$/);\n if (!match) return false;\n return versionAtLeast(match.slice(1).join(\".\"), BROWSER_RS_MIN_SECURE_VERSION);\n } catch {\n return false;\n }\n}\n\n/**\n * Resolve the preferred Browser.rs engine without consulting PATH. The\n * versioned private location keeps different Negotium releases reproducible\n * and avoids changing a user's global browser-rs installation.\n */\nexport function resolveBrowserRsBin(envValue?: string): string | undefined {\n const override = envValue?.trim();\n if (\n !override &&\n !versionAtLeast(BROWSER_RS_VERSION.replace(/^v/, \"\"), BROWSER_RS_MIN_SECURE_VERSION)\n ) {\n return undefined;\n }\n const candidate = override\n ? resolve(override)\n : resolve(BINARIES_DIR, \"browser-rs\", BROWSER_RS_VERSION, \"browser-rs\");\n try {\n accessSync(candidate, constants.X_OK);\n return browserRsMeetsMinimumVersion(candidate) ? candidate : undefined;\n } catch {\n return undefined;\n }\n}\n\nexport const BROWSER_RS_BIN = resolveBrowserRsBin(envText(\"NEGOTIUM_BROWSER_RS_BIN\"));\n\n// Managed Browser.rs terminates MCP transports and security policy itself.\nexport function resolveBrowserMcpBin(envValue?: string): string {\n const override = envValue?.trim();\n if (override) return resolve(override);\n return BROWSER_RS_BIN ?? resolve(BINARIES_DIR, \"browser-rs\", BROWSER_RS_VERSION, \"browser-rs\");\n}\n\nexport const PLAYWRIGHT_MCP_BIN = resolveBrowserMcpBin(envText(\"NEGOTIUM_BROWSER_MCP_BIN\"));\n\n// --- Browser egress proxy ---\n//\n// On a datacenter host (AWS) the browser's egress IP is a known cloud range,\n// so anti-bot services (Cloudflare, DataDome, reCAPTCHA) challenge or block it\n// far more than a residential IP would. Routing the automation browser through\n// a residential/ISP proxy moves the egress IP out of the datacenter range.\n//\n// Operators set BROWSER_PROXY_URL, e.g. http://user:pass@proxy.host:8080 or\n// socks5://proxy.host:1080. Credentials in the URL are split out because\n// Playwright takes them as separate fields. BROWSER_PROXY_BYPASS is an optional\n// comma-separated no-proxy list (e.g. \"localhost,127.0.0.1,*.internal\").\n//\n// NOTE: Chromium does not support authentication for SOCKS proxies — put\n// credentials only on http/https proxy URLs.\nexport type BrowserProxyConfig = {\n server: string;\n username?: string;\n password?: string;\n bypass?: string;\n};\n\nexport function resolveBrowserProxy(): BrowserProxyConfig | null {\n const raw = envText(\"BROWSER_PROXY_URL\");\n if (!raw) return null;\n let url: URL;\n try {\n url = new URL(raw);\n } catch {\n logger.warn({ raw }, \"Ignoring malformed BROWSER_PROXY_URL\");\n return null;\n }\n // Playwright wants the server without embedded credentials.\n const server = `${url.protocol}//${url.host}`;\n const proxy: BrowserProxyConfig = { server };\n if (url.username) proxy.username = decodeURIComponent(url.username);\n if (url.password) proxy.password = decodeURIComponent(url.password);\n const bypass = envText(\"BROWSER_PROXY_BYPASS\");\n if (bypass) proxy.bypass = bypass;\n return proxy;\n}\n\n// --- Node/tsx runtime for the `codex` agent's MCP servers ---\n//\n// codex 0.135's rmcp stdio MCP client cannot reliably complete the initialize\n// handshake with servers spawned via `bun` (the JSON-RPC initialize is\n// dropped/raced and no tools ever reach the model). Pure-node servers connect\n// reliably, so codex turns launch the SAME .ts servers via node + tsx instead\n// of `bun run`. claude/maestro keep using `bun run` (fast, native, unaffected).\n//\n// tsx transpiles .ts on the fly and resolves the `@/*` tsconfig path aliases,\n// but only when it can find the tsconfig — and MCP servers run with cwd set to\n// the user's workspace dir, not PROJECT_ROOT — so we pass TSX_TSCONFIG_PATH\n// explicitly via env. Requires package.json `\"type\": \"module\"` so the servers'\n// top-level `await` loads as ESM under node.\nexport const TSX_BIN = resolveDependencyBin(\"tsx\");\n/** In-process tsx loader used by Node MCP entrypoints (avoids the tsx CLI child process). */\nexport const TSX_LOADER = createRequire(import.meta.url).resolve(\"tsx\");\nexport const TSCONFIG_PATH = resolve(PROJECT_ROOT, \"tsconfig.json\");\n\nexport const SESSION_COMM_SERVER = resolve(PROJECT_ROOT, \"src/mcp/session-comm/server.ts\");\n\nexport const TASK_SERVER = resolve(PROJECT_ROOT, \"src/mcp/task-server.ts\");\nexport const BROWSER_MCP_SSE_PROXY_SERVER = resolve(\n PROJECT_ROOT,\n \"src/mcp/browser-sse-proxy-server.ts\",\n);\nexport const CANONICAL_MCP_PROXY_SERVER = resolve(\n PROJECT_ROOT,\n \"src/mcp/canonical-proxy-server.ts\",\n);\n\nexport const WIKI_SERVER = resolve(PROJECT_ROOT, \"src/mcp/wiki-server.ts\");\n\nexport const TOKEN_STATS_SERVER = resolve(PROJECT_ROOT, \"src/mcp/token-stats-server.ts\");\n\nexport const COMPACTION_LOG_SERVER = resolve(PROJECT_ROOT, \"src/mcp/compaction-log-server.ts\");\n\nexport const SYSTEM_HEALTH_SERVER = resolve(PROJECT_ROOT, \"src/mcp/system-health-server.ts\");\n\nexport const AGENT_HEALTH_SERVER = resolve(PROJECT_ROOT, \"src/mcp/agent-health-server.ts\");\n\nexport const BACKGROUND_BASH_SERVER = resolve(PROJECT_ROOT, \"src/mcp/background-bash-server.ts\");\n\nexport const VAULT_SERVER = resolve(PROJECT_ROOT, \"src/mcp/vault-server.ts\");\n\nexport const BG_BASH_BASE_PORT = parsePortEnv(process.env.BG_BASH_BASE_PORT, 9700);\nexport const BG_BASH_MAX_PORT = parsePortEnv(process.env.BG_BASH_MAX_PORT, 9799);\n\nfunction safeWorkspaceSegment(value: string, fallback: string): string {\n return safeRuntimePathSegment(value, fallback);\n}\n\n/** Resolve the shared filesystem workspace for an API topic. */\nexport function resolveTopicWorkspaceDir(topicId: string): string {\n return join(TOPIC_WORKSPACE_DIR, safeWorkspaceSegment(topicId, \"topic\"));\n}\n\nexport function isProductionEnv(): boolean {\n return process.env.NODE_ENV === \"production\";\n}\n\nfunction loadOrCreateLocalSecret(\n envKey: string,\n filename: string,\n options: { persistEnvValue?: boolean } = {},\n): string {\n const envValue = envText(envKey);\n const secretFile = resolve(SECRETS_DIR, filename);\n mkdirSync(dirname(secretFile), { recursive: true });\n if (envValue) {\n if (options.persistEnvValue) {\n writeFileSync(secretFile, `${envValue}\\n`, { mode: 0o600 });\n chmodSync(secretFile, 0o600);\n }\n return envValue;\n }\n\n if (existsSync(secretFile)) {\n const stored = readFileSync(secretFile, \"utf-8\").trim();\n if (stored) {\n chmodSync(secretFile, 0o600);\n return stored;\n }\n }\n\n const secret = randomBytes(32).toString(\"base64url\");\n try {\n writeFileSync(secretFile, `${secret}\\n`, { mode: 0o600, flag: \"wx\" });\n return secret;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"EEXIST\") throw error;\n const stored = readFileSync(secretFile, \"utf-8\").trim();\n if (!stored) throw new Error(`Secret file exists but is empty: ${secretFile}`);\n chmodSync(secretFile, 0o600);\n return stored;\n }\n}\n\nexport const RUNTIME_MCP_SECRET = loadOrCreateLocalSecret(\n \"RUNTIME_MCP_SECRET\",\n \"runtime-mcp-secret\",\n);\n/** Local bearer token for the loopback node-control API. */\nexport const NODE_CONTROL_TOKEN = loadOrCreateLocalSecret(\n \"NEGOTIUM_CONTROL_TOKEN\",\n \"node-control-token\",\n);\nexport const VAULT_MASTER_KEY = loadOrCreateLocalSecret(\n \"NEGOTIUM_VAULT_MASTER_KEY\",\n \"vault-master-key\",\n { persistEnvValue: true },\n);\n// Agent/tool subprocesses inherit process.env. Keep the loaded key in this\n// process only so `env`/`ps` inside an agent workspace cannot reveal it.\ndelete process.env.NEGOTIUM_VAULT_MASTER_KEY;\n\n/** The node's single open port: runtime MCP endpoint + node API. */\nexport const NEGOTIUM_PORT = parseInt(process.env.NEGOTIUM_PORT || \"7777\", 10);\nexport const hostname = process.env.HOSTNAME || \"127.0.0.1\";\n\n// Persistent state (survives restarts, long-lived)\nexport const DATA_DIR = resolveLocalStateDir(\"NEGOTIUM_DATA_DIR\", \"data\");\nexport const LOG_DIR = resolveLocalStateDir(\"NEGOTIUM_LOG_DIR\", \"logs\");\nexport const UPLOADS_DIR = resolve(DATA_DIR, \"uploads\");\nexport const VAULT_DIR = resolve(DATA_DIR, \"vault\");\n// SESSIONS_DB_PATH env override lets tests point the DB singleton at a temp file.\nexport const SESSIONS_DB = process.env.SESSIONS_DB_PATH\n ? resolve(process.env.SESSIONS_DB_PATH)\n : resolve(DATA_DIR, \"sessions.db\");\nexport const DEBUG_FILE = resolve(DATA_DIR, \"debug-users.json\");\nexport const USERS_LOG_DIR = resolve(DATA_DIR, \"users\");\n\n// Runtime IPC queues (transient, safe to clear on restart)\n/** @deprecated Use the runtime layout name; NEGOTIUM_RUN_DIR remains a compatibility override. */\nexport const RUN_DIR = resolveLocalStateDir(\"NEGOTIUM_RUN_DIR\", \"runtime\");\nexport const RUNTIME_DIR = RUN_DIR;\nexport const PROGRESS_DIR = resolve(RUN_DIR, \"progress\");\nexport const DM_CMD_DIR = resolve(RUN_DIR, \"dm-commands\");\nexport const DM_RESP_DIR = resolve(RUN_DIR, \"dm-responses\");\nexport const SESSION_INBOX_DIR = resolve(RUN_DIR, \"session-inbox\");\nexport const SESSION_ASKS_DIR = resolve(RUN_DIR, \"session-asks\");\nexport const PLAYWRIGHT_BASE_PORT = parsePortEnv(process.env.PLAYWRIGHT_BASE_PORT, 9100);\nexport const PLAYWRIGHT_MAX_PORT = parsePortEnv(process.env.PLAYWRIGHT_MAX_PORT, 9499);\nexport const PLAYWRIGHT_PORTS_DIR = resolve(RUN_DIR, \"playwright-ports\");\nmkdirSync(STATE_DIR, { recursive: true });\nmkdirSync(DATA_DIR, { recursive: true });\nmkdirSync(UPLOADS_DIR, { recursive: true });\nmkdirSync(VAULT_DIR, { recursive: true, mode: 0o700 });\nmkdirSync(LOG_DIR, { recursive: true });\nmkdirSync(PROGRESS_DIR, { recursive: true });\nmkdirSync(DM_CMD_DIR, { recursive: true });\nmkdirSync(DM_RESP_DIR, { recursive: true });\nmkdirSync(SESSION_INBOX_DIR, { recursive: true });\nmkdirSync(SESSION_ASKS_DIR, { recursive: true });\nmkdirSync(PLAYWRIGHT_PORTS_DIR, { recursive: true });\nmkdirSync(WORKSPACE_DIR, { recursive: true });\nmkdirSync(TOPIC_WORKSPACE_DIR, { recursive: true });\nmkdirSync(SHARED_WIKI_DIR, { recursive: true });\nmkdirSync(CRON_WORKSPACE_DIR, { recursive: true });\nmkdirSync(CONTEXTS_DIR, { recursive: true });\nmkdirSync(DM_WORKSPACE_DIR, { recursive: true });\nmkdirSync(SESSION_WORKSPACE_DIR, { recursive: true });\nmkdirSync(BROWSER_DIR, { recursive: true });\nmkdirSync(BROWSER_PROFILES_DIR, { recursive: true });\nmkdirSync(BINARIES_DIR, { recursive: true });\nmkdirSync(SECRETS_DIR, { recursive: true, mode: 0o700 });\n\n/** Stale threshold for active-query state files (crash recovery) */\nexport const ACTIVE_QUERY_STALE_MS = 10 * 60 * 1000; // 10 minutes\n\nexport const AGENTS_PROMPTS_DIR = resolve(PROJECT_ROOT, \"src/prompts/agents\");\nexport const RESOURCES_DIR = resolve(PROJECT_ROOT, \"src/resources\");\n\n/** Returns process.env without CLAUDECODE, to prevent nested claude-code detection in subprocesses. */\nexport function getCleanEnv(): NodeJS.ProcessEnv {\n const env = { ...process.env };\n delete env.CLAUDECODE;\n return env;\n}\n\nexport const FILE_EXTENSIONS_REGEX =\n /(?:\\/[^\\s\"'<>|*?[\\]]+\\.(?:png|jpg|jpeg|gif|webp|svg|pdf|csv|xlsx|xls|json|txt|md|html|zip|py|js|ts|tsx|jsx|css|xml|yaml|yml|docx|pptx))/gi;\n\nexport const FILE_TAG_REGEX = /\\[FILE:(\\/[^\\]]+)\\]/gi;\n\n// Canonical Claude model IDs — update here when Anthropic releases new versions\nexport const MODEL_SONNET = \"claude-sonnet-5\";\nexport const MODEL_OPUS = \"claude-opus-5\";\nexport const MODEL_HAIKU = \"claude-haiku-4-5-20251001\";\nexport const MODEL_FABLE = \"claude-fable-5\"; // Mythos-class, announced 2026-06-09\n\n// DeepSeek V4 (released 2026-04-24). API is OpenAI-compatible at\n// https://api.deepseek.com/v1/chat/completions; thinking mode is enabled via\n// `extra_body.thinking.type` + `reasoning_effort`. Legacy `deepseek-chat` /\n// `deepseek-reasoner` are deprecated 2026-07-24.\nexport const MODEL_DEEPSEEK_V4_PRO = \"deepseek-v4-pro\";\nexport const MODEL_DEEPSEEK_V4_FLASH = \"deepseek-v4-flash\";\n\n// Agent + model defaults split by session role. FALLBACK_* is the shared base;\n// SESSION_* overrides topic + ephemeral; GATEWAY_* overrides dm + manager.\n// DEFAULT_* is accepted as a legacy alias during the env migration window.\nexport const FALLBACK_AGENT: AgentKind = resolveAgentEnv(\n \"FALLBACK_AGENT\",\n \"maestro\",\n \"DEFAULT_AGENT\",\n);\nexport const SESSION_AGENT: AgentKind = resolveAgentEnv(\"SESSION_AGENT\", FALLBACK_AGENT);\nexport const GATEWAY_AGENT: AgentKind = resolveAgentEnv(\"GATEWAY_AGENT\", FALLBACK_AGENT);\n\nexport const FALLBACK_MODEL = envText(\"FALLBACK_MODEL\") ?? envText(\"DEFAULT_MODEL\");\n\nfunction resolveModelEnv(envKey: string, agentConst: AgentKind): string | undefined {\n return envText(envKey) ?? (agentConst === FALLBACK_AGENT ? FALLBACK_MODEL : undefined);\n}\n\nexport const SESSION_MODEL = resolveModelEnv(\"SESSION_MODEL\", SESSION_AGENT);\nexport const GATEWAY_MODEL = resolveModelEnv(\"GATEWAY_MODEL\", GATEWAY_AGENT);\n\n/** Resolve the effective display/default model for a topic (session context).\n * Applies the session model override only when that role owns the agent;\n * otherwise each registry's native default stays authoritative. */\nexport function resolveDefaultModel(agent: string, registryDefaultModel: string): string {\n return agent === SESSION_AGENT && SESSION_MODEL ? SESSION_MODEL : registryDefaultModel;\n}\n\n// ── External tool binaries + media pipeline env ───────────────────\n// (src/media/* 에서 사용. 미설정 시 fallback 의미는 기존 그대로:\n// FFMPEG_BIN은 text-extractor에서 필수(undefined면 spawn 시점 실패),\n// video.ts에서는 PATH의 ffmpeg/ffprobe로 fallback.)\nexport const FFMPEG_BIN = envText(\"FFMPEG_BIN\");\nexport const FFPROBE_BIN = envText(\"FFPROBE_BIN\");\nexport const PYTHON_BIN = envText(\"PYTHON_BIN\") ?? \"python3\";\nexport const FASTER_WHISPER_WRAPPER =\n envText(\"FASTER_WHISPER_WRAPPER\") ?? resolve(PROJECT_ROOT, \"scripts/faster-whisper-wrapper.py\");\nexport const WHISPER_MODEL = envText(\"WHISPER_MODEL_FILE\") ?? \"turbo\";\nexport const TESSERACT_BIN = envText(\"TESSERACT_BIN\") ?? \"tesseract\";\nexport const PDFTOTEXT_BIN = envText(\"PDFTOTEXT_BIN\") ?? \"pdftotext\";\n\n// Max tell_session relay depth from origin user. ask_session forks reset to\n// depth=0, so this only caps tell_session chains. Override via MAX_TELL_DEPTH\n// (positive int); defaults to 20 when unset or invalid.\nconst _envMaxTellDepth = Number.parseInt(process.env.MAX_TELL_DEPTH ?? \"\", 10);\nexport const MAX_TELL_DEPTH =\n Number.isInteger(_envMaxTellDepth) && _envMaxTellDepth > 0 ? _envMaxTellDepth : 20;\n\n/** Codex CLI auth file. 호출 시점에 env를 읽는다 — 테스트가 런타임에\n * NEGOTIUM_CODEX_AUTH_FILE을 바꾸므로 모듈 로드 상수로 만들면 안 된다. */\nexport function codexAuthFilePath(): string {\n return (\n process.env.NEGOTIUM_CODEX_AUTH_FILE ||\n join(process.env.CODEX_HOME || join(homedir(), \".codex\"), \"auth.json\")\n );\n}\n\n// System defaults moved to per-agent registries\n// (`src/agents/{claude,codex}-registry.ts`). Read via\n// `getRegistry(agent).defaultModel` / `.defaultEffort`.\n\n// MCP server builders -> src/platform/mcp-config.ts\n",
7
+ "import { resolve } from \"node:path\";\n\nexport type RuntimeEnvironment = Readonly<Record<string, string | undefined>>;\n\nexport function readEnvText(env: RuntimeEnvironment, key: string): string | undefined {\n const value = env[key]?.trim();\n return value || undefined;\n}\n\nexport function parseRuntimePort(value: string | undefined, fallback: number): number {\n if (!value) return fallback;\n const port = Number.parseInt(value, 10);\n return Number.isInteger(port) && port > 0 && port <= 65_535 ? port : fallback;\n}\n\nexport function resolveRuntimeStateDir(options: {\n env: RuntimeEnvironment;\n envKey: string;\n fallbackRoot: string;\n fallbackName: string;\n}): string {\n const configured = readEnvText(options.env, options.envKey);\n return configured ? resolve(configured) : resolve(options.fallbackRoot, options.fallbackName);\n}\n\nexport function safeRuntimePathSegment(value: string, fallback: string, maxLength = 160): string {\n const cleaned = value\n .trim()\n .replace(/[^A-Za-z0-9._-]/g, \"_\")\n .replace(/^_+|_+$/g, \"\")\n .slice(0, maxLength);\n return cleaned || fallback;\n}\n",
8
+ "import pino from \"pino\";\n\nexport interface StdioLoggerOptions {\n level?: string;\n development?: boolean;\n}\n\n/**\n * Always write logs to stderr (fd 2), never stdout.\n *\n * MCP servers under `src/mcp/**` run as stdio subprocesses where stdout is the\n * JSON-RPC transport channel. A single log line on stdout corrupts the next\n * message and the MCP client closes the transport (\"Transport closed\"). The\n * main bot process is also fine with stderr — pm2 captures both streams.\n *\n * In dev mode pino spawns a `pino-pretty` worker that owns its own sink, so we\n * pass `destination: 2` through transport.options. In prod (no transport) the\n * second arg to `pino()` sets the destination directly.\n */\nexport function createStdioLogger(options: StdioLoggerOptions = {}) {\n const development = options.development ?? process.env.NODE_ENV === \"development\";\n return pino(\n {\n level: options.level ?? process.env.LOG_LEVEL ?? \"info\",\n transport: development\n ? {\n target: \"pino-pretty\",\n options: {\n colorize: true,\n translateTime: \"SYS:yyyy-mm-dd HH:MM:ss\",\n destination: 2,\n },\n }\n : undefined,\n },\n pino.destination(2),\n );\n}\n\nexport type StdioLogger = ReturnType<typeof createStdioLogger>;\n\nexport const logger = createStdioLogger();\n",
9
+ "/**\n * Common context carried through the attachment/prompt-build pipeline.\n * Used by buildPromptFromMessage and related helpers.\n */\nexport interface SessionContext {\n userId: number;\n topicName?: string;\n userDir?: string;\n sessionType?: \"dm\" | \"forum\" | \"ephemeral\" | \"manager\" | \"cron\";\n}\n\nexport interface TokenUsage {\n /** Aggregate billable input across every model call made during this turn. */\n inputTokens: number;\n outputTokens: number;\n cacheCreationInputTokens?: number;\n cacheReadInputTokens?: number;\n /** Provider-reported query cost when available. */\n costUsd?: number;\n /** Tokens occupied by the latest model call, not aggregate turn spend. */\n contextTokens?: number;\n /** Provider-reported context window for the latest model call. */\n contextWindow?: number;\n}\n\n/** Agent identifier — one of the supported AI provider backends. */\nexport type AgentKind = \"maestro\" | \"claude\" | \"codex\";\n\nexport const SUPPORTED_AGENTS: readonly AgentKind[] = [\"maestro\", \"claude\", \"codex\"] as const;\n\nexport function isAgentKind(value: unknown): value is AgentKind {\n return typeof value === \"string\" && (SUPPORTED_AGENTS as readonly string[]).includes(value);\n}\n\n/**\n * Per-agent supported reasoning efforts. Single source of truth for both the\n * `EffortLevel` type and each registry's `validEfforts` runtime list — the\n * registries import these directly so adding a value in one place\n * propagates to validation, footer rendering, and zod enums.\n *\n * Claude SDK rejects 'minimal'; Codex SDK rejects 'max'. The two sets\n * intersect on low/medium/high/xhigh. Maestro (TS port) currently piggybacks\n * on the Anthropic provider, so its efforts mirror the Claude set; this can\n * narrow per-provider once Phase 5 lands.\n *\n * 'minimal' removed from codex: Codex API rejects it when default tools\n * (image_gen, web_search) are active, making agent sessions unusable.\n */\nexport const CLAUDE_EFFORT_VALUES = [\"low\", \"medium\", \"high\", \"xhigh\", \"max\"] as const;\nexport const CODEX_EFFORT_VALUES = [\"low\", \"medium\", \"high\", \"xhigh\", \"max\"] as const;\nexport const MAESTRO_EFFORT_VALUES = [\"low\", \"medium\", \"high\", \"xhigh\", \"max\"] as const;\n\nexport type EffortLevel =\n | (typeof CLAUDE_EFFORT_VALUES)[number]\n | (typeof CODEX_EFFORT_VALUES)[number]\n | (typeof MAESTRO_EFFORT_VALUES)[number];\n\n/**\n * Runtime iteration list (used by zod enums and any callers that need to\n * loop over every accepted value). Manually ordered for readability; the\n * `satisfies` check fails the build if an entry here isn't covered by the\n * per-agent unions above.\n */\nexport const EFFORT_VALUES = [\n \"low\",\n \"medium\",\n \"high\",\n \"xhigh\",\n \"max\",\n] as const satisfies readonly EffortLevel[];\n\n/**\n * Normalized events yielded by any agent provider (claudeProvider, codexProvider).\n * The handler/event-processor consumes these without caring which backend produced them.\n *\n * `user_message` is the lone \"into-the-log\" variant — no provider yields it.\n * The query handler writes it directly to the conversation log right before\n * `runAgent()` starts, so cross-agent rollout reconstruction can pair every\n * assistant turn with the user prompt that triggered it. Consumers that only\n * react to provider output (e.g. processAgentEvent) can safely ignore it.\n */\n/**\n * Wire-safe projection of one task, carried by the `tasks` UnifiedEvent.\n *\n * This is also the on-disk shape of Otium's shared task store, so claude,\n * codex, and maestro render the same live panel from the same source of truth.\n */\nexport interface TaskSnapshot {\n id: string;\n subject: string;\n status: \"pending\" | \"in_progress\" | \"completed\";\n /** Task ids this one is blocked by; omitted when empty. */\n blockedBy?: string[];\n /** Present-continuous label for spinners, when set. */\n activeForm?: string;\n /** Owner / agent name for multi-agent runs, when set. */\n owner?: string;\n}\n\nexport type UnifiedEvent =\n | {\n type: \"user_message\";\n content: string;\n synthetic?: \"compaction\";\n /** Total ordered user submissions represented by one preempting provider turn. */\n consecutiveBatchSize?: number;\n /** Zero-based position within the ordered preemption batch. */\n consecutiveBatchIndex?: number;\n }\n | { type: \"session\"; sessionId: string }\n | {\n type: \"tool_use\";\n name: string;\n input: Record<string, unknown>;\n /** Provider-assigned id so the client can match tool_use→tool_result pairs. */\n toolUseId?: string;\n }\n | { type: \"tool_progress\"; toolName: string; elapsed: number }\n | { type: \"tool_use_summary\"; summary: string }\n // Provider reasoning/thinking summary text (Codex `reasoning` items; Claude\n // extended-thinking). Surfaced so background runs (cron/archiver) show the\n // agent's thought process, not just tool calls.\n | { type: \"reasoning\"; content: string }\n // Full task-list snapshot (replace, not delta) from Otium's shared task\n // store. Provider-native task/todo stores are not authoritative.\n | { type: \"tasks\"; tasks: TaskSnapshot[] }\n | {\n type: \"tool_result\";\n toolUseId: string;\n content: string;\n /** True when the tool call failed; absent/false means success. */\n isError?: boolean;\n metadata?: {\n truncatedForModel: boolean;\n originalBytes: number;\n returnedBytes: number;\n omittedBytes?: number;\n outputPath?: string;\n };\n }\n | { type: \"text_delta\"; content: string }\n | { type: \"text\"; content: string }\n | { type: \"result\"; content: string; stopReason: string; usage?: TokenUsage }\n | { type: \"file\"; path: string; source: string; origin: \"tag\" | \"extension\" }\n | {\n type: \"error\";\n content: string;\n usage?: TokenUsage;\n code?: \"budget_exceeded\";\n }\n | { type: \"status\"; content: string };\n\nexport interface AgentInputAttachment {\n id: string;\n type: \"image\" | \"file\" | \"audio\";\n filename: string;\n mimeType: string;\n sizeBytes: number;\n path: string;\n}\n\n/** Worker-side runtime tools proxy user-facing state back to the canonical\n * hub topic identified here. */\nexport interface PeerRuntimeBridgeContext {\n hubCellId: string;\n hostTopicId: string;\n hostQueryId: string;\n canSpawnSubagents: boolean;\n}\n\nexport interface AgentQueryOptions {\n agent: AgentKind;\n prompt: string;\n attachments?: AgentInputAttachment[];\n sessionId?: string | null;\n cwd: string;\n systemPrompt: string;\n userId?: string;\n session?: string;\n playwrightPort?: number;\n playwrightCapability?: string;\n bgBashPort?: number;\n sessionType?: \"dm\" | \"forum\" | \"ephemeral\" | \"manager\" | \"cron\";\n /** API topic id (REST/WS world). Carries per-query topic context for MCP servers. */\n topicId?: string;\n /** Direct parent topic id when this query runs inside a subagent room. */\n subagentParentTopicId?: string;\n /** API query id for the currently running turn. Used by runtime MCP tools. */\n queryId?: string;\n /** Optional wiki-memory topic id. Derived topics use their root origin here\n * while other per-topic MCP servers keep `topicId` bound to the live room. */\n wikiTopicId?: string;\n /** Whether self-config MCP may enqueue an automatic continue turn after set_* changes. */\n autoContinue?: boolean;\n /** Expose Otium-only visual panel tools for this turn. Default-deny. */\n visualTools?: boolean;\n /** Expose adapter-backed file-delivery tools for this turn. Default-deny. */\n fileDeliveryTools?: boolean;\n abortController?: AbortController;\n model?: string;\n /** Provider-side hard budget when the selected SDK supports one. */\n maxBudgetUsd?: number;\n depth?: number;\n agents?: Record<\n string,\n {\n description: string;\n prompt: string;\n model?: string;\n tools?: string[];\n maxTurns?: number;\n effort?: EffortLevel | number;\n }\n >;\n effort?: EffortLevel;\n /**\n * Per-API-call `max_tokens` ceiling on the assistant's output. Wired\n * through to the underlying provider request body for every agent\n * (claude/codex/maestro). Omit to inherit each provider SDK's per-model\n * default — for maestro that's the v0.1.21+ `getNativeMaxOutputTokens`\n * catalog (deepseek-pro=64K, kimi-k3=64K, kimi-k2.7-code=32K).\n *\n * Pass an explicit number when a specific topic / surface needs a tighter\n * latency cap or a higher ceiling for long-form generation (legal\n * report writing, multi-K Write/Edit file bodies). Pre-0.1.21 maestro\n * builds silently clamped at 4096 and truncated outputs mid-string;\n * setting this field is now the supported way to lift that ceiling.\n */\n maxTokens?: number;\n /**\n * v0.1.22+: Claude-Code-style deferred tool catalog + `ToolSearch` built-in.\n *\n * Wired straight through to `maestro-agent-sdk`'s\n * `AgentQueryOptions.enableToolSearch`. When `true`, the maestro provider\n * registers every MCP tool as deferred — schemas stay off the wire until\n * the model promotes them via `ToolSearch(\"select:Name1,Name2\")` or\n * `ToolSearch(\"keyword\")`. Active set persists across resume.\n *\n * Otium's maestro provider supplies `true` when the caller leaves this\n * option unset, because most forum turns carry enough MCP surface for the\n * reminder-token savings to outweigh the first-use `ToolSearch` round-trip.\n * Callers can still pass `false` per call when a narrow surface or\n * latency-sensitive workflow is better served by eager MCP schemas.\n *\n * No-op for claude / codex agents — they have their own deferred-tool\n * machinery owned by their respective SDKs.\n */\n enableToolSearch?: boolean;\n /**\n * Bounded tool results with the full output kept on disk.\n *\n * Wired to `maestro-agent-sdk`'s `AgentQueryOptions.toolResultTruncation`.\n * The SDK caps a string tool result, writes the untruncated bytes to a file,\n * and splices an opaque `maestro://tool-output/<id>` reference into the text\n * that the `ReadToolOutput` tool can page back through.\n *\n * The maestro provider enables it by default. Left unset, every tool result\n * — a whole-file `Read`, a wide `Grep`, a `WebFetch` of a large page —\n * entered the context at full size, and the `\"ReadToolOutput\"` entry in the\n * provider's builtin list was dead, because the SDK only registers that tool\n * when truncation is on with `saveFullOutput`.\n *\n * Pass an explicit object to tune the budget, or `{ enabled: false }` for a\n * call whose tool results must arrive whole.\n *\n * No-op for claude / codex agents — their SDKs do their own truncation.\n */\n toolResultTruncation?: {\n enabled?: boolean;\n maxBytes?: number;\n headBytes?: number;\n tailBytes?: number;\n saveFullOutput?: boolean;\n outputDir?: string;\n retentionDays?: number;\n ignoreTools?: string[];\n };\n /**\n * Claude-Code-compatible exact tool denylist. Maestro v0.1.42+ hides these\n * tools from provider schemas / ToolSearch and blocks dispatch if a stale\n * call still arrives. Claude maps this to its SDK option. Codex does not\n * support this name-based list; its provider-native multi-agent tool family\n * is disabled separately through the Codex feature config.\n */\n disallowedTools?: readonly string[];\n /**\n * Hard provider tool policy for auxiliary model calls.\n *\n * `\"none\"` removes MCP and provider-native tools before the request is\n * dispatched. `\"compaction-log\"` keeps provider-native tools disabled and\n * exposes only the host-scoped immutable log reader. Use these for untrusted\n * transcript transforms; reacting to tool events after dispatch is not a\n * security boundary.\n */\n toolPolicy?: \"none\" | \"compaction-log\";\n mcpEnabled?: string[] | null;\n peerBridge?: PeerRuntimeBridgeContext;\n mcpExtra?: Record<string, unknown>;\n /**\n * true for silent fork runs generating ask_session replies — restricts session-comm\n * outbound tools (ask/tell/abort) so the forked session can only produce text\n */\n silent?: boolean;\n}\n\n/** State file written to data/users/{userId}/active-queries/{topicId}.json while a query is running. */\nexport interface QueryState {\n topicId?: string;\n topicName?: string;\n task?: string; // first 100 chars of prompt, newlines normalized\n since: string; // ISO timestamp\n}\n",
10
+ "/** One user submission, kept intact while an interrupted turn is replaced. */\nexport interface UserTurnEnvelope {\n prompt: string;\n attachments?: string[];\n}\n\nexport function legacyUserTurnEnvelope(prompt: string, attachments?: string[]): UserTurnEnvelope {\n return attachments?.length ? { prompt, attachments } : { prompt };\n}\n\nexport function flattenUserTurnAttachments(\n messages: readonly UserTurnEnvelope[],\n): string[] | undefined {\n const attachments = messages.flatMap((message) => message.attachments ?? []);\n return attachments.length ? attachments : undefined;\n}\n\nexport function renderUserPromptBatch(prompts: readonly string[]): string {\n if (prompts.length <= 1) return prompts[0] ?? \"\";\n return [\n \"[Consecutive user messages received before an assistant response]\",\n \"\",\n ...prompts.map((prompt, index) => `${index + 1}. ${prompt}`),\n ].join(\"\\n\");\n}\n",
11
+ "/**\n * Claude rollout encoder.\n *\n * Materializes a synthetic JSONL at `~/.claude/projects/<encoded-cwd>/<sessionId>.jsonl`\n * so a subsequent `claude.query({ resume: sessionId })` continues the\n * cross-agent conversation as if it had always been native. Verified by\n * sandbox PoCs (test-7c/test-7d): the SDK accepts these without checksum\n * gating, requiring only `user`/`assistant` messages and a small per-turn\n * attachment chain captured into `agents/fixtures/claude-attachments.jsonl`.\n *\n * Tool history is folded into assistant text as `[Tool: ...]` annotations\n * (see shared.ts:extractChatPairs) — synthetic tool_use IDs across SDKs are\n * too fragile to reconstruct structurally.\n */\n\nimport { randomUUID } from \"node:crypto\";\nimport { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport {\n assertUuidLike,\n type ChatPair,\n clone,\n ensureCwdExists,\n extractChatPairs,\n FIXTURES_DIR,\n} from \"#agents/rollout/shared\";\nimport { parseJsonlText, writeJsonlFile } from \"#platform/jsonl\";\nimport { logger } from \"#platform/logger\";\nimport type { ConversationEntry } from \"#storage/conversations\";\n\ninterface ClaudeAttachments {\n deferredToolsDelta: Record<string, unknown>;\n skillListing: Record<string, unknown>;\n}\n\nlet _attachmentsCache: ClaudeAttachments | null = null;\nfunction loadClaudeAttachments(): ClaudeAttachments {\n if (_attachmentsCache) return _attachmentsCache;\n const raw = readFileSync(join(FIXTURES_DIR, \"claude-attachments.jsonl\"), \"utf8\");\n const lines = parseJsonlText<Record<string, unknown>>(raw);\n if (lines.length < 2) {\n throw new Error(\n `loadClaudeAttachments: expected >=2 entries in claude-attachments.jsonl, got ${lines.length}`,\n );\n }\n _attachmentsCache = {\n deferredToolsDelta: lines[0],\n skillListing: lines[1],\n };\n return _attachmentsCache;\n}\n\n/**\n * Version strings stamped onto synthetic rollouts so they look indistinguishable\n * from a live SDK session. These do not affect resume behavior — the SDKs do\n * not gate on them — but keeping them current avoids confusion in observability\n * tooling that scans rollout files.\n */\nconst CLAUDE_SDK_VERSION = \"2.1.126\";\nconst CLAUDE_DEFAULT_MODEL = \"claude-sonnet-5\";\nconst CLAUDE_DEFAULT_GIT_BRANCH = \"HEAD\";\n\n/**\n * Encode a directory path the way Claude SDK expects in\n * `~/.claude/projects/<encoded-cwd>/`. macOS resolves `/tmp` to\n * `/private/tmp`, mirroring what the SDK records.\n *\n * The SDK normalizes ANY non-alphanumeric character to `-` (verified\n * empirically on disk: `/Users/maestrobot/.../user_6407801418` →\n * `-Users-...-user-6407801418`, i.e. both `/` AND `_` collapse to `-`).\n * A previous implementation only replaced `/` and left `_` intact, so\n * synthetic rollouts landed at `…-user_6407801418/` while the SDK looked\n * at `…-user-6407801418/` — every `set_agent` switch surfaced as \"No\n * conversation found with session ID\" on the next message.\n */\nexport function encodeClaudeCwd(cwd: string): string {\n const realCwd = cwd.startsWith(\"/tmp/\") ? cwd.replace(/^\\/tmp\\//, \"/private/tmp/\") : cwd;\n return `-${realCwd.replaceAll(/[^a-zA-Z0-9]/g, \"-\").replace(/^-/, \"\")}`;\n}\n\nexport interface ClaudeRolloutOptions {\n /** Working directory the resumed Claude session will report. */\n cwd: string;\n /** Optional override; default = freshly generated UUIDv4. */\n sessionId?: string;\n /**\n * Pairs to encode. If omitted, derived from `entries` via extractChatPairs.\n * Pass explicit pairs when the caller has already shaped the dialogue.\n */\n pairs?: ChatPair[];\n /** When `pairs` is omitted, the source UnifiedEvent log to digest. */\n entries?: ConversationEntry[];\n /** Full provider model id stamped on synthesized assistant history. */\n model?: string;\n}\n\nexport interface ClaudeRolloutResult {\n sessionId: string;\n rolloutPath: string;\n}\n\n/**\n * Materialize a Claude rollout JSONL with the provided dialogue and place it\n * at `~/.claude/projects/<encoded-cwd>/<sessionId>.jsonl` so a subsequent\n * `claude.query({ resume: sessionId })` will continue the conversation.\n */\nexport function writeClaudeRollout(opts: ClaudeRolloutOptions): ClaudeRolloutResult {\n const sessionId = opts.sessionId ?? randomUUID();\n assertUuidLike(\"sessionId\", sessionId);\n ensureCwdExists(opts.cwd);\n const pairs = opts.pairs ?? extractChatPairs(opts.entries ?? []);\n const cwdReal = opts.cwd.startsWith(\"/tmp/\")\n ? opts.cwd.replace(/^\\/tmp\\//, \"/private/tmp/\")\n : opts.cwd;\n\n const lines: unknown[] = [];\n const ts = () => new Date().toISOString();\n let lastUuid: string | null = null;\n\n // Queue-operation noise that the live SDK records around each turn. Not\n // strictly required for resume but mirrors what the SDK itself writes,\n // keeping the synthetic file indistinguishable.\n lines.push({ type: \"queue-operation\", operation: \"enqueue\", timestamp: ts(), sessionId });\n lines.push({ type: \"queue-operation\", operation: \"dequeue\", timestamp: ts(), sessionId });\n\n // Per-turn attachment chain captured from a real Claude rollout. claude SDK\n // emits `deferred_tools_delta` followed by `skill_listing` immediately after\n // every user message, building a parentUuid chain user → att1 → att2 →\n // assistant. PoC-7d preserved this shape; replaying it keeps the resumed\n // session indistinguishable from a native one.\n const attachments = loadClaudeAttachments();\n\n for (const pair of pairs) {\n const userUuid = randomUUID();\n lines.push({\n parentUuid: lastUuid,\n isSidechain: false,\n promptId: randomUUID(),\n type: \"user\",\n message: { role: \"user\", content: [{ type: \"text\", text: pair.userText }] },\n uuid: userUuid,\n timestamp: ts(),\n permissionMode: \"bypassPermissions\",\n userType: \"external\",\n entrypoint: \"sdk-ts\",\n cwd: cwdReal,\n sessionId,\n version: CLAUDE_SDK_VERSION,\n gitBranch: CLAUDE_DEFAULT_GIT_BRANCH,\n });\n\n // Attachment 1: deferred_tools_delta — chain from user.\n const att1Uuid = randomUUID();\n const att1 = clone(attachments.deferredToolsDelta);\n (att1 as Record<string, unknown>).parentUuid = userUuid;\n (att1 as Record<string, unknown>).uuid = att1Uuid;\n (att1 as Record<string, unknown>).timestamp = ts();\n (att1 as Record<string, unknown>).sessionId = sessionId;\n (att1 as Record<string, unknown>).cwd = cwdReal;\n lines.push(att1);\n\n // Attachment 2: skill_listing — chain from att1.\n const att2Uuid = randomUUID();\n const att2 = clone(attachments.skillListing);\n (att2 as Record<string, unknown>).parentUuid = att1Uuid;\n (att2 as Record<string, unknown>).uuid = att2Uuid;\n (att2 as Record<string, unknown>).timestamp = ts();\n (att2 as Record<string, unknown>).sessionId = sessionId;\n (att2 as Record<string, unknown>).cwd = cwdReal;\n lines.push(att2);\n\n const assistantUuid = randomUUID();\n lines.push({\n parentUuid: att2Uuid,\n isSidechain: false,\n message: {\n model: opts.model ?? CLAUDE_DEFAULT_MODEL,\n id: `msg_${randomUUID().replace(/-/g, \"\").slice(0, 24)}`,\n type: \"message\",\n role: \"assistant\",\n content: [{ type: \"text\", text: pair.assistantText }],\n stop_reason: \"end_turn\",\n stop_sequence: null,\n stop_details: null,\n usage: {\n input_tokens: 0,\n cache_creation_input_tokens: 0,\n cache_read_input_tokens: 0,\n output_tokens: 0,\n server_tool_use: { web_search_requests: 0, web_fetch_requests: 0 },\n service_tier: \"standard\",\n cache_creation: { ephemeral_1h_input_tokens: 0, ephemeral_5m_input_tokens: 0 },\n inference_geo: \"\",\n iterations: [],\n speed: \"standard\",\n },\n diagnostics: null,\n },\n requestId: `req_${randomUUID().replace(/-/g, \"\").slice(0, 22)}`,\n type: \"assistant\",\n uuid: assistantUuid,\n timestamp: ts(),\n userType: \"external\",\n entrypoint: \"sdk-ts\",\n cwd: cwdReal,\n sessionId,\n version: CLAUDE_SDK_VERSION,\n gitBranch: CLAUDE_DEFAULT_GIT_BRANCH,\n });\n lastUuid = assistantUuid;\n }\n\n const projectsDir = join(homedir(), \".claude\", \"projects\", encodeClaudeCwd(opts.cwd));\n const path = join(projectsDir, `${sessionId}.jsonl`);\n writeJsonlFile(path, lines);\n logger.info(\n { sessionId, path, pairs: pairs.length },\n \"writeClaudeRollout: synthetic rollout placed\",\n );\n return { sessionId, rolloutPath: path };\n}\n\n/**\n * Remove the latest poisoned thinking turn and everything after it from the\n * session JSONL.\n *\n * When a turn ends with stop_reason=\"max_tokens\" while extended thinking is\n * active, the Claude CLI writes the truncated thinking block verbatim to the\n * rollout file. The Anthropic API rejects any subsequent resume that replays\n * this incomplete block with 400 \"thinking/redacted_thinking blocks cannot be\n * modified\". Dropping the entire poisoned turn (user entry + attachments +\n * truncated assistant) leaves the JSONL in a clean state so the next\n * claude.query({ resume }) can proceed without a 400.\n *\n * Returns true when the JSONL was found and repaired, false otherwise\n * (file missing, no poisoned assistant turn found, I/O error). Error-path\n * callers fall back to clearing the session ID when false is returned.\n */\nexport function repairPoisonedRollout(sessionId: string, cwd: string): boolean {\n try {\n const path = join(homedir(), \".claude\", \"projects\", encodeClaudeCwd(cwd), `${sessionId}.jsonl`);\n if (!existsSync(path)) return false;\n\n const lines = readFileSync(path, \"utf8\")\n .split(\"\\n\")\n .filter((l) => l.trim());\n\n // Walk backwards to find the latest assistant turn that actually contains\n // the poisoned shape: max_tokens plus a thinking/redacted_thinking block.\n // A resume failure can append a fresh user entry after the poisoned turn;\n // trimming the last user would remove only the retry and leave the bad\n // assistant in place.\n let poisonedAssistantIdx = -1;\n for (let i = lines.length - 1; i >= 0; i--) {\n const entry = parseClaudeRolloutLine(lines[i]);\n if (entry && isPoisonedAssistantEntry(entry)) {\n poisonedAssistantIdx = i;\n break;\n }\n }\n\n if (poisonedAssistantIdx < 0) {\n logger.warn({ sessionId, path }, \"repairPoisonedRollout: no poisoned assistant entry found\");\n return false;\n }\n\n let turnStartIdx = -1;\n for (let i = poisonedAssistantIdx - 1; i >= 0; i--) {\n const entry = parseClaudeRolloutLine(lines[i]);\n if (entry?.type === \"user\") {\n turnStartIdx = i;\n break;\n }\n }\n\n if (turnStartIdx < 0) {\n logger.warn(\n { sessionId, path, poisonedAssistantIdx },\n \"repairPoisonedRollout: poisoned assistant has no preceding user entry\",\n );\n return false;\n }\n\n const kept = lines.slice(0, turnStartIdx);\n writeFileSync(path, kept.length ? `${kept.join(\"\\n\")}\\n` : \"\");\n logger.warn(\n {\n sessionId,\n path,\n poisonedAssistantIdx,\n turnStartIdx,\n droppedEntries: lines.length - turnStartIdx,\n keptEntries: kept.length,\n },\n \"repairPoisonedRollout: truncated turn removed from rollout JSONL\",\n );\n return true;\n } catch (err) {\n logger.warn({ err, sessionId, cwd }, \"repairPoisonedRollout: I/O error\");\n return false;\n }\n}\n\ntype ClaudeRolloutEntry = {\n type?: string;\n message?: {\n stop_reason?: string | null;\n content?: unknown;\n };\n};\n\nfunction parseClaudeRolloutLine(line: string): ClaudeRolloutEntry | null {\n try {\n return JSON.parse(line) as ClaudeRolloutEntry;\n } catch {\n return null;\n }\n}\n\nfunction isPoisonedAssistantEntry(entry: ClaudeRolloutEntry): boolean {\n if (entry.type !== \"assistant\") return false;\n if (entry.message?.stop_reason !== \"max_tokens\") return false;\n const content = entry.message.content;\n if (!Array.isArray(content)) return false;\n return content.some((block) => {\n if (!block || typeof block !== \"object\") return false;\n const type = (block as { type?: unknown }).type;\n return type === \"thinking\" || type === \"redacted_thinking\";\n });\n}\n",
12
+ "import {\n appendFileSync,\n closeSync,\n fsyncSync,\n mkdirSync,\n openSync,\n readFileSync,\n renameSync,\n statSync,\n unlinkSync,\n writeFileSync,\n} from \"node:fs\";\nimport { dirname } from \"node:path\";\nimport { safeUnlink } from \"#platform/file-utils\";\n\nexport function readJsonlLines(filePath: string): string[] {\n return readFileSync(filePath, \"utf-8\").trim().split(\"\\n\").filter(Boolean);\n}\n\n/**\n * Parse a JSONL string (one JSON value per line) into an array of `T`.\n * Throws on malformed lines — use when a corrupt fixture/log should fail\n * loudly rather than silently drop entries (paired with `readJsonlLines`'\n * resilient counterpart for live data streams).\n */\nexport function parseJsonlText<T = unknown>(raw: string): T[] {\n return raw\n .trim()\n .split(\"\\n\")\n .filter(Boolean)\n .map((line) => JSON.parse(line) as T);\n}\n\n/**\n * Read and JSON-parse a file. Returns null if the file is missing or contains\n * invalid JSON. Use when a missing/corrupt file should fall through to a\n * default rather than throw.\n */\nexport function readJsonFile<T = unknown>(filePath: string): T | null {\n try {\n return JSON.parse(readFileSync(filePath, \"utf-8\")) as T;\n } catch {\n return null;\n }\n}\n\n/** Atomically replace a JSON file and fsync the new contents before rename. */\nexport function writeJsonFileAtomic(filePath: string, value: unknown): void {\n const dir = dirname(filePath);\n mkdirSync(dir, { recursive: true });\n const tmpPath = `${filePath}.tmp-${process.pid}-${Date.now()}-${Math.random()\n .toString(16)\n .slice(2)}`;\n let fd: number | null = null;\n try {\n fd = openSync(tmpPath, \"wx\", 0o600);\n writeFileSync(fd, JSON.stringify(value, null, 2));\n fsyncSync(fd);\n closeSync(fd);\n fd = null;\n renameSync(tmpPath, filePath);\n fsyncDirectoryBestEffort(dir);\n } catch (err) {\n if (fd !== null) {\n try {\n closeSync(fd);\n } catch {}\n }\n safeUnlink(tmpPath);\n throw err;\n }\n}\n\n// --- Cross-process append lock ---\n// POSIX `O_APPEND` is only atomic when the write payload fits in PIPE_BUF\n// (Linux 4096, macOS 512). MCP servers and the bot run as separate\n// processes that all `appendFileSync` to shared inbox/outbox files; a long\n// `tell_session` prompt or large `ask_session` reply is comfortably above\n// PIPE_BUF, and a concurrent append from another process can interleave at\n// the byte level — the result fails JSON parse and the entire entry is\n// silently dropped by `parseOutboxLine`.\n//\n// Mitigation: a sidecar `<filePath>.lock` created with `O_EXCL` serializes\n// every append at the OS level. Lock is held for the duration of one\n// `appendFileSync`, so the contention window is microseconds. Stale locks\n// (process crashed mid-write) are detected via mtime and forcibly removed\n// after `LOCK_STALE_MS`.\n//\n// When the lock still cannot be acquired within `LOCK_TIMEOUT_MS`, the append\n// FAILS. It used to fall through to an unlocked `appendFileSync` on the theory\n// that a possibly-interleaved entry beats a dropped one — but an interleaved\n// write is exactly the corruption the lock exists to prevent, it can damage a\n// neighbouring well-formed entry as well as its own, and `parseOutboxLine`\n// discards the wreckage later and far from the cause. The caller was told the\n// write succeeded. Failing loudly lets each caller choose: surface the error to\n// its client, or log and continue.\n//\n// The timeout MUST outlast the staleness threshold. A writer killed while\n// holding the lock leaves the file behind, and only the mtime check reclaims\n// it. With a timeout shorter than `LOCK_STALE_MS` every append issued in the\n// first few seconds after such a crash gave up *before* the reclaim could fire\n// — measured as a ~3.5s window in which every append to that file failed, all\n// of which the pre-throw fallback used to deliver. Waiting past the staleness\n// threshold means a dead holder is always reclaimed rather than waited out, so\n// a timeout now means a *live* holder has been stuck for over five seconds,\n// which is a genuine fault worth reporting.\nconst LOCK_SUFFIX = \".lock\";\nconst LOCK_RETRY_MS = 5;\nconst DEFAULT_LOCK_STALE_MS = 5000;\n/** Headroom so a waiter never gives up exactly as the reclaim becomes due. */\nconst LOCK_TIMEOUT_HEADROOM_MS = 1500;\n\n/**\n * Staleness threshold, overridable so tests can exercise the timeout path\n * without blocking a real five seconds.\n *\n * Read per call rather than captured at import: the constants are consulted\n * once per append, which is nothing next to the file I/O that follows, and a\n * module-level snapshot could not be adjusted by a test that imports this\n * module transitively.\n */\nfunction lockStaleMs(): number {\n const raw = Number.parseInt(process.env.NEGOTIUM_JSONL_LOCK_STALE_MS ?? \"\", 10);\n return Number.isFinite(raw) && raw > 0 ? raw : DEFAULT_LOCK_STALE_MS;\n}\n\n/** Always > `lockStaleMs()`, so a dead holder is reclaimed rather than waited out. */\nfunction lockTimeoutMs(): number {\n return lockStaleMs() + LOCK_TIMEOUT_HEADROOM_MS;\n}\nconst LOCK_SLEEP = new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));\n\n/**\n * The append lock could not be acquired, so nothing was written.\n *\n * Distinguishable from an I/O error so callers can retry, degrade, or report\n * contention specifically. Nothing was appended when this is thrown.\n */\nexport class JsonlLockTimeoutError extends Error {\n constructor(\n readonly filePath: string,\n readonly timeoutMs: number,\n ) {\n super(`jsonl append lock busy after ${timeoutMs}ms; nothing written to ${filePath}`);\n this.name = \"JsonlLockTimeoutError\";\n }\n}\n\n/** Synchronous, non-spinning sleep supported by both Bun and Node MCP workers. */\nfunction sleepForAppendLock(ms: number): void {\n Atomics.wait(LOCK_SLEEP, 0, 0, ms);\n}\n\nfunction tryAcquireAppendLock(lockPath: string): boolean {\n try {\n closeSync(openSync(lockPath, \"wx\")); // O_CREAT | O_EXCL — atomic\n return true;\n } catch (e) {\n if ((e as NodeJS.ErrnoException).code !== \"EEXIST\") throw e;\n return false;\n }\n}\n\nfunction isStaleLock(lockPath: string): boolean {\n try {\n return Date.now() - statSync(lockPath).mtimeMs > lockStaleMs();\n } catch {\n return false;\n }\n}\n\n/**\n * Append a JSON-encoded entry + newline to a JSONL file. Ensures the parent\n * directory exists and serializes concurrent multi-process appends through a\n * sidecar lock so payloads larger than PIPE_BUF do not interleave.\n *\n * The drainer side (`outbox/file-ops.ts`) claims the file via atomic rename\n * and handles recovery of leftover `.processing` files from crashes.\n */\nexport function appendJsonlEntry(filePath: string, entry: unknown): void {\n appendJsonlLine(filePath, `${JSON.stringify(entry)}\\n`);\n}\n\n/**\n * Append an already-serialized JSONL line (must end with \"\\n\") under the\n * same cross-process append lock as `appendJsonlEntry`. Use when you\n * want to write back a raw line **exactly** — e.g. flusher tail-writeback\n * preserving lines that current parser can't decode, so a future parser\n * release still sees them.\n */\nexport function appendJsonlLine(filePath: string, line: string): void {\n mkdirSync(dirname(filePath), { recursive: true });\n const lockPath = `${filePath}${LOCK_SUFFIX}`;\n const payload = line.endsWith(\"\\n\") ? line : `${line}\\n`;\n\n let acquired = tryAcquireAppendLock(lockPath);\n // Pre-check: if the existing lock is already stale (writer crashed before\n // unlinking), reclaim it before sleeping. Saves the entire retry budget\n // for the common stale-leftover case.\n if (!acquired && isStaleLock(lockPath)) {\n safeUnlink(lockPath);\n acquired = tryAcquireAppendLock(lockPath);\n }\n if (!acquired) {\n const start = Date.now();\n const timeoutMs = lockTimeoutMs();\n while (!acquired && Date.now() - start < timeoutMs) {\n // Codex launches built-in stdio MCPs under Node+tsx while the runtime\n // itself uses Bun. Atomics.wait gives both processes a blocking sleep\n // without a CPU-spinning fallback or a Bun-only global.\n sleepForAppendLock(LOCK_RETRY_MS);\n acquired = tryAcquireAppendLock(lockPath);\n // Recheck staleness inside the loop so a writer that crashes mid-wait\n // doesn't leave us spinning the whole timeout.\n if (!acquired && isStaleLock(lockPath)) {\n safeUnlink(lockPath);\n acquired = tryAcquireAppendLock(lockPath);\n }\n }\n }\n\n if (!acquired) throw new JsonlLockTimeoutError(filePath, lockTimeoutMs());\n\n try {\n appendFileSync(filePath, payload);\n } finally {\n safeUnlink(lockPath);\n }\n}\n\n/** Overwrite a JSONL file with the given entries. Trailing newline included. */\nexport function writeJsonlFile(filePath: string, entries: readonly unknown[]): void {\n const dir = dirname(filePath);\n mkdirSync(dir, { recursive: true });\n const tmpPath = `${filePath}.tmp-${process.pid}-${Date.now()}-${Math.random()\n .toString(16)\n .slice(2)}`;\n const payload = `${entries.map((e) => JSON.stringify(e)).join(\"\\n\")}\\n`;\n let fd: number | null = null;\n try {\n fd = openSync(tmpPath, \"w\");\n writeFileSync(fd, payload);\n fsyncSync(fd);\n closeSync(fd);\n fd = null;\n renameSync(tmpPath, filePath);\n fsyncDirectoryBestEffort(dir);\n } catch (err) {\n if (fd !== null) {\n try {\n closeSync(fd);\n } catch {}\n }\n try {\n unlinkSync(tmpPath);\n } catch {}\n throw err;\n }\n}\n\nfunction fsyncDirectoryBestEffort(dir: string): void {\n let fd: number | null = null;\n try {\n fd = openSync(dir, \"r\");\n fsyncSync(fd);\n } catch {\n // Directory fsync is not portable across every runtime/filesystem. The\n // file fsync + rename above is the important integrity boundary; this is\n // best-effort durability for the directory entry.\n } finally {\n if (fd !== null) {\n try {\n closeSync(fd);\n } catch {}\n }\n }\n}\n",
13
+ "import { unlinkSync } from \"node:fs\";\nimport { logger } from \"#platform/logger\";\n\nexport interface SafeUnlinkHost {\n unlink(path: string): void;\n warn(context: { err: unknown; path: string }, message: string): void;\n}\n\nexport type SafeUnlink = (path: string, warnLabel?: string) => void;\n\n/** Create an isolated best-effort unlink helper using caller-owned I/O and logging. */\nexport function createSafeUnlink(host: SafeUnlinkHost): SafeUnlink {\n return (path, warnLabel) => {\n try {\n host.unlink(path);\n } catch (e) {\n if ((e as NodeJS.ErrnoException)?.code === \"ENOENT\") return;\n if (warnLabel) host.warn({ err: e, path }, warnLabel);\n }\n };\n}\n\nconst defaultSafeUnlink = createSafeUnlink({\n unlink: unlinkSync,\n warn: (context, message) => logger.warn(context, message),\n});\n\n/**\n * Best-effort unlink. ENOENT is always swallowed (the file is already gone).\n * Other errors are silent unless `warnLabel` is provided, in which case they\n * are logged at warn level with `{ err, path }` context.\n */\nexport function safeUnlink(path: string, warnLabel?: string): void {\n defaultSafeUnlink(path, warnLabel);\n}\n",
14
+ "/**\n * Codex rollout encoder.\n *\n * Materializes a synthetic JSONL at\n * `~/.codex/sessions/<yyyy>/<mm>/<dd>/rollout-<ts>-<threadId>.jsonl` so a\n * subsequent `codex.resumeThread(threadId)` continues the cross-agent\n * conversation as if it had always been native. Verified by sandbox PoC\n * test-7c: the SDK accepts these without checksum gating, requiring only the\n * captured 5-entry SDK shell (`agents/fixtures/codex-shell.jsonl`) plus\n * synthesized `response_item`/`event_msg` pairs per turn.\n *\n * Tool history is folded into assistant text as `[Tool: ...]` annotations\n * (see shared.ts:extractChatPairs). Native same-agent forks use App Server's\n * `thread/fork`; this encoder remains the fallback and cross-agent bridge,\n * where synthetic tool_use IDs are too fragile to reconstruct structurally.\n */\n\nimport { randomBytes } from \"node:crypto\";\nimport { existsSync, readFileSync, realpathSync, statSync, unlinkSync } from \"node:fs\";\nimport { basename, dirname, join, resolve } from \"node:path\";\nimport { hostedCodexHomePath } from \"#agents/execution-host\";\nimport {\n assertUuidLike,\n type ChatPair,\n clone,\n ensureCwdExists,\n extractChatPairs,\n FIXTURES_DIR,\n} from \"#agents/rollout/shared\";\nimport { parseJsonlText, writeJsonlFile } from \"#platform/jsonl\";\nimport { logger } from \"#platform/logger\";\nimport type { ConversationEntry } from \"#storage/conversations\";\nimport type { EffortLevel } from \"#types\";\n\ninterface CodexShell {\n sessionMeta: Record<string, unknown>;\n taskStarted: Record<string, unknown>;\n developerSetup: Record<string, unknown>;\n envContext: Record<string, unknown>;\n turnContext: Record<string, unknown>;\n}\n\nfunction codexSessionsDir(): string {\n return join(hostedCodexHomePath(), \"sessions\");\n}\n\nlet _shellCache: CodexShell | null = null;\nfunction loadCodexShell(): CodexShell {\n if (_shellCache) return _shellCache;\n const raw = readFileSync(join(FIXTURES_DIR, \"codex-shell.jsonl\"), \"utf8\");\n const lines = parseJsonlText<Record<string, unknown>>(raw);\n if (lines.length < 5) {\n throw new Error(\n `loadCodexShell: expected >=5 entries in codex-shell.jsonl, got ${lines.length}`,\n );\n }\n _shellCache = {\n sessionMeta: lines[0],\n taskStarted: lines[1],\n developerSetup: lines[2],\n envContext: lines[3],\n turnContext: lines[4],\n };\n return _shellCache;\n}\n\n/** UUIDv7 (Codex thread_id format). */\nfunction uuidv7(): string {\n const ts = Date.now();\n const tsHex = ts.toString(16).padStart(12, \"0\");\n const rand = randomBytes(10);\n rand[0] = (rand[0] & 0x0f) | 0x70; // version 7\n rand[2] = (rand[2] & 0x3f) | 0x80; // variant\n return [\n tsHex.slice(0, 8),\n tsHex.slice(8, 12),\n rand.slice(0, 2).toString(\"hex\"),\n rand.slice(2, 4).toString(\"hex\"),\n rand.slice(4, 10).toString(\"hex\"),\n ].join(\"-\");\n}\n\n/** Replace captured developer metadata with the policy used for resumed turns. */\nfunction patchDeveloperSetup(developerSetup: Record<string, unknown>): void {\n const payload = developerSetup.payload as Record<string, unknown> | undefined;\n if (!payload) return;\n payload.content = [\n {\n type: \"input_text\",\n text: [\n \"<permissions instructions>\",\n \"Filesystem sandboxing is disabled for this runtime turn (`danger-full-access`).\",\n \"Approval policy is `never`.\",\n \"</permissions instructions>\",\n ].join(\"\\n\"),\n },\n ];\n}\n\n/** Mutate captured `<environment_context>` fields to the current runtime. */\nfunction patchEnvContext(\n envContext: Record<string, unknown>,\n cwd: string,\n currentDate: string,\n timezone: string,\n): void {\n const payload = envContext.payload as Record<string, unknown> | undefined;\n if (!payload) return;\n const content = payload.content as Array<Record<string, unknown>> | undefined;\n if (!Array.isArray(content)) return;\n for (const block of content) {\n if (block.type === \"input_text\" && typeof block.text === \"string\") {\n block.text = block.text\n .replace(/<cwd>[^<]*<\\/cwd>/, `<cwd>${cwd}</cwd>`)\n .replace(\n /<current_date>[^<]*<\\/current_date>/,\n `<current_date>${currentDate}</current_date>`,\n )\n .replace(/<timezone>[^<]*<\\/timezone>/, `<timezone>${timezone}</timezone>`);\n }\n }\n}\n\nexport interface CodexRolloutOptions {\n /** Working directory the resumed Codex thread will report. */\n cwd: string;\n /** Optional override; default = freshly generated UUIDv7. */\n threadId?: string;\n /** Override extracted pairs. */\n pairs?: ChatPair[];\n /** Source UnifiedEvent log when `pairs` is omitted. */\n entries?: ConversationEntry[];\n /** Effective model/effort that Codex will use when this thread is resumed. */\n model?: string;\n effort?: EffortLevel;\n}\n\nexport interface CodexRolloutResult {\n threadId: string;\n rolloutPath: string;\n}\n\nexport interface CodexContextUsage {\n contextTokens: number;\n contextWindow: number;\n}\n\nexport interface CodexPatchChangePreview {\n path: string;\n before?: string;\n after?: string;\n diffPreview?: string;\n}\n\nexport interface CodexPatchPreview {\n callId: string;\n changes: CodexPatchChangePreview[];\n}\n\nfunction canonicalFilePath(path: string): string {\n const absolute = resolve(path);\n try {\n return realpathSync(absolute);\n } catch {\n try {\n return join(realpathSync(dirname(absolute)), basename(absolute));\n } catch {\n return absolute;\n }\n }\n}\n\nfunction changedPatchLines(value: string): Omit<CodexPatchChangePreview, \"path\"> {\n const removed: string[] = [];\n const added: string[] = [];\n const diffPreview: string[] = [];\n let oldLine = 0;\n let newLine = 0;\n let sawHunk = false;\n for (const line of value.split(\"\\n\")) {\n const hunk = /^@@ -(\\d+)(?:,\\d+)? \\+(\\d+)(?:,\\d+)? @@/.exec(line);\n if (hunk) {\n if (sawHunk) diffPreview.push(\"…\");\n sawHunk = true;\n oldLine = Number.parseInt(hunk[1] ?? \"0\", 10);\n newLine = Number.parseInt(hunk[2] ?? \"0\", 10);\n continue;\n }\n if (!sawHunk && (line.startsWith(\"--- \") || line.startsWith(\"+++ \"))) continue;\n if (line.startsWith(\"\\\\ No newline\")) continue;\n if (line.startsWith(\"-\")) {\n removed.push(line.slice(1));\n diffPreview.push(`${oldLine} -${line.slice(1)}`);\n oldLine += 1;\n continue;\n }\n if (line.startsWith(\"+\")) {\n added.push(line.slice(1));\n diffPreview.push(`${newLine} +${line.slice(1)}`);\n newLine += 1;\n continue;\n }\n if (line.startsWith(\" \")) {\n diffPreview.push(`${newLine} ${line.slice(1)}`);\n oldLine += 1;\n newLine += 1;\n }\n }\n return {\n ...(removed.length > 0 ? { before: removed.join(\"\\n\") } : {}),\n ...(added.length > 0 ? { after: added.join(\"\\n\") } : {}),\n ...(diffPreview.length > 0 ? { diffPreview: diffPreview.join(\"\\n\") } : {}),\n };\n}\n\n/**\n * Extract the newest native apply_patch result matching a Codex file_change.\n *\n * The public SDK intentionally reduces file changes to path + kind, while the\n * native rollout keeps the exact unified diff in patch_apply_end. Reading that\n * payload preserves the real per-edit +/- lines even when the topic cwd itself\n * is not a Git repository.\n */\nexport function extractLatestCodexPatchPreview(\n jsonl: string,\n expectedPaths: string[],\n consumedCallIds: ReadonlySet<string> = new Set(),\n expectedCallId?: string,\n): CodexPatchPreview | undefined {\n const expected = expectedPaths.map(canonicalFilePath);\n const lines = jsonl.trimEnd().split(\"\\n\");\n for (let index = lines.length - 1; index >= 0; index -= 1) {\n try {\n const entry = JSON.parse(lines[index] ?? \"\") as {\n type?: string;\n payload?: {\n type?: string;\n call_id?: string;\n changes?: Record<\n string,\n { type?: string; unified_diff?: string; content?: string; move_path?: string | null }\n >;\n };\n };\n if (entry.type !== \"event_msg\" || entry.payload?.type !== \"patch_apply_end\") continue;\n const callId = entry.payload.call_id;\n const rawChanges = entry.payload.changes;\n if (\n !callId ||\n consumedCallIds.has(callId) ||\n (expectedCallId !== undefined && callId !== expectedCallId) ||\n !rawChanges\n ) {\n continue;\n }\n\n const entries = Object.entries(rawChanges);\n const matched = expected.map((path) =>\n entries.find(([candidate]) => canonicalFilePath(candidate) === path),\n );\n const complete = matched.filter(\n (change): change is NonNullable<typeof change> => change !== undefined,\n );\n if (complete.length !== expected.length) continue;\n\n return {\n callId,\n changes: complete.map(([path, change]) => {\n if (typeof change.unified_diff === \"string\") {\n return { path, ...changedPatchLines(change.unified_diff) };\n }\n const content =\n typeof change.content === \"string\" ? change.content.replace(/\\n$/, \"\") : undefined;\n return {\n path,\n ...(change.type === \"delete\" && content !== undefined ? { before: content } : {}),\n ...(change.type === \"add\" && content !== undefined ? { after: content } : {}),\n };\n }),\n };\n } catch {\n // A concurrently appended final line may be incomplete; keep scanning.\n }\n }\n return undefined;\n}\n\nexport function extractCodexPatchCallIds(jsonl: string): string[] {\n const callIds: string[] = [];\n for (const line of jsonl.trimEnd().split(\"\\n\")) {\n try {\n const entry = JSON.parse(line) as {\n type?: string;\n payload?: { type?: string; call_id?: string };\n };\n if (\n entry.type === \"event_msg\" &&\n entry.payload?.type === \"patch_apply_end\" &&\n typeof entry.payload.call_id === \"string\"\n ) {\n callIds.push(entry.payload.call_id);\n }\n } catch {\n // A concurrently appended final line may be incomplete.\n }\n }\n return callIds;\n}\n\n/** List native patch calls that already existed before a resumed turn. */\nexport function readCodexPatchCallIds(threadId: string): string[] {\n const path = latestCodexRolloutPath(threadId);\n if (!path) return [];\n try {\n return extractCodexPatchCallIds(readFileSync(path, \"utf8\"));\n } catch (error) {\n logger.debug({ error, threadId }, \"codex patch ids: rollout read failed\");\n return [];\n }\n}\n\n/** Resolve a thread's newest native apply_patch preview. */\nexport function readLatestCodexPatchPreview(\n threadId: string,\n expectedPaths: string[],\n consumedCallIds: ReadonlySet<string> = new Set(),\n expectedCallId?: string,\n): CodexPatchPreview | undefined {\n const path = latestCodexRolloutPath(threadId);\n if (!path) return undefined;\n try {\n return extractLatestCodexPatchPreview(\n readFileSync(path, \"utf8\"),\n expectedPaths,\n consumedCallIds,\n expectedCallId,\n );\n } catch (error) {\n logger.debug({ error, threadId }, \"codex patch preview: rollout read failed\");\n return undefined;\n }\n}\n\n/** Read the latest per-request context measurement from a Codex rollout. */\nexport function extractLatestCodexContextUsage(jsonl: string): CodexContextUsage | undefined {\n const lines = jsonl.trimEnd().split(\"\\n\");\n for (let index = lines.length - 1; index >= 0; index -= 1) {\n try {\n const entry = JSON.parse(lines[index] ?? \"\") as {\n type?: string;\n payload?: {\n type?: string;\n info?: {\n last_token_usage?: { total_tokens?: number };\n model_context_window?: number;\n };\n };\n };\n if (entry.type !== \"event_msg\" || entry.payload?.type !== \"token_count\") continue;\n const contextTokens = entry.payload.info?.last_token_usage?.total_tokens;\n const contextWindow = entry.payload.info?.model_context_window;\n if (\n typeof contextTokens === \"number\" &&\n Number.isFinite(contextTokens) &&\n contextTokens >= 0 &&\n typeof contextWindow === \"number\" &&\n Number.isFinite(contextWindow) &&\n contextWindow > 0\n ) {\n return { contextTokens, contextWindow };\n }\n } catch {\n // A concurrently appended final line may be incomplete; keep scanning.\n }\n }\n return undefined;\n}\n\n/** Resolve a thread's current rollout and return its latest context measurement. */\nexport function readLatestCodexContextUsage(threadId: string): CodexContextUsage | undefined {\n const path = latestCodexRolloutPath(threadId);\n if (!path) return undefined;\n try {\n return extractLatestCodexContextUsage(readFileSync(path, \"utf8\"));\n } catch (error) {\n logger.debug({ error, threadId }, \"codex context usage: rollout read failed\");\n return undefined;\n }\n}\n\n/**\n * Old and metadata-free Codex rollouts resume as native multi-agent v1 even\n * when the feature flag is false. Rewrite their runtime metadata in place so\n * the same thread can resume without losing provider conversation history.\n */\nexport function migrateCodexRolloutNativeMultiAgentMetadata(threadId: string): boolean {\n const path = latestCodexRolloutPath(threadId);\n if (!path) return false;\n try {\n const entries = parseJsonlText<{\n type?: string;\n payload?: Record<string, unknown>;\n }>(readFileSync(path, \"utf8\"));\n let changed = false;\n for (const entry of entries) {\n if (entry.type !== \"session_meta\" && entry.type !== \"turn_context\") continue;\n if (!entry.payload) entry.payload = {};\n if (entry.payload.multi_agent_version !== \"disabled\") {\n entry.payload.multi_agent_version = \"disabled\";\n changed = true;\n }\n }\n if (changed) {\n writeJsonlFile(path, entries);\n logger.info({ threadId, path }, \"codex rollout native multi-agent metadata disabled\");\n }\n return changed;\n } catch (error) {\n logger.error({ error, threadId, path }, \"codex rollout native multi-agent migration failed\");\n throw new Error(`Failed to migrate Codex rollout '${threadId}'`, { cause: error });\n }\n}\n\nexport function latestCodexRolloutPath(threadId: string): string | undefined {\n const sessionsDir = codexSessionsDir();\n const candidates: string[] = [];\n const buckets = candidateDateBuckets(threadId);\n try {\n if (buckets) {\n for (const bucket of buckets) {\n const dir = join(sessionsDir, bucket);\n if (!existsSync(dir)) continue;\n const glob = new Bun.Glob(`rollout-*-${threadId}.jsonl`);\n for (const rel of glob.scanSync({ cwd: dir, onlyFiles: true })) {\n candidates.push(join(dir, rel));\n }\n }\n }\n // The UUIDv7 timestamp is UTC, but Codex names session directories by the\n // local date, so a session opened in the evening of a negative-offset\n // timezone lands in the previous day's bucket. When the date-derived\n // buckets miss (or none were computed), fall back to a whole-tree scan so\n // that skew never silently drops the rollout.\n if (candidates.length === 0) {\n const glob = new Bun.Glob(`**/rollout-*-${threadId}.jsonl`);\n for (const rel of glob.scanSync({ cwd: sessionsDir, onlyFiles: true })) {\n candidates.push(join(sessionsDir, rel));\n }\n }\n return candidates.sort((a, b) => statSync(b).mtimeMs - statSync(a).mtimeMs)[0];\n } catch (error) {\n logger.debug({ error, threadId }, \"codex rollout lookup failed\");\n return undefined;\n }\n}\n\n/**\n * Materialize a Codex rollout JSONL with the provided dialogue and place it\n * at `~/.codex/sessions/<yyyy>/<mm>/<dd>/rollout-<ts>-<threadId>.jsonl` so a\n * subsequent `codex.resumeThread(threadId)` continues the conversation.\n */\nexport function writeCodexRollout(opts: CodexRolloutOptions): CodexRolloutResult {\n const threadId = opts.threadId ?? uuidv7();\n assertUuidLike(\"threadId\", threadId);\n ensureCwdExists(opts.cwd);\n const pairs = opts.pairs ?? extractChatPairs(opts.entries ?? []);\n const now = new Date();\n const tsIso = now.toISOString();\n const currentDate = [\n now.getFullYear(),\n String(now.getMonth() + 1).padStart(2, \"0\"),\n String(now.getDate()).padStart(2, \"0\"),\n ].join(\"-\");\n const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone || process.env.TZ || \"UTC\";\n\n // Captured 5-entry SDK shell (session_meta, task_started, developer setup,\n // environment_context, turn_context). Cloned per call so the cached\n // fixture is never mutated; only id/timestamp/cwd are patched.\n const shell = loadCodexShell();\n const sessionMeta = clone(shell.sessionMeta);\n (sessionMeta.payload as Record<string, unknown>).id = threadId;\n (sessionMeta.payload as Record<string, unknown>).timestamp = tsIso;\n (sessionMeta.payload as Record<string, unknown>).cwd = opts.cwd;\n (sessionMeta.payload as Record<string, unknown>).multi_agent_version = \"disabled\";\n (sessionMeta as Record<string, unknown>).timestamp = tsIso;\n\n const taskStarted = clone(shell.taskStarted);\n (taskStarted as Record<string, unknown>).timestamp = tsIso;\n\n const developerSetup = clone(shell.developerSetup);\n (developerSetup as Record<string, unknown>).timestamp = tsIso;\n patchDeveloperSetup(developerSetup);\n\n const envContext = clone(shell.envContext);\n (envContext as Record<string, unknown>).timestamp = tsIso;\n patchEnvContext(envContext, opts.cwd, currentDate, timezone);\n\n const turnContext = clone(shell.turnContext);\n (turnContext as Record<string, unknown>).timestamp = tsIso;\n const turnPayload = turnContext.payload as Record<string, unknown>;\n turnPayload.cwd = opts.cwd;\n turnPayload.current_date = currentDate;\n turnPayload.timezone = timezone;\n turnPayload.approval_policy = \"never\";\n turnPayload.sandbox_policy = { type: \"danger-full-access\" };\n turnPayload.multi_agent_version = \"disabled\";\n delete turnPayload.permission_profile;\n if (opts.model) turnPayload.model = opts.model;\n const collaborationMode = turnPayload.collaboration_mode as Record<string, unknown> | undefined;\n const collaborationSettings = collaborationMode?.settings as Record<string, unknown> | undefined;\n if (collaborationSettings) {\n if (opts.model) collaborationSettings.model = opts.model;\n if (opts.effort !== undefined) collaborationSettings.reasoning_effort = opts.effort;\n }\n\n const lines: unknown[] = [sessionMeta, taskStarted, developerSetup, envContext, turnContext];\n\n for (const pair of pairs) {\n lines.push({\n timestamp: tsIso,\n type: \"response_item\",\n payload: {\n type: \"message\",\n role: \"user\",\n content: [{ type: \"input_text\", text: pair.userText }],\n },\n });\n lines.push({\n timestamp: tsIso,\n type: \"event_msg\",\n payload: {\n type: \"user_message\",\n message: pair.userText,\n images: [],\n local_images: [],\n text_elements: [],\n },\n });\n lines.push({\n timestamp: tsIso,\n type: \"event_msg\",\n payload: {\n type: \"agent_message\",\n message: pair.assistantText,\n phase: \"final_answer\",\n memory_citation: null,\n },\n });\n lines.push({\n timestamp: tsIso,\n type: \"response_item\",\n payload: {\n type: \"message\",\n role: \"assistant\",\n content: [{ type: \"output_text\", text: pair.assistantText }],\n phase: \"final_answer\",\n },\n });\n }\n\n lines.push({\n timestamp: tsIso,\n type: \"event_msg\",\n payload: { type: \"task_complete\" },\n });\n\n const yyyy = now.getUTCFullYear();\n const mm = String(now.getUTCMonth() + 1).padStart(2, \"0\");\n const dd = String(now.getUTCDate()).padStart(2, \"0\");\n const tsStr = tsIso.replace(/[:.]/g, \"-\").slice(0, 19);\n const dir = join(codexSessionsDir(), String(yyyy), mm, dd);\n const path = join(dir, `rollout-${tsStr}-${threadId}.jsonl`);\n\n // Round-trip cleanup: when the caller reused a threadId (claude→codex→...\n // or maestro→codex→... cycles via `findLastSessionIdForAgent`), the SDK's\n // original rollout for that threadId still sits at its ORIGINAL-date\n // directory (`~/.codex/sessions/<orig-yyyy>/<orig-mm>/<orig-dd>/...`).\n // Writing today's synthetic rollout next to it leaves two jsonls sharing\n // the same threadId — `codex resume <tid>` globs `~/.codex/sessions/**`\n // and the SDK has no spec for which match it picks, so behavior becomes\n // environment-/codex-version-dependent. Sweep every prior file for this\n // threadId BEFORE writing the new one so resume always reads our synth.\n //\n // Synchronous on purpose: writeCodexRollout's signature is sync (called\n // inside set_agent's DB transaction), and an async sweep would race with\n // the following `writeJsonlFile` — Bun.Glob would re-scan once the\n // microtask queue drains and could unlink the file we just wrote if today\n // and the original-write-date are the same. Sync glob/unlink completes\n // before the new file ever lands on disk.\n //\n // Only runs when `opts.threadId` was supplied; fresh-mint threadIds can't\n // have prior files. Errors are logged but non-fatal — losing the sweep on\n // a permission glitch is preferable to crashing the whole switch.\n if (opts.threadId) {\n sweepPriorRolloutsForThread(opts.threadId);\n }\n\n writeJsonlFile(path, lines);\n logger.info(\n { threadId, path, pairs: pairs.length },\n \"writeCodexRollout: synthetic rollout placed\",\n );\n return { threadId, rolloutPath: path };\n}\n\n/**\n * Synchronous unlink of every existing `rollout-*-<threadId>.jsonl` under\n * `~/.codex/sessions/**`. Same glob shape `codexRegistry.cleanupRollouts`\n * uses (kept duplicate rather than imported to avoid the registry → rollout\n * → registry cycle).\n */\nfunction sweepPriorRolloutsForThread(threadId: string): void {\n const sessionsDir = codexSessionsDir();\n const buckets = candidateDateBuckets(threadId);\n if (!buckets) {\n // Couldn't pin a date from the threadId — fall back to the safer (but\n // much slower) whole-tree scan so we still find every prior rollout.\n sweepPriorRolloutsFullTree(threadId, sessionsDir);\n return;\n }\n for (const bucket of buckets) {\n const dir = join(sessionsDir, bucket);\n if (!existsSync(dir)) continue;\n try {\n const glob = new Bun.Glob(`rollout-*-${threadId}.jsonl`);\n for (const rel of glob.scanSync({ cwd: dir, onlyFiles: true })) {\n const fullPath = join(dir, rel);\n try {\n unlinkSync(fullPath);\n } catch (e) {\n if ((e as NodeJS.ErrnoException)?.code !== \"ENOENT\") {\n logger.warn(\n { err: e, path: fullPath },\n \"writeCodexRollout: prior-rollout unlink failed (continuing)\",\n );\n }\n }\n }\n } catch (e) {\n logger.warn(\n { err: e, threadId, bucket },\n \"writeCodexRollout: prior-rollout bucket scan failed (continuing)\",\n );\n }\n }\n}\n\n/** Legacy whole-tree scan. Used only when `candidateDateBuckets` can't pin a\n * date set from the threadId (non-UUIDv7 ids, e.g. some test fixtures). */\nfunction sweepPriorRolloutsFullTree(threadId: string, sessionsDir: string): void {\n try {\n const glob = new Bun.Glob(`**/rollout-*-${threadId}.jsonl`);\n for (const rel of glob.scanSync({ cwd: sessionsDir, onlyFiles: true })) {\n const fullPath = join(sessionsDir, rel);\n try {\n unlinkSync(fullPath);\n } catch (e) {\n if ((e as NodeJS.ErrnoException)?.code !== \"ENOENT\") {\n logger.warn(\n { err: e, path: fullPath },\n \"writeCodexRollout: prior-rollout unlink failed (continuing)\",\n );\n }\n }\n }\n } catch (e) {\n logger.warn(\n { err: e, threadId },\n \"writeCodexRollout: full-tree prior-rollout sweep failed (continuing)\",\n );\n }\n}\n\n/**\n * UUIDv7 ids encode their creation time in the first 48 bits. `writeCodexRollout`\n * buckets new files at `<yyyy>/<mm>/<dd>/` keyed off the WRITE time, so a\n * thread's rollouts can only live between (threadId's birth date) and\n * (today's date) — typically a 0-2 day span. We enumerate every day in that\n * inclusive range so a Mon-bridge / Tue-rebridge picks up both.\n *\n * Returns null when:\n * - threadId isn't a parseable UUIDv7 (atypical fixture / future format)\n * - the day span exceeds MAX_DAY_SPAN (a month+-old re-bridge isn't worth\n * per-day enumeration; safer to scan the full tree than to enumerate\n * hundreds of dirs and still maybe miss something)\n * In both cases the caller falls back to the whole-tree sweep so safety\n * never degrades below the original implementation.\n */\nconst MAX_DAY_SPAN = 30;\nconst DAY_MS = 86_400_000;\nconst LOCAL_DATE_SKEW_DAYS = 1;\n\nfunction candidateDateBuckets(threadId: string): Set<string> | null {\n const tidMs = decodeUuidV7Timestamp(threadId);\n if (tidMs === null) return null;\n const nowMs = Date.now();\n // Day-floor each end so DST / minutes-of-day noise doesn't bloat the span.\n const tidDay = Math.floor(tidMs / DAY_MS);\n const todayDay = Math.floor(nowMs / DAY_MS);\n const minDay = Math.min(tidDay, todayDay);\n const maxDay = Math.max(tidDay, todayDay);\n const span = maxDay - minDay;\n if (span > MAX_DAY_SPAN) return null;\n const buckets = new Set<string>();\n // Codex buckets sessions by local calendar date while UUIDv7 timestamps are\n // UTC. Include one day on each edge so every date-bucketed caller (context\n // usage, migration, and prior-rollout cleanup) covers timezone skew without\n // falling back to a whole-tree scan.\n for (let d = minDay - LOCAL_DATE_SKEW_DAYS; d <= maxDay + LOCAL_DATE_SKEW_DAYS; d++) {\n buckets.add(formatDateBucket(new Date(d * DAY_MS)));\n }\n return buckets;\n}\n\n/**\n * Decode the 48-bit unix-ms timestamp out of a UUIDv7. The first 12 hex\n * chars of the dash-separated form are the timestamp. Returns null when the\n * input doesn't look like a UUIDv7 or the decoded value is outside a\n * plausibility window (defensive: a malformed id that fits the regex but\n * decodes to year 1972 would point the sweep at a non-existent bucket —\n * better to fall back to the whole-tree scan than to silently no-op).\n *\n * Exported for tests.\n */\nexport function decodeUuidV7Timestamp(threadId: string): number | null {\n if (typeof threadId !== \"string\") return null;\n const m =\n /^([0-9a-fA-F]{8})-([0-9a-fA-F]{4})-7[0-9a-fA-F]{3}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.exec(\n threadId,\n );\n if (!m) return null;\n const hex = `${m[1]}${m[2]}`;\n const ms = Number.parseInt(hex, 16);\n if (!Number.isFinite(ms)) return null;\n const MIN = 1577836800000; // 2020-01-01T00:00:00Z\n const MAX = 4102444800000; // 2100-01-01T00:00:00Z\n if (ms < MIN || ms > MAX) return null;\n return ms;\n}\n\nfunction formatDateBucket(d: Date): string {\n const yyyy = d.getUTCFullYear();\n const mm = String(d.getUTCMonth() + 1).padStart(2, \"0\");\n const dd = String(d.getUTCDate()).padStart(2, \"0\");\n return `${yyyy}/${mm}/${dd}`;\n}\n\n/** Internal export for tests. */\nexport const __candidateDateBuckets = candidateDateBuckets;\n",
15
+ "import { AsyncLocalStorage } from \"node:async_hooks\";\nimport { dirname } from \"node:path\";\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 {\n redactVaultSecrets as defaultRedactVaultSecrets,\n vaultSubstituteDetailed as defaultVaultSubstituteDetailed,\n} 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 substituteVaultSecrets(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 substituteVaultSecrets: (userId, value) => defaultVaultSubstituteDetailed(userId, value).text,\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 if (opts.toolPolicy === \"none\") return {};\n if (opts.toolPolicy === \"compaction-log\") {\n const compactLog = opts.mcpExtra?.compact_log;\n return compactLog ? { compact_log: compactLog } : {};\n }\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 substituteHostedSecrets(userId: string, value: string): string {\n return activeHost().substituteVaultSecrets(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\n/** The one Codex state root used by auth, rollouts, native forks, and SDK resume. */\nexport function hostedCodexHomePath(): string {\n return dirname(hostedCodexAuthFilePath());\n}\n",
16
+ "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",
17
+ "import { isSensitivePath } from \"#security/sensitive-path\";\n\nconst SENSITIVE_RUNTIME_NAMES = [\n \"vault.db\",\n \"vault-master-key\",\n \"runtime-mcp-secret\",\n \"sessions.db\",\n] as const;\n\n// Direct substitution is deliberately default-deny. These provider-owned\n// execution tools consume credentials transiently; persistence and messaging\n// tools must keep placeholders unresolved.\nconst DIRECT_VAULT_EXECUTION_TOOLS = new Set([\"Bash\", \"WebFetch\"]);\n\nfunction leafToolName(toolName: string): string {\n const parts = toolName.split(\"__\");\n return parts.at(-1) ?? toolName;\n}\n\nexport function shouldSubstituteVaultToolInput(toolName: string): boolean {\n const leaf = leafToolName(toolName);\n return leaf.startsWith(\"browser_\") || DIRECT_VAULT_EXECUTION_TOOLS.has(leaf);\n}\n\nexport const VAULT_BROKER_REDIRECT_ERROR =\n \"Vault broker redirection is disabled; use {{KEY}} directly in normal tool inputs.\";\n\nexport interface VaultToolPolicyHost {\n isSensitivePath(path: string): boolean;\n valueReferencesVaultKey(userId: string, value: unknown): boolean;\n}\n\nexport interface VaultToolPolicy {\n isVaultBrokerTool(toolName: string): boolean;\n referencesRuntimeSecretStorage(value: unknown): boolean;\n shouldRedirectVaultTool(userId: string, toolName: string, input: unknown): boolean;\n}\n\nexport function createVaultToolPolicy(host: VaultToolPolicyHost): VaultToolPolicy {\n function isVaultBrokerTool(toolName: string): boolean {\n return toolName.includes(\"vault_run\") || toolName.includes(\"vault_http_request\");\n }\n\n 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(\"/\") && host.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\n function shouldRedirectVaultTool(userId: string, toolName: string, input: unknown): boolean {\n // Kept as a compatibility surface for embedding hosts that implemented the\n // pre-0.1.20 broker-only policy. Normal tools now receive Vault values from\n // the execution-time substitution hook, so redirecting a {{KEY}} call\n // would only make browser form filling and other interactive tools fail.\n void userId;\n void toolName;\n void input;\n return false;\n }\n\n return { isVaultBrokerTool, referencesRuntimeSecretStorage, shouldRedirectVaultTool };\n}\n\nconst defaultVaultToolPolicy = createVaultToolPolicy({\n isSensitivePath,\n valueReferencesVaultKey: () => false,\n});\n\nexport const isVaultBrokerTool = defaultVaultToolPolicy.isVaultBrokerTool;\nexport const referencesRuntimeSecretStorage = defaultVaultToolPolicy.referencesRuntimeSecretStorage;\nexport const shouldRedirectVaultTool = defaultVaultToolPolicy.shouldRedirectVaultTool;\n",
18
+ "import type { PeerRuntimeBridgeContext } from \"#types\";\n\nexport type CanonicalMcpSurface = \"task\" | \"wiki\";\n\nexport interface CanonicalMcpBridgeScope {\n surface: CanonicalMcpSurface;\n userId: string;\n topicId: string;\n queryId: string;\n peerBridge: PeerRuntimeBridgeContext;\n}\n\nexport interface CanonicalMcpBridgeEnvLease {\n env: Record<string, string>;\n /** Revoke the capability immediately. Must be safe to call more than once. */\n revoke(): void;\n}\n\nexport type CanonicalMcpBridgeEnvProvider = (\n scope: CanonicalMcpBridgeScope,\n) => CanonicalMcpBridgeEnvLease | undefined;\n\nconst registrations: Array<{ id: symbol; provider: CanonicalMcpBridgeEnvProvider }> = [];\nconst turnLeases = new Map<string, Set<() => void>>();\n\nfunction turnKey(\n scope: Pick<CanonicalMcpBridgeScope, \"userId\" | \"topicId\" | \"queryId\" | \"peerBridge\">,\n): string {\n return JSON.stringify([\n scope.userId,\n scope.topicId,\n scope.queryId,\n scope.peerBridge.hubCellId,\n scope.peerBridge.hostTopicId,\n scope.peerBridge.hostQueryId,\n ]);\n}\n\n/** Placement adapters install a scoped capability issuer without exposing\n * their hub discovery or authentication model to generic core. */\nexport function registerCanonicalMcpBridgeEnvProvider(\n provider: CanonicalMcpBridgeEnvProvider,\n): () => void {\n const registration = { id: Symbol(\"canonical-mcp-bridge\"), provider };\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 canonicalMcpBridgeEnv(\n scope: CanonicalMcpBridgeScope,\n): Record<string, string> | undefined {\n const lease = registrations.at(-1)?.provider(scope);\n if (!lease) return undefined;\n const key = turnKey(scope);\n const leases = turnLeases.get(key) ?? new Set<() => void>();\n leases.add(lease.revoke);\n turnLeases.set(key, leases);\n return lease.env;\n}\n\n/** Revoke every canonical MCP capability issued while building one placed turn. */\nexport function revokeCanonicalMcpBridgeTurn(\n scope: Pick<CanonicalMcpBridgeScope, \"userId\" | \"topicId\" | \"queryId\" | \"peerBridge\">,\n): number {\n const key = turnKey(scope);\n const leases = turnLeases.get(key);\n if (!leases) return 0;\n turnLeases.delete(key);\n for (const revoke of leases) {\n try {\n revoke();\n } catch {\n // Revocation is best-effort across independently owned bridge adapters;\n // continue so one broken disposer cannot preserve sibling capabilities.\n }\n }\n return leases.size;\n}\n",
19
+ "/**\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\";\nexport const HOSTED_MCP_SURFACES = [\n \"task\",\n \"token-stats\",\n \"system-health\",\n \"vault\",\n \"wiki\",\n \"skills\",\n \"session-comm\",\n \"agent-health\",\n] as const;\nexport type HostedMcpSurface = (typeof HOSTED_MCP_SURFACES)[number];\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 /** Capability minted by the adapter. File-delivery tools are absent unless true. */\n fileDeliveryTools?: boolean;\n peerBridge?: PeerRuntimeBridgeContext;\n}\n\n/** Signed identity/capability context shared by hosted built-in MCP surfaces. */\nexport interface HostedMcpContext {\n userId: string;\n topicTitle: string;\n topicId?: string;\n queryId?: string;\n wikiTopicId?: string;\n subagentParentTopicId?: string;\n cwd: string;\n agent: AgentKind;\n model?: string;\n depth?: number;\n silent?: boolean;\n peerBridge?: PeerRuntimeBridgeContext;\n}\n\ntype RuntimeTokenPayload = {\n v: 1;\n exp: number;\n ctx: RuntimeMcpContext;\n};\n\ntype HostedTokenPayload = {\n v: 2;\n exp: number;\n aud: HostedMcpSurface;\n ctx: HostedMcpContext;\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.fileDeliveryTools === undefined || typeof ctx.fileDeliveryTools === \"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 isHostedMcpSurface(value: string): value is HostedMcpSurface {\n return (HOSTED_MCP_SURFACES as readonly string[]).includes(value);\n}\n\nfunction isHostedMcpContext(value: unknown): value is HostedMcpContext {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n const ctx = value as Partial<HostedMcpContext>;\n return (\n typeof ctx.userId === \"string\" &&\n typeof ctx.topicTitle === \"string\" &&\n typeof ctx.cwd === \"string\" &&\n typeof ctx.agent === \"string\" &&\n isAgentKind(ctx.agent) &&\n (ctx.topicId === undefined || typeof ctx.topicId === \"string\") &&\n (ctx.queryId === undefined || typeof ctx.queryId === \"string\") &&\n (ctx.wikiTopicId === undefined || typeof ctx.wikiTopicId === \"string\") &&\n (ctx.subagentParentTopicId === undefined || typeof ctx.subagentParentTopicId === \"string\") &&\n (ctx.model === undefined || typeof ctx.model === \"string\") &&\n (ctx.depth === undefined || (Number.isInteger(ctx.depth) && ctx.depth >= 0)) &&\n (ctx.silent === undefined || typeof ctx.silent === \"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\nexport function issueHostedMcpToken(surface: HostedMcpSurface, ctx: HostedMcpContext): string {\n const payloadPart = encodeTokenPart({\n v: 2,\n exp: Date.now() + TOKEN_TTL_MS,\n aud: surface,\n ctx,\n } satisfies HostedTokenPayload);\n return `${payloadPart}.${signTokenPayload(payloadPart)}`;\n}\n\nexport function resolveHostedMcpToken(\n token: string | null,\n surface: HostedMcpSurface,\n): HostedMcpContext | 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<HostedTokenPayload>;\n if (\n payload.v !== 2 ||\n payload.aud !== surface ||\n typeof payload.exp !== \"number\" ||\n payload.exp <= Date.now()\n ) {\n return null;\n }\n return isHostedMcpContext(payload.ctx) ? payload.ctx : null;\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\n/** Build an agent transport spec for one logical MCP surface on the shared runtime process. */\nexport function buildHostedMcpSpec(\n agent: AgentKind,\n surface: HostedMcpSurface,\n ctx: HostedMcpContext,\n): Record<string, unknown> {\n const token = issueHostedMcpToken(surface, ctx);\n const base = `http://127.0.0.1:${runtimePort}${RUNTIME_MCP_BASE_PATH}/${surface}`;\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",
20
+ "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",
21
+ "import { type ChildProcess, execFileSync, spawn } from \"node:child_process\";\nimport { randomBytes } from \"node:crypto\";\nimport { BACKGROUND_BASH_SERVER, BG_BASH_BASE_PORT, BG_BASH_MAX_PORT } from \"#platform/config\";\nimport { delay } from \"#platform/delay\";\nimport { logger } from \"#platform/logger\";\nimport { deriveBgBashContextCapability } from \"./context\";\n\nexport function makeBgBashKey(_userId: string, _topic: string): string {\n return \"runtime\";\n}\n\ninterface BgBashInstance {\n process: ChildProcess;\n port: number;\n startedAt: number;\n lastUsedAt: number;\n}\n\nexport interface BackgroundBashManager {\n contextCapability(userId: string, topic: string): string;\n ensure(userId: string, topic: string): Promise<number>;\n clear(userId: string, topic: string): void;\n clearUser(userId: string): void;\n killAll(): Promise<void>;\n}\n\nexport interface BackgroundBashManagerOptions {\n serverFile?: string;\n basePort?: number;\n maxPort?: number;\n capability?: string;\n serverId?: string;\n env?: NodeJS.ProcessEnv;\n fetch?: typeof globalThis.fetch;\n now?: () => number;\n delay?: (milliseconds: number) => Promise<void>;\n portPids?: (port: number) => readonly number[];\n spawn?: (\n command: string,\n args: readonly string[],\n options: Parameters<typeof spawn>[2],\n ) => ChildProcess;\n}\n\nfunction defaultPortPids(port: number): number[] {\n try {\n return execFileSync(\"lsof\", [\"-i\", `:${port}`, \"-t\"], { stdio: \"pipe\" })\n .toString()\n .trim()\n .split(\"\\n\")\n .map((pid) => Number.parseInt(pid, 10))\n .filter((pid) => !Number.isNaN(pid));\n } catch {\n return [];\n }\n}\n\n/** Create a fully isolated manager. All mutable process/port/context state belongs to the caller. */\nexport function createBackgroundBashManager(\n options: BackgroundBashManagerOptions = {},\n): BackgroundBashManager {\n const instances = new Map<string, BgBashInstance>();\n const usedPorts = new Set<number>();\n const spawning = new Map<string, Promise<number>>();\n const knownContexts = new Map<string, { userId: string; topic: string }>();\n const runtimeCapability = options.capability ?? randomBytes(32).toString(\"hex\");\n const runtimeServerId = options.serverId ?? randomBytes(16).toString(\"hex\");\n const serverFile = options.serverFile ?? BACKGROUND_BASH_SERVER;\n const basePort = options.basePort ?? BG_BASH_BASE_PORT;\n const maxPort = options.maxPort ?? BG_BASH_MAX_PORT;\n const fetchImpl = options.fetch ?? globalThis.fetch;\n const now = options.now ?? Date.now;\n const wait = options.delay ?? delay;\n const portPids = options.portPids ?? defaultPortPids;\n const spawnImpl =\n options.spawn ?? ((command, args, spawnOptions) => spawn(command, [...args], spawnOptions));\n\n function contextKey(userId: string, topic: string): string {\n return `${userId}\\0${topic}`;\n }\n\n function contextCapability(userId: string, topic: string): string {\n return deriveBgBashContextCapability(runtimeCapability, userId, topic);\n }\n\n async function allocatePort(excludedPorts: ReadonlySet<number> = new Set()): Promise<number> {\n for (let port = basePort; port <= maxPort; port++) {\n if (usedPorts.has(port) || excludedPorts.has(port)) continue;\n usedPorts.add(port);\n if (portPids(port).length > 0) {\n usedPorts.delete(port);\n continue;\n }\n return port;\n }\n throw new Error(\n `No available ports for background-bash (range ${basePort}-${maxPort}, ${instances.size} active)`,\n );\n }\n\n async function isHealthy(port: number): Promise<boolean> {\n try {\n const response = await fetchImpl(`http://127.0.0.1:${port}/health`, {\n signal: AbortSignal.timeout(2000),\n });\n return response.ok && (await response.text()) === runtimeServerId;\n } catch {\n return false;\n }\n }\n\n function killRuntime(): void {\n const key = \"runtime\";\n const instance = instances.get(key);\n if (!instance) return;\n try {\n instance.process.kill(\"SIGTERM\");\n } catch {}\n usedPorts.delete(instance.port);\n instances.delete(key);\n logger.info({ key, port: instance.port }, \"background-bash server killed\");\n }\n\n async function spawnServer(\n key: string,\n reservedPort?: number,\n excludedPorts: ReadonlySet<number> = new Set(),\n ): Promise<number> {\n const port = reservedPort ?? (await allocatePort(excludedPorts));\n const process = spawnImpl(\"bun\", [\"run\", serverFile, `--port=${port}`], {\n stdio: \"ignore\",\n detached: false,\n env: {\n ...(options.env ?? globalThis.process.env),\n NEGOTIUM_BG_BASH_CAPABILITY: runtimeCapability,\n NEGOTIUM_BG_BASH_SERVER_ID: runtimeServerId,\n },\n });\n\n process.once(\"error\", (error) => {\n logger.error({ err: error, key }, \"background-bash server error\");\n if (instances.get(key)?.process === process) {\n usedPorts.delete(port);\n instances.delete(key);\n }\n });\n process.once(\"exit\", (code) => {\n logger.info({ key, code }, \"background-bash server exited\");\n if (instances.get(key)?.process === process) {\n usedPorts.delete(port);\n instances.delete(key);\n }\n });\n\n const timestamp = now();\n instances.set(key, { process, port, startedAt: timestamp, lastUsedAt: timestamp });\n const started = now();\n while (now() - started < 8_000) {\n if (process.exitCode !== null) {\n const nextExcluded = new Set(excludedPorts);\n nextExcluded.add(port);\n return spawnServer(key, undefined, nextExcluded);\n }\n if (await isHealthy(port)) return port;\n await wait(200);\n }\n killRuntime();\n throw new Error(`background-bash server failed health check after spawn on port ${port}`);\n }\n\n async function ensure(userId: string, topic: string): Promise<number> {\n const key = makeBgBashKey(userId, topic);\n knownContexts.set(contextKey(userId, topic), { userId, topic });\n const inProgress = spawning.get(key);\n if (inProgress) return inProgress;\n\n const promise = (async () => {\n const existing = instances.get(key);\n if (existing && !existing.process.killed && existing.process.exitCode === null) {\n if (await isHealthy(existing.port)) {\n existing.lastUsedAt = now();\n return existing.port;\n }\n killRuntime();\n } else if (existing) {\n usedPorts.delete(existing.port);\n instances.delete(key);\n }\n return spawnServer(key);\n })().finally(() => spawning.delete(key));\n spawning.set(key, promise);\n return promise;\n }\n\n function clear(userId: string, topic: string): void {\n knownContexts.delete(contextKey(userId, topic));\n const instance = instances.get(\"runtime\");\n if (!instance) return;\n const query = new URLSearchParams({\n user: userId,\n topic,\n capability: contextCapability(userId, topic),\n });\n void fetchImpl(`http://127.0.0.1:${instance.port}/contexts?${query}`, {\n method: \"DELETE\",\n }).catch(() => {});\n }\n\n function clearUser(userId: string): void {\n for (const context of [...knownContexts.values()]) {\n if (context.userId === userId) clear(context.userId, context.topic);\n }\n }\n\n async function killAll(): Promise<void> {\n const entries = [...instances.values()];\n for (const instance of entries) {\n try {\n instance.process.kill(\"SIGTERM\");\n } catch {}\n }\n instances.clear();\n usedPorts.clear();\n knownContexts.clear();\n const deadline = now() + 3000;\n await Promise.all(\n entries.map(\n (instance) =>\n new Promise<void>((resolve) => {\n if (instance.process.exitCode !== null || instance.process.killed) return resolve();\n instance.process.once(\"exit\", resolve);\n instance.process.once(\"error\", resolve);\n const timer = setTimeout(resolve, Math.max(0, deadline - now()));\n timer.unref?.();\n }),\n ),\n );\n }\n\n return { contextCapability, ensure, clear, clearUser, killAll };\n}\n\nconst defaultManager = createBackgroundBashManager();\n\nexport const bgBashContextCapability = defaultManager.contextCapability;\nexport const ensureBgBash = defaultManager.ensure;\nexport const killBgBash = defaultManager.clear;\nexport const killBgBashForUser = defaultManager.clearUser;\nexport const killAllBgBash = defaultManager.killAll;\n",
22
+ "export const delay = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));\n",
23
+ "import { createHmac } from \"node:crypto\";\n\nexport function deriveBgBashContextCapability(\n runtimeCapability: string,\n userId: string,\n topic: string,\n): string {\n return createHmac(\"sha256\", runtimeCapability).update(`${userId}\\0${topic}`).digest(\"hex\");\n}\n",
24
+ "export type RuntimeMcpScope = \"dm\" | \"forum\" | \"fork\" | \"manager\" | \"cron\";\n\nexport interface RuntimeMcpPolicyEntry {\n scopes: readonly RuntimeMcpScope[];\n /** Forum entries marked required cannot be disabled by a topic whitelist. */\n forumRequired?: boolean;\n}\n\nexport const COMMON_RUNTIME_MCP_POLICY = {\n playwright: { scopes: [\"dm\", \"forum\", \"fork\", \"cron\"], forumRequired: true },\n runtime: { scopes: [\"forum\", \"manager\", \"fork\", \"cron\"], forumRequired: true },\n \"token-stats\": { scopes: [\"dm\", \"forum\", \"manager\", \"cron\"], forumRequired: true },\n task: { scopes: [\"dm\", \"forum\", \"manager\", \"cron\"], forumRequired: true },\n \"session-comm\": { scopes: [\"forum\", \"fork\", \"manager\"], forumRequired: true },\n wiki: { scopes: [\"dm\", \"forum\", \"manager\", \"cron\"], forumRequired: true },\n skills: { scopes: [\"dm\", \"forum\", \"manager\", \"cron\"], forumRequired: true },\n \"system-health\": { scopes: [\"dm\", \"forum\", \"manager\", \"cron\"], forumRequired: true },\n \"background-bash\": { scopes: [\"forum\"], forumRequired: true },\n \"agent-health\": { scopes: [\"forum\", \"manager\", \"cron\"], forumRequired: true },\n vault: { scopes: [\"dm\", \"forum\", \"manager\", \"cron\"], forumRequired: true },\n} as const satisfies Record<string, RuntimeMcpPolicyEntry>;\n\nexport type CommonRuntimeMcpName = keyof typeof COMMON_RUNTIME_MCP_POLICY;\n\nexport interface ForumMcpClassification {\n all: string[];\n required: string[];\n optional: string[];\n}\n\nexport function classifyForumMcpServers(\n catalog: Readonly<Record<string, RuntimeMcpPolicyEntry>>,\n): ForumMcpClassification {\n const all = Object.entries(catalog)\n .filter(([, entry]) => entry.scopes.includes(\"forum\"))\n .map(([name]) => name);\n const required = Object.entries(catalog)\n .filter(([, entry]) => entry.scopes.includes(\"forum\") && entry.forumRequired)\n .map(([name]) => name);\n const requiredSet = new Set(required);\n return { all, required, optional: all.filter((name) => !requiredSet.has(name)) };\n}\n\nexport function commonRuntimeMcpPolicy(name: CommonRuntimeMcpName): RuntimeMcpPolicyEntry {\n return COMMON_RUNTIME_MCP_POLICY[name];\n}\n\nexport function isForumRequiredMcp(name: string): boolean {\n const entry = COMMON_RUNTIME_MCP_POLICY[name as CommonRuntimeMcpName];\n return Boolean(entry?.scopes.includes(\"forum\") && entry.forumRequired);\n}\n",
25
+ "import { createHmac } from \"node:crypto\";\n\nexport function browserOwnerCapability(capability: string, owner: string): string {\n return createHmac(\"sha256\", capability).update(owner).digest(\"hex\");\n}\n",
26
+ "import { canonicalMcpBridgeEnv } from \"#mcp/canonical-bridge-config\";\nimport {\n buildHostedMcpSpec,\n buildRuntimeMcpSpec,\n type HostedMcpSurface,\n RUNTIME_MCP_KEY,\n} from \"#mcp/runtime-spec\";\nimport { peerSessionBridgeIpcEnv } from \"#mcp/session-comm/bridge-ipc-config\";\nimport { bgBashContextCapability } from \"#platform/background-bash/manager\";\nimport {\n AGENT_HEALTH_SERVER,\n BROWSER_MCP_SSE_PROXY_SERVER,\n CANONICAL_MCP_PROXY_SERVER,\n envText,\n FALLBACK_AGENT,\n resolveTopicWorkspaceDir,\n SESSION_COMM_SERVER,\n SYSTEM_HEALTH_SERVER,\n TASK_SERVER,\n TOKEN_STATS_SERVER,\n TSCONFIG_PATH,\n TSX_LOADER,\n VAULT_SERVER,\n WIKI_SERVER,\n} from \"#platform/config\";\nimport { logger } from \"#platform/logger\";\nimport {\n classifyForumMcpServers,\n commonRuntimeMcpPolicy,\n type RuntimeMcpScope,\n} from \"#platform/mcp-catalog-policy\";\nimport { browserOwnerCapability } from \"#platform/playwright/capability\";\nimport type { AgentKind, AgentQueryOptions, PeerRuntimeBridgeContext } from \"#types\";\n\nexport type { RuntimeMcpScope } from \"#platform/mcp-catalog-policy\";\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: [\"--import\", TSX_LOADER, 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\nfunction useHostedBuiltinMcp(): boolean {\n return envText(\"NEGOTIUM_BUILTIN_MCP_TRANSPORT\") !== \"stdio\";\n}\n\nfunction buildBuiltinMcpServer(\n surface: HostedMcpSurface,\n ctx: RuntimeMcpBuildContext,\n stdio: () => Record<string, unknown>,\n): Record<string, unknown> {\n if (!useHostedBuiltinMcp()) return stdio();\n const agent = ctx.agent ?? FALLBACK_AGENT;\n return buildHostedMcpSpec(agent, surface, {\n userId: ctx.userId,\n topicTitle: ctx.session,\n ...(ctx.topicId ? { topicId: ctx.topicId } : {}),\n ...(ctx.queryId ? { queryId: ctx.queryId } : {}),\n ...(ctx.wikiTopicId ? { wikiTopicId: ctx.wikiTopicId } : {}),\n ...(ctx.subagentParentTopicId ? { subagentParentTopicId: ctx.subagentParentTopicId } : {}),\n cwd: ctx.cwd ?? (ctx.topicId ? resolveTopicWorkspaceDir(ctx.topicId) : process.cwd()),\n agent,\n ...(ctx.model ? { model: ctx.model } : {}),\n ...(ctx.depth !== undefined ? { depth: ctx.depth } : {}),\n ...(ctx.silent !== undefined ? { silent: ctx.silent } : {}),\n ...(ctx.peerBridge ? { peerBridge: ctx.peerBridge } : {}),\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 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 /** Direct parent topic id when the current topic is a subagent room. */\n subagentParentTopicId?: 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 fileDeliveryTools?: 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 { browserOwnerCapability };\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 const query = new URLSearchParams({ owner });\n return {\n url: `http://127.0.0.1:${port}/mcp?${query}`,\n env_http_headers: { \"X-Browser-Capability\": CODEX_BROWSER_CAPABILITY_ENV },\n };\n }\n const query = new URLSearchParams({ owner });\n if (agent === \"maestro\") {\n // maestro-agent-sdk does not expose SSE headers. Route it through a\n // tiny stdio bridge so the bearer capability stays in an environment\n // variable rather than appearing in URLs and request logs.\n return buildStdioMcpServer(\"maestro\", BROWSER_MCP_SSE_PROXY_SERVER, [], {\n NEGOTIUM_BROWSER_SSE_URL: `http://127.0.0.1:${port}/sse?${query}`,\n NEGOTIUM_BROWSER_OWNER_CAPABILITY: ownerCapability,\n });\n }\n return {\n type: \"sse\" as const,\n url: `http://127.0.0.1:${port}/sse?${query}`,\n headers: { \"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\nfunction backgroundBashTransport(\n agent: AgentKind | undefined,\n port: number,\n userId: string,\n topic: string,\n) {\n const capability = bgBashContextCapability(userId, topic);\n const headers = {\n \"X-Background-Bash-User\": userId,\n \"X-Background-Bash-Topic\": topic,\n \"X-Background-Bash-Capability\": capability,\n };\n if (agent === \"codex\") return { url: `http://127.0.0.1:${port}/mcp`, http_headers: headers };\n if (agent === \"maestro\") {\n const query = new URLSearchParams({ user: userId, topic, capability });\n return { type: \"sse\" as const, url: `http://127.0.0.1:${port}/sse?${query}` };\n }\n return { type: \"sse\" as const, url: `http://127.0.0.1:${port}/sse`, headers };\n}\n\n// --- Catalog ---\n\nconst MCP_CATALOG: Record<string, RuntimeMcpCatalogEntry> = {\n playwright: {\n ...commonRuntimeMcpPolicy(\"playwright\"),\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 ...commonRuntimeMcpPolicy(\"runtime\"),\n build({\n userId,\n session,\n topicId,\n queryId,\n agent,\n cwd,\n model,\n currentUserPrompt,\n autoContinue,\n visualTools,\n fileDeliveryTools,\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 fileDeliveryTools,\n peerBridge,\n });\n },\n },\n \"token-stats\": {\n ...commonRuntimeMcpPolicy(\"token-stats\"),\n build(ctx) {\n return buildBuiltinMcpServer(\"token-stats\", ctx, () =>\n buildStdioMcpServer(ctx.agent, TOKEN_STATS_SERVER, [`--user-id=${ctx.userId}`]),\n );\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 ...commonRuntimeMcpPolicy(\"task\"),\n build(ctx) {\n const { userId, session, topicId, queryId, agent, peerBridge } = ctx;\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 buildBuiltinMcpServer(\"task\", ctx, () =>\n buildStdioMcpServer(agent, TASK_SERVER, args),\n );\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 ...commonRuntimeMcpPolicy(\"session-comm\"),\n build(ctx) {\n const {\n userId,\n session,\n topicId,\n subagentParentTopicId,\n agent,\n depth = 0,\n silent,\n peerBridge,\n } = ctx;\n const effectiveAgent = agent ?? FALLBACK_AGENT;\n const args = [\n `--user-id=${userId}`,\n `--topic=${session}`,\n ...(topicId ? [`--topic-id=${topicId}`] : []),\n ...(subagentParentTopicId ? [`--subagent-parent-topic-id=${subagentParentTopicId}`] : []),\n `--depth=${depth}`,\n `--agent=${effectiveAgent}`,\n ...(silent ? [\"--reply-only=true\"] : []),\n ...(peerBridge ? [`--peer-host-query-id=${peerBridge.hostQueryId}`] : []),\n ];\n return buildBuiltinMcpServer(\"session-comm\", ctx, () =>\n buildStdioMcpServer(\n effectiveAgent,\n SESSION_COMM_SERVER,\n args,\n peerBridge ? peerSessionBridgeIpcEnv() : undefined,\n ),\n );\n },\n },\n wiki: {\n ...commonRuntimeMcpPolicy(\"wiki\"),\n build(ctx) {\n const { userId, session, topicId, queryId, wikiTopicId, agent, peerBridge } = ctx;\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 buildBuiltinMcpServer(\"wiki\", { ...ctx, wikiTopicId: resolvedWikiTopicId }, () =>\n buildStdioMcpServer(agent, WIKI_SERVER, args),\n );\n },\n },\n skills: {\n ...commonRuntimeMcpPolicy(\"skills\"),\n build(ctx) {\n const { userId, topicId, agent } = ctx;\n const args = [`--user-id=${userId}`, \"--surface=skills\"];\n if (topicId) args.push(`--topic-id=${topicId}`);\n return buildBuiltinMcpServer(\"skills\", ctx, () =>\n buildStdioMcpServer(agent, WIKI_SERVER, args),\n );\n },\n },\n \"system-health\": {\n ...commonRuntimeMcpPolicy(\"system-health\"),\n build(ctx) {\n return buildBuiltinMcpServer(\"system-health\", ctx, () =>\n buildStdioMcpServer(ctx.agent, SYSTEM_HEALTH_SERVER, []),\n );\n },\n },\n \"background-bash\": {\n ...commonRuntimeMcpPolicy(\"background-bash\"),\n build({ agent, bgBashPort, userId, topicId }) {\n // Key the whole pipeline by the canonical topic id: it flows through the\n // capability, the request context, and the completion inbox filename\n // (sessionInboxPath) so the exiting process's output is routed back to\n // the exact originating topic. A title/session fallback would be encoded\n // as if it were an id and the inbox worker would fail to resolve it, so\n // background-bash is simply unavailable without a topic id.\n if (bgBashPort === undefined || !topicId) return null;\n return backgroundBashTransport(agent, bgBashPort, userId, topicId);\n },\n },\n \"agent-health\": {\n ...commonRuntimeMcpPolicy(\"agent-health\"),\n build(ctx) {\n const { userId, agent } = ctx;\n const args = [`--user-id=${userId}`];\n return buildBuiltinMcpServer(\"agent-health\", ctx, () =>\n buildStdioMcpServer(agent, AGENT_HEALTH_SERVER, args),\n );\n },\n },\n vault: {\n ...commonRuntimeMcpPolicy(\"vault\"),\n build(ctx) {\n const { userId, agent } = ctx;\n // Normal turns use {{KEY}} directly in tool inputs. Keep the Vault MCP\n // surface focused on key discovery; broker tools remain available from\n // the public factory for compatibility but are no longer the default UX.\n const args = [`--user-id=${userId}`];\n if (agent !== \"codex\") args.push(\"--list-only=true\");\n return buildBuiltinMcpServer(\"vault\", ctx, () =>\n buildStdioMcpServer(agent, VAULT_SERVER, args),\n );\n },\n },\n};\n\n// --- Derived catalog views ---\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, required, optional } = classifyForumMcpServers(MCP_CATALOG);\n allForumMcpServerNames.splice(0, allForumMcpServerNames.length, ...all);\n requiredForumMcpServers.splice(0, requiredForumMcpServers.length, ...required);\n optionalForumMcpServers.splice(0, optionalForumMcpServers.length, ...optional);\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-heavy work belongs in dedicated topics, so\n * Playwright is 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 fileDeliveryTools?: 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 fileDeliveryTools: opts.fileDeliveryTools,\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 subagentParentTopicId?: 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 fileDeliveryTools?: 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 subagentParentTopicId,\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 fileDeliveryTools,\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 subagentParentTopicId,\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 fileDeliveryTools,\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 * 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 fileDeliveryTools?: 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 fileDeliveryTools: opts.fileDeliveryTools,\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.toolPolicy === \"none\") return {};\n if (opts.toolPolicy === \"compaction-log\") {\n const compactLog = opts.mcpExtra?.compact_log;\n return compactLog ? { compact_log: compactLog } : {};\n }\n if (opts.sessionType === \"cron\") {\n if (!opts.topicId) throw new Error(\"getMcpServersForQuery: cron sessionType requires topicId\");\n return getCronMcpServers({\n userId: opts.userId || \"local\",\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 fileDeliveryTools: opts.fileDeliveryTools,\n });\n }\n if (opts.sessionType === \"dm\" || opts.sessionType === \"ephemeral\") {\n return getDmMcpServers({\n userId: opts.userId || \"local\",\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 || \"local\",\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 fileDeliveryTools: opts.fileDeliveryTools,\n });\n }\n return getForumMcpServers({\n userId: opts.userId || \"local\",\n session: opts.session || \"default\",\n topicId: opts.topicId,\n subagentParentTopicId: opts.subagentParentTopicId,\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 fileDeliveryTools: opts.fileDeliveryTools,\n depth: opts.depth,\n enabled: opts.mcpEnabled,\n extra: opts.mcpExtra,\n silent: opts.silent,\n peerBridge: opts.peerBridge,\n });\n}\n",
27
+ "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 vaultDir = join(dataDir, \"vault\");\n const path = join(vaultDir, \"vault.db\");\n mkdirSync(vaultDir, { recursive: true, mode: 0o700 });\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\n/**\n * Return only rows that can still be authenticated with the active master key.\n *\n * This is intentionally limited to redaction indexes: one damaged credential\n * must not disable unrelated tools, while direct access to that credential\n * continues to fail closed through vaultGetValue().\n */\nexport function vaultListDecryptableValues(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 const entries: VaultEntryWithValue[] = [];\n for (const row of rows) {\n try {\n entries.push({\n key: row.key,\n description: row.description,\n value: decryptRow(userId, row.key, row.value),\n });\n } catch {\n // A value that cannot be authenticated cannot be exposed by substitution,\n // so there is no plaintext form available to add to the redaction index.\n }\n }\n return entries;\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<string, string | undefined>();\n const usedKeys = new Set<string>();\n const substituted = text.replace(/\\{\\{([^}]+)\\}\\}/g, (match, rawKey: string) => {\n const key = normalizeVaultKey(rawKey);\n if (!entries.has(key)) entries.set(key, vaultGetValue(userId, key));\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 = vaultListDecryptableValues(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",
28
+ "// Runtime-adaptive SQLite façade.\n//\n// Why this exists: Otium normally runs on bun and uses `bun:sqlite` (native,\n// fast, zero-build). But the `codex` agent's MCP servers must run on pure node\n// — codex 0.135's rmcp stdio client can't handshake with bun-spawned servers\n// (see serverLaunch in platform/mcp-config.ts). `bun:sqlite` doesn't exist\n// under node, so any MCP server that touches the DB would crash on import.\n//\n// This module picks the backend at runtime and re-exports it as `Database`:\n// - under bun → the real `bun:sqlite` Database (unchanged behavior)\n// - under node → a thin shim over node:sqlite's DatabaseSync exposing the\n// exact subset Otium uses: new Database(path, {readonly?,create?}),\n// .query()/.prepare() → statement, .exec(), .run(), .transaction(fn),\n// .close(); statements support positional `?` params via .run()/.get()/\n// .all(). (No named-object params / .values()/.iterate()/.as() are used in\n// this codebase, so the shim intentionally omits them.)\n//\n// The TYPE of the exported `Database` is bun:sqlite's own class type (imported\n// type-only, so it's erased at runtime and never resolved under node). That\n// keeps every existing call site — including generic `.query<Row, Params>()`\n// usages — type-checking exactly as before with zero changes.\n//\n// The bun branch uses a dynamic import so node never resolves the `bun:sqlite`\n// specifier (dead code under node), and the node branch's `node:sqlite` import\n// never runs under bun.\n\nimport type { Database as BunDatabase } from \"bun:sqlite\";\n\n// `mock.module()` can replace the Bun global while a test graph is being\n// evaluated. The runtime version flag is stable and is also the documented\n// cross-runtime discriminator.\nconst isBun = typeof process.versions.bun === \"string\";\n\ntype DatabaseCtor = typeof BunDatabase;\n\nlet Database: DatabaseCtor;\n\nif (isBun) {\n ({ Database } = await import(\"bun:sqlite\"));\n} else {\n // node:sqlite has no type declarations under our tsconfig (`types: bun-types`\n // only), and `bun-types` doesn't ship them — so type the dynamic import\n // locally and use a `string` specifier to keep tsc from trying to resolve it.\n type NodeStatement = {\n run(...params: unknown[]): unknown;\n get(...params: unknown[]): unknown;\n all(...params: unknown[]): unknown[];\n };\n type NodeDatabaseSync = {\n prepare(sql: string): NodeStatement;\n exec(sql: string): void;\n close(): void;\n };\n type NodeSqliteModule = {\n DatabaseSync: new (path: string, options?: { readOnly?: boolean }) => NodeDatabaseSync;\n };\n // Keep Bun's resolver from eagerly resolving the Node-only builtin even\n // though this branch is dead there (notably under `bun test` + mock.module).\n const nodeSqliteSpecifier = [\"node\", \"sqlite\"].join(\":\");\n const { DatabaseSync } = (await import(nodeSqliteSpecifier)) as NodeSqliteModule;\n\n type DbOptions = { readonly?: boolean; create?: boolean };\n\n class NodeDatabase {\n #db: NodeDatabaseSync;\n\n constructor(path: string, options: DbOptions = {}) {\n // node:sqlite opens read-write and creates-if-missing by default, which\n // matches bun's `{create:true}`. For readonly we must not create.\n this.#db = options.readonly\n ? new DatabaseSync(path, { readOnly: true })\n : new DatabaseSync(path);\n }\n\n query(sql: string) {\n return this.#db.prepare(sql);\n }\n\n prepare(sql: string) {\n return this.#db.prepare(sql);\n }\n\n exec(sql: string): void {\n this.#db.exec(sql);\n }\n\n run(sql: string, ...params: unknown[]) {\n return this.#db.prepare(sql).run(...params);\n }\n\n transaction<Args extends unknown[], R>(fn: (...args: Args) => R): (...args: Args) => R {\n // bun's db.transaction(fn) returns a function that runs fn inside a\n // transaction when called. node:sqlite has no helper, so emulate with\n // BEGIN/COMMIT/ROLLBACK. It also exposes deferred/immediate/exclusive\n // variants; mirror those so Node-launched MCP servers can share call\n // sites with Bun.\n const run =\n (begin: \"BEGIN\" | \"BEGIN DEFERRED\" | \"BEGIN IMMEDIATE\" | \"BEGIN EXCLUSIVE\") =>\n (...args: Args): R => {\n this.#db.exec(begin);\n try {\n const result = fn(...args);\n this.#db.exec(\"COMMIT\");\n return result;\n } catch (err) {\n this.#db.exec(\"ROLLBACK\");\n throw err;\n }\n };\n const tx = run(\"BEGIN\") as ((...args: Args) => R) & {\n deferred: (...args: Args) => R;\n immediate: (...args: Args) => R;\n exclusive: (...args: Args) => R;\n };\n tx.deferred = run(\"BEGIN DEFERRED\");\n tx.immediate = run(\"BEGIN IMMEDIATE\");\n tx.exclusive = run(\"BEGIN EXCLUSIVE\");\n return tx;\n }\n\n close(): void {\n this.#db.close();\n }\n }\n\n Database = NodeDatabase as unknown as DatabaseCtor;\n}\n\nexport { Database };\n",
29
+ "import { createCipheriv, createDecipheriv, createHash, randomBytes } from \"node:crypto\";\n\nconst ENVELOPE_PREFIX = \"otium-vault:v1:\";\nconst IV_BYTES = 12;\nconst KEY_BYTES = 32;\n\nfunction encryptionKey(masterKey: string): 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\nexport function encryptVaultValueWithKey(\n userId: string,\n key: string,\n value: string,\n masterKey: string,\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\nexport function decryptVaultValueWithKey(\n userId: string,\n key: string,\n storedValue: string,\n masterKey: string,\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",
30
+ "import { VAULT_MASTER_KEY } from \"#platform/config\";\nimport {\n decryptVaultValueWithKey,\n encryptVaultValueWithKey,\n isEncryptedVaultValue,\n} from \"#storage/vault-crypto-core\";\n\nexport { isEncryptedVaultValue };\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 return encryptVaultValueWithKey(userId, key, value, masterKey);\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 return decryptVaultValueWithKey(userId, key, storedValue, masterKey);\n}\n"
31
+ ],
32
+ "mappings": ";;;;AASA,sBAAS;AACT,oBAAS;;;ACVT;AACA;AACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AASA;AACA;AACA;AACA;;;ACVO,SAAS,WAAW,CAAC,KAAyB,KAAiC;AAAA,EACpF,MAAM,QAAQ,IAAI,MAAM,KAAK;AAAA,EAC7B,OAAO,SAAS;AAAA;AAGX,SAAS,gBAAgB,CAAC,OAA2B,UAA0B;AAAA,EACpF,IAA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