negotium 0.23.4 → 0.23.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent-helpers.js +29 -4
- package/dist/agent-helpers.js.map +9 -9
- package/dist/background-bash.js +2 -1
- package/dist/background-bash.js.map +3 -3
- package/dist/browser-runtime.js +2 -1
- package/dist/browser-runtime.js.map +3 -3
- package/dist/{chunk-qekt5bnd.js → chunk-ad7kxsaq.js} +4 -2
- package/dist/{chunk-qekt5bnd.js.map → chunk-ad7kxsaq.js.map} +1 -1
- package/dist/{chunk-ggdwn8d5.js → chunk-dtmsberv.js} +3 -3
- package/dist/{chunk-ggdwn8d5.js.map → chunk-dtmsberv.js.map} +2 -2
- package/dist/chunk-f7p0h1gs.js.map +1 -1
- package/dist/{chunk-jarf6nb2.js → chunk-mxxwx5mg.js} +3 -2
- package/dist/{chunk-jarf6nb2.js.map → chunk-mxxwx5mg.js.map} +3 -3
- package/dist/{chunk-vtd5kn4n.js → chunk-n6crwk1s.js} +26 -2
- package/dist/{chunk-vtd5kn4n.js.map → chunk-n6crwk1s.js.map} +7 -7
- package/dist/{chunk-pwafy9bb.js → chunk-ztcj9grz.js} +1 -1
- package/dist/hosted-agent.js +29 -5
- package/dist/hosted-agent.js.map +6 -6
- package/dist/main.js +368 -36
- package/dist/main.js.map +13 -12
- package/dist/mcp-catalog.js +3 -2
- package/dist/mcp-catalog.js.map +3 -3
- package/dist/mcp-factories.js +344 -32
- package/dist/mcp-factories.js.map +11 -10
- package/dist/mcp-servers.js +3 -1
- package/dist/mcp-servers.js.map +3 -3
- package/dist/media.js +2 -1
- package/dist/media.js.map +3 -3
- package/dist/prompts.js +2 -1
- package/dist/prompts.js.map +3 -3
- package/dist/query-runtime.js +2 -1
- package/dist/query-runtime.js.map +3 -3
- package/dist/registry.js +3 -3
- package/dist/rollout.js +2 -2
- package/dist/runtime/src/mcp/canonical-bridge-config.ts +1 -1
- package/dist/runtime/src/mcp/canonical-proxy-server.ts +39 -1
- package/dist/runtime/src/mcp/factories/index.ts +4 -0
- package/dist/runtime/src/mcp/factories/session-history.ts +388 -0
- package/dist/runtime/src/mcp/runtime-spec.ts +1 -0
- package/dist/runtime/src/mcp/session-history-server.ts +27 -0
- package/dist/runtime/src/platform/config.ts +2 -0
- package/dist/runtime/src/platform/mcp-catalog-policy.ts +5 -0
- package/dist/runtime/src/platform/mcp-config.ts +30 -0
- package/dist/runtime/src/storage/topic-archive.ts +4 -2
- package/dist/runtime/src/version.ts +1 -1
- package/dist/runtime-helpers.js +2 -1
- package/dist/runtime-helpers.js.map +3 -3
- package/dist/storage.js +5 -1
- package/dist/storage.js.map +3 -3
- package/dist/types/apps/negotium/src/mcp-servers.d.ts +1 -1
- package/dist/types/packages/core/src/mcp/canonical-bridge-config.d.ts +1 -1
- package/dist/types/packages/core/src/mcp/factories/index.d.ts +1 -0
- package/dist/types/packages/core/src/mcp/factories/session-history.d.ts +11 -0
- package/dist/types/packages/core/src/mcp/runtime-spec.d.ts +1 -1
- package/dist/types/packages/core/src/platform/config.d.ts +1 -0
- package/dist/types/packages/core/src/platform/mcp-catalog-policy.d.ts +4 -0
- package/dist/types/packages/core/src/storage/topic-archive.d.ts +5 -0
- package/dist/types/packages/core/src/version.d.ts +1 -1
- package/dist/vault.js +2 -1
- package/dist/vault.js.map +3 -3
- package/package.json +1 -1
- /package/dist/{chunk-pwafy9bb.js.map → chunk-ztcj9grz.js.map} +0 -0
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"sources": ["../../../packages/core/src/agents/rollout/shared.ts", "../../../packages/core/src/platform/config.ts", "../../../packages/core/src/types.ts", "../../../packages/core/src/platform/config-helpers.ts", "../../../packages/core/src/platform/logger.ts", "../../../packages/core/src/platform/paths.ts", "../../../packages/core/src/runtime/user-turn-envelope.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/agents/explicit-agent-switch.ts", "../../../packages/core/src/mcp/canonical-bridge-config.ts", "../../../packages/core/src/mcp/runtime-spec.ts", "../../../packages/core/src/runtime/actor-topic-scope.ts", "../../../packages/core/src/runtime/remote-session-grant.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/playwright/mcp-transport.ts", "../../../packages/core/src/runtime/cron-sessions.ts", "../../../packages/core/src/platform/constants.ts", "../../../packages/core/src/storage/storage-host.ts", "../../../packages/core/src/storage/sqlite.ts", "../../../packages/core/src/storage/forum-db.ts", "../../../packages/core/src/storage/runtime-topic-state.ts", "../../../packages/core/src/storage/api-messages.ts", "../../../packages/core/src/storage/topic-link-records.ts", "../../../packages/core/src/storage/api-topics.ts", "../../../packages/core/src/platform/mcp-config.ts", "../../../packages/core/src/storage/vault.ts", "../../../packages/core/src/storage/vault-crypto-core.ts", "../../../packages/core/src/storage/vault-crypto.ts", "../../../packages/core/src/agents/rollout/codex.ts", "../../../packages/core/src/platform/jsonl.ts", "../../../packages/core/src/platform/file-utils.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
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 { isInsideDir } from \"#platform/paths\";\nimport { renderUserPromptBatch } from \"#runtime/user-turn-envelope\";\nimport type { ConversationEntry } from \"#storage/conversations\";\nimport type { UnifiedEvent } from \"#types\";\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) => isInsideDir(abs, 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\nexport interface ExtractOptions {\n includeToolAnnotations: boolean;\n formatToolUse?: (event: Extract<UnifiedEvent, { type: \"tool_use\" }>) => string;\n formatToolResult?: (event: Extract<UnifiedEvent, { type: \"tool_result\" }>) => string;\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 Extract<UnifiedEvent, { type: \"tool_use\" }>;\n toolBuffer.push(\n opts.formatToolUse?.(u) ??\n `<!-- Tool: ${u.name} ${truncate(JSON.stringify(u.input), 200)} -->`,\n );\n break;\n }\n case \"tool_result\": {\n const u = ev as Extract<UnifiedEvent, { type: \"tool_result\" }>;\n toolBuffer.push(\n opts.formatToolResult?.(u) ?? `<!-- Tool result: ${truncate(u.content, 200)} -->`,\n );\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, pathToFileURL } from \"node:url\";\nimport {\n parseRuntimePort,\n readEnvText,\n resolveFallbackAgent,\n safeRuntimePathSegment,\n} from \"#platform/config-helpers\";\nimport { logger } from \"#platform/logger\";\nimport { type AgentKind, EFFORT_VALUES, type EffortLevel } from \"#types\";\n\nexport function envText(envKey: string): string | undefined {\n return readEnvText(process.env, envKey);\n}\n\nconst HOME = homedir();\n\nfunction resolveStateDir(): string {\n const configured = envText(\"NEGOTIUM_STATE_DIR\");\n if (process.env.NODE_ENV === \"test\" && !configured) {\n throw new Error(\n \"NEGOTIUM_STATE_DIR must be set before importing #platform/config in test processes\",\n );\n }\n return configured ? resolve(configured) : resolve(HOME, \".negotium\");\n}\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. */\n/**\n * Names a package-manager shim can carry in `node_modules/.bin`.\n *\n * POSIX gets one extension-less executable. Windows has no execute bit, so the\n * installer writes an extension instead — bun produces `<name>.exe` plus a\n * `<name>.bunx` stub, npm a `.cmd`/`.ps1` pair — and probing only the bare name\n * finds nothing, leaving the resolved path pointing at a file that does not\n * exist.\n */\nfunction dependencyBinNames(name: string): string[] {\n if (process.platform !== \"win32\") return [name];\n return [name, `${name}.exe`, `${name}.cmd`, `${name}.bat`, `${name}.bunx`];\n}\n\nfunction resolveDependencyBin(name: string): string {\n let dir = PROJECT_ROOT;\n while (true) {\n const binDir = resolve(dir, \"node_modules\", \".bin\");\n for (const candidate of dependencyBinNames(name)) {\n const path = resolve(binDir, candidate);\n if (existsSync(path)) return path;\n }\n const parent = dirname(dir);\n // Exhausted: hand back the canonical spelling so the failure names the\n // path that was expected.\n if (parent === dir) return resolve(binDir, name);\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).\nexport const STATE_DIR = resolveStateDir();\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 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/**\n * Suffix the managed Rust helpers carry on this platform.\n *\n * The installers write the binary under its plain name, which on Windows is\n * not executable — the release asset is `browser-rs.exe` and the resolver has\n * to look for exactly that. Empty everywhere else, so POSIX paths are\n * unchanged.\n */\nexport const BINARY_EXTENSION = process.platform === \"win32\" ? \".exe\" : \"\";\n\n/** Browser.rs release tested with this Negotium version. */\nexport const BROWSER_RS_VERSION = \"v0.7.7\";\n/** Require the authenticated listener and the current Browser.rs tool contract. */\nexport const BROWSER_RS_MIN_SECURE_VERSION = \"0.2.1\";\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\n/**\n * Ceiling for the `--version` probe, not a latency expectation.\n *\n * The probe exists so a wedged binary cannot hang startup; a healthy one\n * answers in milliseconds. At 2s it also failed whenever the machine was merely\n * busy — process startup under a loaded test suite regularly exceeds that —\n * which turned a correctness check into a load measurement and made\n * `resolveBrowserRsBin` intermittently report a perfectly good binary as\n * unusable. Generous enough that only a genuinely stuck process trips it.\n */\nconst BROWSER_RS_VERSION_PROBE_TIMEOUT_MS = 15_000;\n\nfunction browserRsMeetsMinimumVersion(candidate: string): boolean {\n try {\n const output = execFileSync(candidate, [\"--version\"], {\n encoding: \"utf8\",\n timeout: BROWSER_RS_VERSION_PROBE_TIMEOUT_MS,\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n // This module is imported by every CLI invocation, so on Windows the\n // probe blinked a console window each time `negotium` was run. Ignored\n // on POSIX.\n windowsHide: true,\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${BINARY_EXTENSION}`);\n try {\n accessSync(candidate, constants.X_OK);\n return browserRsMeetsMinimumVersion(candidate) ? candidate : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Backend that stores documents published by `publish_html` and serves them\n * at `<base>/snippets/<id>`. Unset means the deployment has nowhere to\n * publish, and the publish tools are omitted from the catalog rather than\n * offering a link that cannot be minted.\n */\nexport const SNIPPETS_API_URL = (\n envText(\"NEGOTIUM_SNIPPETS_API_URL\") ??\n envText(\"SNIPPETS_API_URL\") ??\n \"\"\n).replace(/\\/+$/, \"\");\n\nexport const BROWSER_RS_BIN = resolveBrowserRsBin(envText(\"NEGOTIUM_BROWSER_RS_BIN\"));\n\n/** bash-rs release tested with this Negotium version — see apps/negotium/install-bash-rs.mjs. */\nexport const BASH_RS_VERSION = \"v0.1.10\";\n\n/**\n * Resolve the bash-rs binary the same way `resolveBrowserRsBin` resolves\n * Browser.rs: a versioned private location, no PATH lookup, `undefined`\n * (rather than throwing) when it's missing. There is no substitute: the manager\n * throws when a turn tries to prepare background-bash without a binary (see\n * `background-bash/manager.ts`), the turn runner catches that and continues\n * with a reminder that the tools are gone, so background-bash is simply\n * unavailable on a platform without a prebuilt binary.\n */\nexport function resolveBashRsBin(envValue?: string): string | undefined {\n const override = envValue?.trim();\n const candidate = override\n ? resolve(override)\n : resolve(BINARIES_DIR, \"bash-rs\", BASH_RS_VERSION, `bash-rs${BINARY_EXTENSION}`);\n try {\n accessSync(candidate, constants.X_OK);\n return candidate;\n } catch {\n return undefined;\n }\n}\n\nexport const BASH_RS_BIN = resolveBashRsBin(envText(\"NEGOTIUM_BASH_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 (\n BROWSER_RS_BIN ??\n resolve(BINARIES_DIR, \"browser-rs\", BROWSER_RS_VERSION, `browser-rs${BINARY_EXTENSION}`)\n );\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/**\n * In-process tsx loader used by Node MCP entrypoints (avoids the tsx CLI child\n * process).\n *\n * `node --import` takes a module specifier, not a filesystem path. A POSIX\n * absolute path happens to be a valid one; a Windows `C:\\…` is not — Node reads\n * the drive letter as a URL scheme and refuses it with\n * ERR_UNSUPPORTED_ESM_URL_SCHEME, which took out every tsx-hosted MCP server\n * (the Codex tool surface) at spawn. Hand it a `file://` URL there, and leave\n * the POSIX value exactly as it was.\n */\nconst TSX_LOADER_PATH = createRequire(import.meta.url).resolve(\"tsx\");\nexport const TSX_LOADER =\n process.platform === \"win32\" ? pathToFileURL(TSX_LOADER_PATH).href : TSX_LOADER_PATH;\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 DECISION_SERVER = resolve(PROJECT_ROOT, \"src/mcp/decision-server.ts\");\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 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);\n/**\n * Stable identity of this node's store, minted once and kept across restarts.\n *\n * Deliberately not a secret: it is published in the gateway health response so a\n * host can tell \"the node I recorded a mapping against\" apart from \"whatever is\n * answering on that port today\". Without it, pointing a host at a different node\n * makes every existing mapping look like a topic whose owner withdrew it, and the\n * same topics come back as duplicate rooms. It shares the secrets directory only\n * because that is already where per-install state that must survive restarts\n * lives; the stricter file mode costs nothing.\n */\nexport const NODE_ID = loadOrCreateLocalSecret(\"NEGOTIUM_NODE_ID\", \"node-id\");\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\");\n/**\n * Passed to `bash-rs` as `BASHRS_SPILL_ROOT`. Each job gets a subdirectory\n * here (`{bash_id}/meta.json`, `result.json`, `stdout.log`, `stderr.log`) —\n * see bash-rs-mcp's `journal.rs`. `runtime/bashrs-completions.ts` watches\n * this directory and turns `result.json` into a session-inbox `tell`. The\n * retired TypeScript server used to write one directly instead.\n */\nexport const BASHRS_SPILL_ROOT = resolve(RUN_DIR, \"bashrs\");\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(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\n/**\n * How an absolute path can start.\n *\n * A POSIX root (`/`) is not the only form once the runtime also runs on\n * Windows, where the same tag carries `C:\\…` or a `\\\\server\\share` UNC path.\n * Anchoring on `/` alone silently dropped every Windows attachment: the tag\n * stayed in the visible text and no file was ever sent.\n */\nconst ABSOLUTE_PATH_PREFIX = String.raw`(?:[A-Za-z]:[\\\\/]|\\\\\\\\|\\/)`;\n\nexport const FILE_EXTENSIONS_REGEX = new RegExp(\n `(?:${ABSOLUTE_PATH_PREFIX}[^\\\\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))`,\n \"gi\",\n);\n\nexport const FILE_TAG_REGEX = new RegExp(`\\\\[FILE:(${ABSOLUTE_PATH_PREFIX}[^\\\\]]+)\\\\]`, \"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-5\";\nexport const MODEL_HAIKU = \"claude-haiku-4-5-20251001\";\nexport const MODEL_FABLE = \"claude-fable-5-1\"; // Mythos-class, Fable 5.1 announced 2026-09-01 (was claude-fable-5)\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// Single agent + model default for the whole node. DEFAULT_* remains a legacy alias.\nexport const FALLBACK_AGENT: AgentKind = resolveFallbackAgent(process.env);\nexport const FALLBACK_MODEL = envText(\"FALLBACK_MODEL\") ?? envText(\"DEFAULT_MODEL\");\n\n/**\n * Effort used when a caller (or an archiver assignment) names a model but no\n * effort. Deliberately one fixed node-wide value instead of each agent's\n * registry default: a model-derived agent switch would otherwise move effort —\n * and therefore cost — without anyone asking for it.\n */\nexport const DEFAULT_TOPIC_EFFORT: EffortLevel = ((): EffortLevel => {\n const raw = envText(\"NEGOTIUM_DEFAULT_EFFORT\")?.toLowerCase();\n return raw && (EFFORT_VALUES as readonly string[]).includes(raw)\n ? (raw as EffortLevel)\n : \"medium\";\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// ── Whisper backend selection ──────────────────────────────────────\n// Different hosts want different whisper runtimes: Apple Silicon Macs get\n// real acceleration from mlx-whisper (see clawgram's transcribe.ts, which\n// this mirrors), while Linux/Ubuntu hubs have no MLX and use the CPU-friendly\n// faster-whisper wrapper instead. Both CLIs accept the same\n// `INPUT --model M --language L --output-dir D --output-format txt` shape\n// and write `{basename}.txt`, so extractFromAudio only needs to pick which\n// binary/args to use — no per-backend parsing logic.\nexport type WhisperBackend = \"faster-whisper\" | \"mlx-whisper\";\nfunction resolveWhisperBackend(): WhisperBackend {\n return envText(\"WHISPER_BACKEND\") === \"mlx-whisper\" ? \"mlx-whisper\" : \"faster-whisper\";\n}\nexport const WHISPER_BACKEND = resolveWhisperBackend();\n/** Path to the `mlx_whisper` CLI (only used when WHISPER_BACKEND=mlx-whisper). */\nexport const MLX_WHISPER_BIN = envText(\"MLX_WHISPER_BIN\");\n/** mlx-whisper model id, e.g. \"mlx-community/whisper-large-v3-turbo\".\n *\n * Deliberately does NOT fall back to WHISPER_MODEL: that env defaults to the\n * bare alias \"turbo\", which faster-whisper's own model-name normalization\n * accepts but mlx_whisper's `--model` does not — it expects a full\n * HuggingFace repo id and otherwise fails hard with a 401\n * RepositoryNotFoundError trying to resolve \"turbo\" as a repo. Confirmed by\n * actually running mlx_whisper with each value while wiring up the\n * mlx-whisper hub in production. */\nexport const WHISPER_MODEL_MLX =\n envText(\"WHISPER_MODEL_MLX\") ?? \"mlx-community/whisper-large-v3-turbo\";\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",
|
|
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, pathToFileURL } from \"node:url\";\nimport {\n parseRuntimePort,\n readEnvText,\n resolveFallbackAgent,\n safeRuntimePathSegment,\n} from \"#platform/config-helpers\";\nimport { logger } from \"#platform/logger\";\nimport { type AgentKind, EFFORT_VALUES, type EffortLevel } from \"#types\";\n\nexport function envText(envKey: string): string | undefined {\n return readEnvText(process.env, envKey);\n}\n\nconst HOME = homedir();\n\nfunction resolveStateDir(): string {\n const configured = envText(\"NEGOTIUM_STATE_DIR\");\n if (process.env.NODE_ENV === \"test\" && !configured) {\n throw new Error(\n \"NEGOTIUM_STATE_DIR must be set before importing #platform/config in test processes\",\n );\n }\n return configured ? resolve(configured) : resolve(HOME, \".negotium\");\n}\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. */\n/**\n * Names a package-manager shim can carry in `node_modules/.bin`.\n *\n * POSIX gets one extension-less executable. Windows has no execute bit, so the\n * installer writes an extension instead — bun produces `<name>.exe` plus a\n * `<name>.bunx` stub, npm a `.cmd`/`.ps1` pair — and probing only the bare name\n * finds nothing, leaving the resolved path pointing at a file that does not\n * exist.\n */\nfunction dependencyBinNames(name: string): string[] {\n if (process.platform !== \"win32\") return [name];\n return [name, `${name}.exe`, `${name}.cmd`, `${name}.bat`, `${name}.bunx`];\n}\n\nfunction resolveDependencyBin(name: string): string {\n let dir = PROJECT_ROOT;\n while (true) {\n const binDir = resolve(dir, \"node_modules\", \".bin\");\n for (const candidate of dependencyBinNames(name)) {\n const path = resolve(binDir, candidate);\n if (existsSync(path)) return path;\n }\n const parent = dirname(dir);\n // Exhausted: hand back the canonical spelling so the failure names the\n // path that was expected.\n if (parent === dir) return resolve(binDir, name);\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).\nexport const STATE_DIR = resolveStateDir();\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 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/**\n * Suffix the managed Rust helpers carry on this platform.\n *\n * The installers write the binary under its plain name, which on Windows is\n * not executable — the release asset is `browser-rs.exe` and the resolver has\n * to look for exactly that. Empty everywhere else, so POSIX paths are\n * unchanged.\n */\nexport const BINARY_EXTENSION = process.platform === \"win32\" ? \".exe\" : \"\";\n\n/** Browser.rs release tested with this Negotium version. */\nexport const BROWSER_RS_VERSION = \"v0.7.7\";\n/** Require the authenticated listener and the current Browser.rs tool contract. */\nexport const BROWSER_RS_MIN_SECURE_VERSION = \"0.2.1\";\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\n/**\n * Ceiling for the `--version` probe, not a latency expectation.\n *\n * The probe exists so a wedged binary cannot hang startup; a healthy one\n * answers in milliseconds. At 2s it also failed whenever the machine was merely\n * busy — process startup under a loaded test suite regularly exceeds that —\n * which turned a correctness check into a load measurement and made\n * `resolveBrowserRsBin` intermittently report a perfectly good binary as\n * unusable. Generous enough that only a genuinely stuck process trips it.\n */\nconst BROWSER_RS_VERSION_PROBE_TIMEOUT_MS = 15_000;\n\nfunction browserRsMeetsMinimumVersion(candidate: string): boolean {\n try {\n const output = execFileSync(candidate, [\"--version\"], {\n encoding: \"utf8\",\n timeout: BROWSER_RS_VERSION_PROBE_TIMEOUT_MS,\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n // This module is imported by every CLI invocation, so on Windows the\n // probe blinked a console window each time `negotium` was run. Ignored\n // on POSIX.\n windowsHide: true,\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${BINARY_EXTENSION}`);\n try {\n accessSync(candidate, constants.X_OK);\n return browserRsMeetsMinimumVersion(candidate) ? candidate : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Backend that stores documents published by `publish_html` and serves them\n * at `<base>/snippets/<id>`. Unset means the deployment has nowhere to\n * publish, and the publish tools are omitted from the catalog rather than\n * offering a link that cannot be minted.\n */\nexport const SNIPPETS_API_URL = (\n envText(\"NEGOTIUM_SNIPPETS_API_URL\") ??\n envText(\"SNIPPETS_API_URL\") ??\n \"\"\n).replace(/\\/+$/, \"\");\n\nexport const BROWSER_RS_BIN = resolveBrowserRsBin(envText(\"NEGOTIUM_BROWSER_RS_BIN\"));\n\n/** bash-rs release tested with this Negotium version — see apps/negotium/install-bash-rs.mjs. */\nexport const BASH_RS_VERSION = \"v0.1.10\";\n\n/**\n * Resolve the bash-rs binary the same way `resolveBrowserRsBin` resolves\n * Browser.rs: a versioned private location, no PATH lookup, `undefined`\n * (rather than throwing) when it's missing. There is no substitute: the manager\n * throws when a turn tries to prepare background-bash without a binary (see\n * `background-bash/manager.ts`), the turn runner catches that and continues\n * with a reminder that the tools are gone, so background-bash is simply\n * unavailable on a platform without a prebuilt binary.\n */\nexport function resolveBashRsBin(envValue?: string): string | undefined {\n const override = envValue?.trim();\n const candidate = override\n ? resolve(override)\n : resolve(BINARIES_DIR, \"bash-rs\", BASH_RS_VERSION, `bash-rs${BINARY_EXTENSION}`);\n try {\n accessSync(candidate, constants.X_OK);\n return candidate;\n } catch {\n return undefined;\n }\n}\n\nexport const BASH_RS_BIN = resolveBashRsBin(envText(\"NEGOTIUM_BASH_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 (\n BROWSER_RS_BIN ??\n resolve(BINARIES_DIR, \"browser-rs\", BROWSER_RS_VERSION, `browser-rs${BINARY_EXTENSION}`)\n );\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/**\n * In-process tsx loader used by Node MCP entrypoints (avoids the tsx CLI child\n * process).\n *\n * `node --import` takes a module specifier, not a filesystem path. A POSIX\n * absolute path happens to be a valid one; a Windows `C:\\…` is not — Node reads\n * the drive letter as a URL scheme and refuses it with\n * ERR_UNSUPPORTED_ESM_URL_SCHEME, which took out every tsx-hosted MCP server\n * (the Codex tool surface) at spawn. Hand it a `file://` URL there, and leave\n * the POSIX value exactly as it was.\n */\nconst TSX_LOADER_PATH = createRequire(import.meta.url).resolve(\"tsx\");\nexport const TSX_LOADER =\n process.platform === \"win32\" ? pathToFileURL(TSX_LOADER_PATH).href : TSX_LOADER_PATH;\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 DECISION_SERVER = resolve(PROJECT_ROOT, \"src/mcp/decision-server.ts\");\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 SESSION_HISTORY_SERVER = resolve(PROJECT_ROOT, \"src/mcp/session-history-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 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);\n/**\n * Stable identity of this node's store, minted once and kept across restarts.\n *\n * Deliberately not a secret: it is published in the gateway health response so a\n * host can tell \"the node I recorded a mapping against\" apart from \"whatever is\n * answering on that port today\". Without it, pointing a host at a different node\n * makes every existing mapping look like a topic whose owner withdrew it, and the\n * same topics come back as duplicate rooms. It shares the secrets directory only\n * because that is already where per-install state that must survive restarts\n * lives; the stricter file mode costs nothing.\n */\nexport const NODE_ID = loadOrCreateLocalSecret(\"NEGOTIUM_NODE_ID\", \"node-id\");\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\");\n/**\n * Passed to `bash-rs` as `BASHRS_SPILL_ROOT`. Each job gets a subdirectory\n * here (`{bash_id}/meta.json`, `result.json`, `stdout.log`, `stderr.log`) —\n * see bash-rs-mcp's `journal.rs`. `runtime/bashrs-completions.ts` watches\n * this directory and turns `result.json` into a session-inbox `tell`. The\n * retired TypeScript server used to write one directly instead.\n */\nexport const BASHRS_SPILL_ROOT = resolve(RUN_DIR, \"bashrs\");\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(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\n/**\n * How an absolute path can start.\n *\n * A POSIX root (`/`) is not the only form once the runtime also runs on\n * Windows, where the same tag carries `C:\\…` or a `\\\\server\\share` UNC path.\n * Anchoring on `/` alone silently dropped every Windows attachment: the tag\n * stayed in the visible text and no file was ever sent.\n */\nconst ABSOLUTE_PATH_PREFIX = String.raw`(?:[A-Za-z]:[\\\\/]|\\\\\\\\|\\/)`;\n\nexport const FILE_EXTENSIONS_REGEX = new RegExp(\n `(?:${ABSOLUTE_PATH_PREFIX}[^\\\\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))`,\n \"gi\",\n);\n\nexport const FILE_TAG_REGEX = new RegExp(`\\\\[FILE:(${ABSOLUTE_PATH_PREFIX}[^\\\\]]+)\\\\]`, \"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-5\";\nexport const MODEL_HAIKU = \"claude-haiku-4-5-20251001\";\nexport const MODEL_FABLE = \"claude-fable-5-1\"; // Mythos-class, Fable 5.1 announced 2026-09-01 (was claude-fable-5)\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// Single agent + model default for the whole node. DEFAULT_* remains a legacy alias.\nexport const FALLBACK_AGENT: AgentKind = resolveFallbackAgent(process.env);\nexport const FALLBACK_MODEL = envText(\"FALLBACK_MODEL\") ?? envText(\"DEFAULT_MODEL\");\n\n/**\n * Effort used when a caller (or an archiver assignment) names a model but no\n * effort. Deliberately one fixed node-wide value instead of each agent's\n * registry default: a model-derived agent switch would otherwise move effort —\n * and therefore cost — without anyone asking for it.\n */\nexport const DEFAULT_TOPIC_EFFORT: EffortLevel = ((): EffortLevel => {\n const raw = envText(\"NEGOTIUM_DEFAULT_EFFORT\")?.toLowerCase();\n return raw && (EFFORT_VALUES as readonly string[]).includes(raw)\n ? (raw as EffortLevel)\n : \"medium\";\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// ── Whisper backend selection ──────────────────────────────────────\n// Different hosts want different whisper runtimes: Apple Silicon Macs get\n// real acceleration from mlx-whisper (see clawgram's transcribe.ts, which\n// this mirrors), while Linux/Ubuntu hubs have no MLX and use the CPU-friendly\n// faster-whisper wrapper instead. Both CLIs accept the same\n// `INPUT --model M --language L --output-dir D --output-format txt` shape\n// and write `{basename}.txt`, so extractFromAudio only needs to pick which\n// binary/args to use — no per-backend parsing logic.\nexport type WhisperBackend = \"faster-whisper\" | \"mlx-whisper\";\nfunction resolveWhisperBackend(): WhisperBackend {\n return envText(\"WHISPER_BACKEND\") === \"mlx-whisper\" ? \"mlx-whisper\" : \"faster-whisper\";\n}\nexport const WHISPER_BACKEND = resolveWhisperBackend();\n/** Path to the `mlx_whisper` CLI (only used when WHISPER_BACKEND=mlx-whisper). */\nexport const MLX_WHISPER_BIN = envText(\"MLX_WHISPER_BIN\");\n/** mlx-whisper model id, e.g. \"mlx-community/whisper-large-v3-turbo\".\n *\n * Deliberately does NOT fall back to WHISPER_MODEL: that env defaults to the\n * bare alias \"turbo\", which faster-whisper's own model-name normalization\n * accepts but mlx_whisper's `--model` does not — it expects a full\n * HuggingFace repo id and otherwise fails hard with a 401\n * RepositoryNotFoundError trying to resolve \"turbo\" as a repo. Confirmed by\n * actually running mlx_whisper with each value while wiring up the\n * mlx-whisper hub in production. */\nexport const WHISPER_MODEL_MLX =\n envText(\"WHISPER_MODEL_MLX\") ?? \"mlx-community/whisper-large-v3-turbo\";\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
7
|
"import type { HostMcpServerSpec } from \"#runtime-gateway\";\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\n/** One topic-scoped decision and its incoming causal edges. */\nexport interface DecisionSnapshot {\n id: string;\n action: string;\n reasoning: string;\n agent: AgentKind;\n model?: string;\n status: \"proposed\" | \"accepted\" | \"executed\" | \"rejected\" | \"superseded\";\n /** Upstream decision ids. Each entry forms a directed upstream -> this edge. */\n causedBy?: string[];\n timestamp: number;\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 /**\n * - `budget_exceeded`: the Claude spend budget (max USD) was hit.\n * - `context_budget_exceeded`: maestro-agent-sdk refused a request that is\n * still over the model's context budget after trimming (SDK >= 0.5.4).\n */\n code?: \"budget_exceeded\" | \"context_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\n/**\n * The rooms the turn's human actor may reach on this node, asserted by the\n * hub that owns per-person membership for the `otium` surface.\n *\n * Node topic ids, valid on the node the turn was submitted to. `visible` is\n * every room the actor participates in (owner or member); `owned` is the\n * subset the actor owns. The assertion rides the signed per-turn MCP token,\n * so the agent can never widen it. With one, it is authoritative: reachable is\n * exactly the current room plus `visible`, owned exactly `owned` — the node\n * adds nothing of its own, not even subagent lineage. A turn without one\n * (older hub, or a turn no person started: cron, self-schedule, a subagent's\n * spawn/report/follow-up) is fail-closed to the current room plus the node's\n * own subagent lineage (direct parent, `grant_subagent_tell` targets, own\n * child workers).\n *\n * `issuedAt` (epoch ms) bounds how long the assertion is believed: this node\n * stamps it when the turn request arrives (the earlier of the hub's own\n * `issuedAt`, if sent, and the receipt time). Past\n * `actorTopicScopeMaxAgeMs()` — or with no `issuedAt` at all — the assertion\n * is stale and grants no cross-room reach (see `isActorTopicScopeFresh`).\n */\nexport interface ActorTopicScope {\n visibleNodeTopicIds: string[];\n ownedNodeTopicIds: string[];\n issuedAt?: number;\n}\n\n/**\n * Hub-issued authority for the `node/topic` branches of `session-comm` on\n * the `otium` surface, one per turn. `capability` is an opaque bearer\n * (`rsc1.<payload>.<hmac>`) only the hub can verify: it binds the person who\n * spoke, the origin room and this turn's request id, and the hub re-checks\n * the person's membership of the origin and target rooms on every call. The\n * node holds no key, so it can neither mint nor verify one; the only thing it\n * reads out of the payload is `e` (expiry), base64-decoded untrusted to order\n * grants when several requests fold into one turn. `hubUrl` is where the\n * node presents it (`/api/v1/session-comm/remote/*`). Absent — an older hub,\n * a hub with the feature off, or a turn no person started (cron,\n * self-schedule, subagent lineage) — remote session-comm stays fail-closed.\n */\nexport interface RemoteSessionGrant {\n hubUrl: string;\n capability: string;\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 /**\n * Trusted system-level instructions for this Maestro invocation only.\n * Maestro projects them onto the invocation-start user message without\n * persisting them in session history or compaction. Omitted for Claude/Codex.\n */\n ephemeralSystemPrompt?: string;\n userId?: string;\n /** Product actor identity when execution uses a canonical node principal. */\n actorUserId?: string;\n /** Hub-asserted rooms the product actor may reach; absent means fail-closed. */\n actorTopicScope?: ActorTopicScope;\n /** Hub-issued per-turn authority for remote (`node/topic`) session-comm. */\n remoteSession?: RemoteSessionGrant;\n /** Credential namespace when it differs from the execution principal. */\n vaultUserId?: 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 /** Validated host MCPs resolved from durable manager-room grants at execution time. */\n hostMcpServers?: Record<string, HostMcpServerSpec>;\n /**\n * Thread this turn answers inside, so the turn's runtime MCP can default\n * `thread_read` to it. Turn-scoped, unlike the session, which is per topic.\n */\n threadRootId?: string;\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",
|
|
8
8
|
"import { resolve } from \"node:path\";\nimport { type AgentKind, isAgentKind } from \"#types\";\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\n/**\n * Node-wide default agent (FALLBACK_AGENT env, legacy DEFAULT_AGENT, else\n * \"claude\"). Lives in this side-effect-free leaf module — not #platform/config\n * — so storage layers that only need this one value (e.g. the forum/api-topics\n * repositories, re-exported through the public storage facade) don't drag in\n * config.ts's eager `mkdirSync` of every node data directory just by\n * importing it.\n */\nexport function resolveFallbackAgent(env: RuntimeEnvironment = process.env): AgentKind {\n const value = readEnvText(env, \"FALLBACK_AGENT\") ?? readEnvText(env, \"DEFAULT_AGENT\");\n return isAgentKind(value) ? value : \"claude\";\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",
|
|
9
9
|
"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",
|
|
@@ -13,15 +13,15 @@
|
|
|
13
13
|
"import { realpathSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { toDisplayPath } from \"#platform/paths\";\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 // Every pattern above anchors on \"/\". `resolve` returns the host separator,\n // so on Windows each one silently stopped matching and the whole blacklist\n // became inert. Compare against a \"/\"-separated rendering instead; on POSIX\n // `toDisplayPath` is the identity, so matching there is unchanged.\n if (SENSITIVE_PATH_PATTERNS.some((p) => p.test(toDisplayPath(normalized)))) return true;\n try {\n const real = realpathSync(normalized);\n if (real !== normalized) {\n return SENSITIVE_PATH_PATTERNS.some((p) => p.test(toDisplayPath(real)));\n }\n } catch {\n // File doesn't exist — no symlink concern\n }\n return false;\n}\n",
|
|
14
14
|
"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 function referencesRuntimeSecretStorage(value: unknown): boolean {\n if (typeof value === \"string\") {\n const lower = value.toLowerCase();\n if (SENSITIVE_RUNTIME_NAMES.some((name) => lower.includes(name))) return true;\n return value.startsWith(\"/\") && isSensitivePath(value);\n }\n if (Array.isArray(value)) return value.some(referencesRuntimeSecretStorage);\n if (value && typeof value === \"object\") {\n return Object.values(value as Record<string, unknown>).some(referencesRuntimeSecretStorage);\n }\n return false;\n}\n",
|
|
15
15
|
"/**\n * The explicit-switch gate behind `set_agent`: an agent may move a topic to\n * another backend only when the *person's* current message asked for it.\n *\n * The decision is derived here, once, from the full prompt on the node that\n * mints the per-turn runtime MCP token, and the token then carries only the\n * result ({@link explicitAgentSwitchTargets}) — a bounded list of agent kinds\n * — instead of the prompt itself. That keeps the token small whatever the\n * prompt's length and means a long message cannot push the phrase past a\n * cap and turn a request the user made into a refusal.\n */\nimport { type AgentKind, SUPPORTED_AGENTS } from \"#types\";\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\nfunction agentAliases(agent: AgentKind): string[] {\n switch (agent) {\n case \"codex\":\n return [\n \"codex\",\n \"코덱스\",\n \"astra\",\n \"sol\",\n \"luna\",\n \"terra\",\n \"gpt-6-luna\",\n \"gpt-6-sol\",\n \"gpt-5.6-luna\",\n \"gpt-6.1-terra\",\n \"gpt-5.6-terra\",\n \"gpt-5.6-sol\",\n \"gpt-6-astra\",\n ];\n case \"claude\":\n return [\"claude\", \"클로드\", \"sonnet\", \"opus\", \"fable\"];\n case \"maestro\":\n return [\n \"maestro\",\n \"마에스트로\",\n \"메스트로\",\n \"deepseek\",\n \"deepseek-pro\",\n \"kimi\",\n \"kimi-pro\",\n \"kimi-k3\",\n \"kimi-code\",\n \"kimi-k2.7-code\",\n \"딥시크\",\n \"키미\",\n ];\n }\n}\n\n/** Whether `prompt` explicitly asks to switch this topic to `agent`. */\nexport function hasExplicitAgentSwitchRequest(\n prompt: string | undefined,\n agent: AgentKind,\n): boolean {\n if (!prompt?.trim()) return false;\n const text = prompt.toLowerCase().replace(/\\s+/g, \" \").trim();\n const target = `(?<![A-Za-z0-9_-])(?:${agentAliases(agent).map(escapeRegExp).join(\"|\")})(?![A-Za-z0-9_-])`;\n const switchVerb =\n \"(?:바꿔|바꿔줘|변경|변경해|전환|전환해|설정|설정해|써줘|사용|가|switch|change|set|use)\";\n const switchSubject = \"(?:agent|runtime|model|에이전트|런타임|모델)\";\n\n return [\n new RegExp(`^/(?:agent|runtime)\\\\s+${target}(?:\\\\s|$)`, \"iu\"),\n new RegExp(`${target}\\\\s*(?:로|으로)\\\\s*.{0,16}${switchVerb}`, \"iu\"),\n new RegExp(`${switchSubject}.{0,24}${target}.{0,24}${switchVerb}`, \"iu\"),\n new RegExp(`${switchVerb}.{0,24}${switchSubject}.{0,24}${target}`, \"iu\"),\n new RegExp(`(?:switch|change|set|use).{0,24}${target}`, \"iu\"),\n ].some((pattern) => pattern.test(text));\n}\n\n/**\n * The agents `prompt` explicitly asks to switch to, in {@link SUPPORTED_AGENTS}\n * order — the same test as {@link hasExplicitAgentSwitchRequest}, evaluated for\n * every agent kind over the whole prompt. Empty when nothing was asked for.\n */\nexport function explicitAgentSwitchTargets(prompt: string | undefined): AgentKind[] {\n if (!prompt?.trim()) return [];\n return SUPPORTED_AGENTS.filter((agent) => hasExplicitAgentSwitchRequest(prompt, agent));\n}\n\n/**\n * Shape check for the derived field where it crosses a trust boundary (the\n * signed token): a de-duplicated list of known agent kinds. It cannot hold\n * more entries than there are agents, so its size is fixed.\n */\nexport function isExplicitAgentSwitchTargets(value: unknown): value is AgentKind[] {\n return (\n Array.isArray(value) &&\n value.length <= SUPPORTED_AGENTS.length &&\n value.every((item, index) => isAgentKindUnique(value, item, index))\n );\n}\n\nfunction isAgentKindUnique(list: unknown[], item: unknown, index: number): boolean {\n return (\n typeof item === \"string\" &&\n (SUPPORTED_AGENTS as readonly string[]).includes(item) &&\n list.indexOf(item) === index\n );\n}\n",
|
|
16
|
-
"import type { PeerRuntimeBridgeContext } from \"#types\";\n\nexport type CanonicalMcpSurface = \"task\" | \"decision\" | \"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",
|
|
17
|
-
"/**\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 { createHash, createHmac, timingSafeEqual } from \"node:crypto\";\nimport { isExplicitAgentSwitchTargets } from \"#agents/explicit-agent-switch\";\nimport { NEGOTIUM_PORT, RUNTIME_MCP_SECRET } from \"#platform/config\";\nimport { logger } from \"#platform/logger\";\nimport { isActorTopicScope } from \"#runtime/actor-topic-scope\";\nimport { isRemoteSessionGrant } from \"#runtime/remote-session-grant\";\nimport {\n type ActorTopicScope,\n type AgentKind,\n isAgentKind,\n type PeerRuntimeBridgeContext,\n type RemoteSessionGrant,\n} 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 \"decision\",\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\n/**\n * Hard ceiling on the length of a built-in MCP URL (path plus `?token=...`).\n *\n * The signed per-turn token rides the URL query of an `http://127.0.0.1`\n * request, and `Bun.serve` answers 431 once the request line is too long:\n * measured on Bun 1.3.14 with a plain `fetch`, a 16,205-character URL is\n * served (200) and a 16,305-character one is refused (431). The budget stays\n * 1,869 characters under the last known-good length so the server, the\n * agent's own client and a slightly different Bun release all have room.\n *\n * Real sizes (UUID ids, base64url growth of 4/3 on the JSON payload):\n * - runtime token, no assertion, every optional field set (peer bridge,\n * thread, 64-char title, workspace cwd, all three explicit-switch\n * targets): ~1,150-character URL;\n * - the same with the largest assertion `validateActorTopicScope` admits\n * (8,159 bytes of JSON = 208 UUIDs): 12,052–12,055 characters, under this\n * budget with ~2,280 characters to spare for an unusually long cwd or title;\n * the hosted tokens (`buildHostedMcpSpec`) with the same assertion measure\n * 12,100–12,118, so neither variant is the \"small\" one.\n * The token has no free-text field: the user's prompt never rides it. It used\n * to, and an uncapped prompt made the assertion cap meaningless (3,000 Korean\n * characters on top of the maximal assertion gave a 24,009-character URL and\n * 10,000 gave 52,009 — every built-in MCP unreachable for that turn), while a\n * capped one broke `set_agent` for any request phrased after the cap. The\n * prompt's only consumer was that gate, so the node now derives the gate's\n * answer from the full prompt when it mints the token\n * (`explicitAgentSwitchTargets`, at most three agent names) and signs that.\n *\n * Over budget, {@link buildRuntimeMcpSpec} throws\n * {@link McpUrlBudgetExceededError} rather than minting a URL that will 431.\n * Nothing is dropped or trimmed to fit: every remaining field either\n * authorizes (ids, assertion, switch targets) or changes behaviour (thread,\n * capabilities, bridge), and a token missing one would widen or alter the\n * turn, not narrow it.\n */\nexport const MCP_URL_BUDGET_CHARS = 14 * 1024;\n\nexport class McpUrlBudgetExceededError extends Error {\n constructor(\n readonly surface: string,\n readonly urlLength: number,\n ) {\n super(\n `built-in MCP URL for \"${surface}\" is ${urlLength} characters; the transport allows at most ${MCP_URL_BUDGET_CHARS}`,\n );\n this.name = \"McpUrlBudgetExceededError\";\n }\n}\n\nexport interface RuntimeMcpContext {\n /** Canonical principal authorized against this node's topic roster. */\n userId: string;\n /** Product-side human actor when it differs from the execution principal. */\n actorUserId?: string;\n /**\n * Hub-asserted rooms `actorUserId` may reach on this node. Signed with the\n * rest of the context and authoritative when present (no lineage is added);\n * absent means the tools reach only the current room plus its own subagent\n * lineage.\n */\n actorTopicScope?: ActorTopicScope;\n topicId: string;\n topicTitle: string;\n queryId?: string;\n cwd: string;\n agent: AgentKind;\n model?: string;\n /**\n * Agents the current user message explicitly asked to switch to, derived\n * from the full prompt at mint time (`explicitAgentSwitchTargets`). Signed\n * with the rest of the context, so the agent cannot grant itself a switch;\n * absent or empty means `set_agent` is refused this turn.\n */\n explicitAgentSwitchTargets?: AgentKind[];\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 /**\n * Thread this turn is answering inside, when it is answering in one.\n *\n * The runtime MCP is built per turn from a signed token, so unlike the\n * session — which spans the whole topic — this context can carry a value\n * that changes from one turn to the next. That is what lets `thread_read`\n * default to \"the thread I am in\" with no argument.\n */\n threadRootId?: string;\n peerBridge?: PeerRuntimeBridgeContext;\n}\n\n/** Signed identity/capability context shared by hosted built-in MCP surfaces. */\nexport interface HostedMcpContext {\n userId: string;\n /** Product-side human actor when it differs from the execution principal. */\n actorUserId?: string;\n /** Hub-asserted rooms `actorUserId` may reach; see {@link RuntimeMcpContext}. */\n actorTopicScope?: ActorTopicScope;\n /**\n * Hub-issued per-turn authority for remote (`node/topic`) session-comm.\n * Carried by the `session-comm` audience only. Signed with the rest of the\n * context so the agent cannot mint or swap one; the capability inside is a\n * bearer for the hub, which the node cannot verify (it holds no key) and\n * only ever decodes for the untrusted `e` expiry it uses to order grants\n * when several requests fold into one turn.\n */\n remoteSession?: RemoteSessionGrant;\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 /**\n * Thread the calling turn is answering inside.\n *\n * Present on the hosted surface as well as the stdio one: `session-comm` is\n * served both ways, and the hosted path — the default — carries its context\n * in a signed per-turn token rather than in argv.\n */\n threadRootId?: string;\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.actorUserId === undefined || typeof ctx.actorUserId === \"string\") &&\n (ctx.actorTopicScope === undefined || isActorTopicScope(ctx.actorTopicScope)) &&\n (ctx.queryId === undefined || typeof ctx.queryId === \"string\") &&\n (ctx.model === undefined || typeof ctx.model === \"string\") &&\n (ctx.explicitAgentSwitchTargets === undefined ||\n isExplicitAgentSwitchTargets(ctx.explicitAgentSwitchTargets)) &&\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.actorUserId === undefined || typeof ctx.actorUserId === \"string\") &&\n (ctx.actorTopicScope === undefined || isActorTopicScope(ctx.actorTopicScope)) &&\n (ctx.remoteSession === undefined || isRemoteSessionGrant(ctx.remoteSession)) &&\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 base = `http://127.0.0.1:${runtimePort}${RUNTIME_MCP_BASE_PATH}`;\n const query = `token=${encodeURIComponent(issueRuntimeMcpToken(ctx))}`;\n const url = agent === \"codex\" ? `${base}/mcp?${query}` : `${base}/sse?${query}`;\n assertMcpUrlWithinBudget(RUNTIME_MCP_KEY, url, ctx.topicId);\n if (agent === \"codex\") return { url };\n return {\n type: \"sse\" as const,\n url,\n timeout: CLAUDE_MCP_TOOL_TIMEOUT_MS,\n ...(agent === \"maestro\" ? { lifecycle: \"turn\" as const } : {}),\n };\n}\n\n/**\n * Refuse loudly rather than hand the agent a URL the server will 431. This\n * fails the turn's MCP setup, which is the safe outcome: the alternative —\n * minting the token without the fields that do not fit — would silently\n * widen the turn whenever the field that did not fit was the assertion.\n */\nfunction assertMcpUrlWithinBudget(surface: string, url: string, topicId: string | undefined) {\n if (url.length <= MCP_URL_BUDGET_CHARS) return;\n const error = new McpUrlBudgetExceededError(surface, url.length);\n logger.error(\n { topicId, surface, urlLength: url.length, budget: MCP_URL_BUDGET_CHARS },\n \"built-in MCP URL exceeds the transport budget; refusing to mint the token\",\n );\n throw error;\n}\n\nfunction hostedMcpCacheIdentity(surface: HostedMcpSurface, ctx: HostedMcpContext): string {\n let semanticContext: unknown;\n switch (surface) {\n case \"system-health\":\n semanticContext = {};\n break;\n case \"token-stats\":\n case \"agent-health\":\n semanticContext = { userId: ctx.userId };\n break;\n case \"task\":\n semanticContext = {\n userId: ctx.userId,\n topicTitle: ctx.topicTitle,\n topicId: ctx.topicId ?? null,\n };\n break;\n case \"wiki\":\n case \"skills\":\n semanticContext = {\n userId: ctx.userId,\n topicId: ctx.wikiTopicId ?? ctx.topicId ?? null,\n };\n break;\n case \"vault\":\n semanticContext = { userId: ctx.userId, cwd: ctx.cwd, agent: ctx.agent };\n break;\n case \"session-comm\":\n semanticContext = {\n userId: ctx.userId,\n // Who may reach what changes per turn (a different person, or a hub\n // that has since changed a roster), so a cached server must not carry\n // an earlier turn's reach into this one.\n actorUserId: ctx.actorUserId ?? null,\n actorTopicScope: ctx.actorTopicScope ?? null,\n // The grant is per turn (bound to this turn's request id), so a\n // server cached with one must not answer a later turn with it.\n remoteSession: ctx.remoteSession ?? null,\n topicTitle: ctx.topicTitle,\n topicId: ctx.topicId ?? null,\n subagentParentTopicId: ctx.subagentParentTopicId ?? null,\n depth: ctx.depth ?? 0,\n silent: ctx.silent ?? false,\n agent: ctx.agent,\n // Part of the identity, not a detail: a server cached for a channel\n // turn would otherwise be reused for a thread turn and record the ask\n // against the wrong conversation.\n threadRootId: ctx.threadRootId ?? null,\n peerBridge: ctx.peerBridge ?? null,\n };\n break;\n }\n const digest = createHash(\"sha256\")\n .update(JSON.stringify([surface, semanticContext]))\n .digest(\"hex\")\n .slice(0, 24);\n return `hosted:${surface}:${digest}`;\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 const url = agent === \"codex\" ? `${base}/mcp?${query}` : `${base}/sse?${query}`;\n // A hosted context has no free-text field either. Measured with the\n // maximal assertion (208 UUIDs, 8,159 bytes) and every optional field set,\n // the hosted URL is marginally *longer* than the runtime one — ~12,118\n // characters for `session-comm`, 12,100–12,109 for the other surfaces,\n // against 12,052–12,055 for the runtime token — because the surface name\n // and lifecycle fields outweigh the runtime token's switch-target list.\n // All stay ≥ 2,200 characters under budget. The session-comm token may\n // additionally carry a remote-session grant. Measured in\n // `hosted-runtime-spec.test.ts`: the hub's real grant (≈440-character\n // capability, short hub URL) adds 682 characters — 12,800 beside the\n // maximal assertion, ~1,500 to spare. A grant at both caps (512-char URL,\n // 2 KiB capability) adds ≈3,475 and fits alone (4,689) but not beside the\n // maximal assertion (15,593); the hard check below refuses that mint, so\n // the caps bound the grant while the budget bounds the token — the largest\n // capability that fits beside a maximal assertion is ≈1,590 characters.\n // The check is the same on purpose, so a field added later cannot quietly\n // push it past the transport.\n assertMcpUrlWithinBudget(surface, url, ctx.topicId);\n if (agent === \"codex\") return { url };\n const queryBound =\n surface === \"session-comm\" &&\n (ctx.silent === true || ctx.peerBridge !== undefined || ctx.remoteSession !== undefined);\n const lifecycle = queryBound ? \"turn\" : surface === \"session-comm\" ? \"session\" : \"process\";\n return {\n type: \"sse\" as const,\n url,\n timeout: CLAUDE_MCP_TOOL_TIMEOUT_MS,\n ...(agent === \"maestro\"\n ? {\n lifecycle,\n cacheKey: hostedMcpCacheIdentity(surface, ctx),\n }\n : {}),\n };\n}\n",
|
|
16
|
+
"import type { PeerRuntimeBridgeContext } from \"#types\";\n\nexport type CanonicalMcpSurface = \"task\" | \"decision\" | \"wiki\" | \"session-history\";\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",
|
|
17
|
+
"/**\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 { createHash, createHmac, timingSafeEqual } from \"node:crypto\";\nimport { isExplicitAgentSwitchTargets } from \"#agents/explicit-agent-switch\";\nimport { NEGOTIUM_PORT, RUNTIME_MCP_SECRET } from \"#platform/config\";\nimport { logger } from \"#platform/logger\";\nimport { isActorTopicScope } from \"#runtime/actor-topic-scope\";\nimport { isRemoteSessionGrant } from \"#runtime/remote-session-grant\";\nimport {\n type ActorTopicScope,\n type AgentKind,\n isAgentKind,\n type PeerRuntimeBridgeContext,\n type RemoteSessionGrant,\n} 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 \"decision\",\n \"token-stats\",\n \"system-health\",\n \"vault\",\n \"wiki\",\n \"skills\",\n \"session-comm\",\n \"agent-health\",\n \"session-history\",\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\n/**\n * Hard ceiling on the length of a built-in MCP URL (path plus `?token=...`).\n *\n * The signed per-turn token rides the URL query of an `http://127.0.0.1`\n * request, and `Bun.serve` answers 431 once the request line is too long:\n * measured on Bun 1.3.14 with a plain `fetch`, a 16,205-character URL is\n * served (200) and a 16,305-character one is refused (431). The budget stays\n * 1,869 characters under the last known-good length so the server, the\n * agent's own client and a slightly different Bun release all have room.\n *\n * Real sizes (UUID ids, base64url growth of 4/3 on the JSON payload):\n * - runtime token, no assertion, every optional field set (peer bridge,\n * thread, 64-char title, workspace cwd, all three explicit-switch\n * targets): ~1,150-character URL;\n * - the same with the largest assertion `validateActorTopicScope` admits\n * (8,159 bytes of JSON = 208 UUIDs): 12,052–12,055 characters, under this\n * budget with ~2,280 characters to spare for an unusually long cwd or title;\n * the hosted tokens (`buildHostedMcpSpec`) with the same assertion measure\n * 12,100–12,118, so neither variant is the \"small\" one.\n * The token has no free-text field: the user's prompt never rides it. It used\n * to, and an uncapped prompt made the assertion cap meaningless (3,000 Korean\n * characters on top of the maximal assertion gave a 24,009-character URL and\n * 10,000 gave 52,009 — every built-in MCP unreachable for that turn), while a\n * capped one broke `set_agent` for any request phrased after the cap. The\n * prompt's only consumer was that gate, so the node now derives the gate's\n * answer from the full prompt when it mints the token\n * (`explicitAgentSwitchTargets`, at most three agent names) and signs that.\n *\n * Over budget, {@link buildRuntimeMcpSpec} throws\n * {@link McpUrlBudgetExceededError} rather than minting a URL that will 431.\n * Nothing is dropped or trimmed to fit: every remaining field either\n * authorizes (ids, assertion, switch targets) or changes behaviour (thread,\n * capabilities, bridge), and a token missing one would widen or alter the\n * turn, not narrow it.\n */\nexport const MCP_URL_BUDGET_CHARS = 14 * 1024;\n\nexport class McpUrlBudgetExceededError extends Error {\n constructor(\n readonly surface: string,\n readonly urlLength: number,\n ) {\n super(\n `built-in MCP URL for \"${surface}\" is ${urlLength} characters; the transport allows at most ${MCP_URL_BUDGET_CHARS}`,\n );\n this.name = \"McpUrlBudgetExceededError\";\n }\n}\n\nexport interface RuntimeMcpContext {\n /** Canonical principal authorized against this node's topic roster. */\n userId: string;\n /** Product-side human actor when it differs from the execution principal. */\n actorUserId?: string;\n /**\n * Hub-asserted rooms `actorUserId` may reach on this node. Signed with the\n * rest of the context and authoritative when present (no lineage is added);\n * absent means the tools reach only the current room plus its own subagent\n * lineage.\n */\n actorTopicScope?: ActorTopicScope;\n topicId: string;\n topicTitle: string;\n queryId?: string;\n cwd: string;\n agent: AgentKind;\n model?: string;\n /**\n * Agents the current user message explicitly asked to switch to, derived\n * from the full prompt at mint time (`explicitAgentSwitchTargets`). Signed\n * with the rest of the context, so the agent cannot grant itself a switch;\n * absent or empty means `set_agent` is refused this turn.\n */\n explicitAgentSwitchTargets?: AgentKind[];\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 /**\n * Thread this turn is answering inside, when it is answering in one.\n *\n * The runtime MCP is built per turn from a signed token, so unlike the\n * session — which spans the whole topic — this context can carry a value\n * that changes from one turn to the next. That is what lets `thread_read`\n * default to \"the thread I am in\" with no argument.\n */\n threadRootId?: string;\n peerBridge?: PeerRuntimeBridgeContext;\n}\n\n/** Signed identity/capability context shared by hosted built-in MCP surfaces. */\nexport interface HostedMcpContext {\n userId: string;\n /** Product-side human actor when it differs from the execution principal. */\n actorUserId?: string;\n /** Hub-asserted rooms `actorUserId` may reach; see {@link RuntimeMcpContext}. */\n actorTopicScope?: ActorTopicScope;\n /**\n * Hub-issued per-turn authority for remote (`node/topic`) session-comm.\n * Carried by the `session-comm` audience only. Signed with the rest of the\n * context so the agent cannot mint or swap one; the capability inside is a\n * bearer for the hub, which the node cannot verify (it holds no key) and\n * only ever decodes for the untrusted `e` expiry it uses to order grants\n * when several requests fold into one turn.\n */\n remoteSession?: RemoteSessionGrant;\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 /**\n * Thread the calling turn is answering inside.\n *\n * Present on the hosted surface as well as the stdio one: `session-comm` is\n * served both ways, and the hosted path — the default — carries its context\n * in a signed per-turn token rather than in argv.\n */\n threadRootId?: string;\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.actorUserId === undefined || typeof ctx.actorUserId === \"string\") &&\n (ctx.actorTopicScope === undefined || isActorTopicScope(ctx.actorTopicScope)) &&\n (ctx.queryId === undefined || typeof ctx.queryId === \"string\") &&\n (ctx.model === undefined || typeof ctx.model === \"string\") &&\n (ctx.explicitAgentSwitchTargets === undefined ||\n isExplicitAgentSwitchTargets(ctx.explicitAgentSwitchTargets)) &&\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.actorUserId === undefined || typeof ctx.actorUserId === \"string\") &&\n (ctx.actorTopicScope === undefined || isActorTopicScope(ctx.actorTopicScope)) &&\n (ctx.remoteSession === undefined || isRemoteSessionGrant(ctx.remoteSession)) &&\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 base = `http://127.0.0.1:${runtimePort}${RUNTIME_MCP_BASE_PATH}`;\n const query = `token=${encodeURIComponent(issueRuntimeMcpToken(ctx))}`;\n const url = agent === \"codex\" ? `${base}/mcp?${query}` : `${base}/sse?${query}`;\n assertMcpUrlWithinBudget(RUNTIME_MCP_KEY, url, ctx.topicId);\n if (agent === \"codex\") return { url };\n return {\n type: \"sse\" as const,\n url,\n timeout: CLAUDE_MCP_TOOL_TIMEOUT_MS,\n ...(agent === \"maestro\" ? { lifecycle: \"turn\" as const } : {}),\n };\n}\n\n/**\n * Refuse loudly rather than hand the agent a URL the server will 431. This\n * fails the turn's MCP setup, which is the safe outcome: the alternative —\n * minting the token without the fields that do not fit — would silently\n * widen the turn whenever the field that did not fit was the assertion.\n */\nfunction assertMcpUrlWithinBudget(surface: string, url: string, topicId: string | undefined) {\n if (url.length <= MCP_URL_BUDGET_CHARS) return;\n const error = new McpUrlBudgetExceededError(surface, url.length);\n logger.error(\n { topicId, surface, urlLength: url.length, budget: MCP_URL_BUDGET_CHARS },\n \"built-in MCP URL exceeds the transport budget; refusing to mint the token\",\n );\n throw error;\n}\n\nfunction hostedMcpCacheIdentity(surface: HostedMcpSurface, ctx: HostedMcpContext): string {\n let semanticContext: unknown;\n switch (surface) {\n case \"system-health\":\n semanticContext = {};\n break;\n case \"token-stats\":\n case \"agent-health\":\n semanticContext = { userId: ctx.userId };\n break;\n case \"task\":\n semanticContext = {\n userId: ctx.userId,\n topicTitle: ctx.topicTitle,\n topicId: ctx.topicId ?? null,\n };\n break;\n case \"wiki\":\n case \"skills\":\n semanticContext = {\n userId: ctx.userId,\n topicId: ctx.wikiTopicId ?? ctx.topicId ?? null,\n };\n break;\n case \"vault\":\n semanticContext = { userId: ctx.userId, cwd: ctx.cwd, agent: ctx.agent };\n break;\n case \"session-comm\":\n semanticContext = {\n userId: ctx.userId,\n // Who may reach what changes per turn (a different person, or a hub\n // that has since changed a roster), so a cached server must not carry\n // an earlier turn's reach into this one.\n actorUserId: ctx.actorUserId ?? null,\n actorTopicScope: ctx.actorTopicScope ?? null,\n // The grant is per turn (bound to this turn's request id), so a\n // server cached with one must not answer a later turn with it.\n remoteSession: ctx.remoteSession ?? null,\n topicTitle: ctx.topicTitle,\n topicId: ctx.topicId ?? null,\n subagentParentTopicId: ctx.subagentParentTopicId ?? null,\n depth: ctx.depth ?? 0,\n silent: ctx.silent ?? false,\n agent: ctx.agent,\n // Part of the identity, not a detail: a server cached for a channel\n // turn would otherwise be reused for a thread turn and record the ask\n // against the wrong conversation.\n threadRootId: ctx.threadRootId ?? null,\n peerBridge: ctx.peerBridge ?? null,\n };\n break;\n }\n const digest = createHash(\"sha256\")\n .update(JSON.stringify([surface, semanticContext]))\n .digest(\"hex\")\n .slice(0, 24);\n return `hosted:${surface}:${digest}`;\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 const url = agent === \"codex\" ? `${base}/mcp?${query}` : `${base}/sse?${query}`;\n // A hosted context has no free-text field either. Measured with the\n // maximal assertion (208 UUIDs, 8,159 bytes) and every optional field set,\n // the hosted URL is marginally *longer* than the runtime one — ~12,118\n // characters for `session-comm`, 12,100–12,109 for the other surfaces,\n // against 12,052–12,055 for the runtime token — because the surface name\n // and lifecycle fields outweigh the runtime token's switch-target list.\n // All stay ≥ 2,200 characters under budget. The session-comm token may\n // additionally carry a remote-session grant. Measured in\n // `hosted-runtime-spec.test.ts`: the hub's real grant (≈440-character\n // capability, short hub URL) adds 682 characters — 12,800 beside the\n // maximal assertion, ~1,500 to spare. A grant at both caps (512-char URL,\n // 2 KiB capability) adds ≈3,475 and fits alone (4,689) but not beside the\n // maximal assertion (15,593); the hard check below refuses that mint, so\n // the caps bound the grant while the budget bounds the token — the largest\n // capability that fits beside a maximal assertion is ≈1,590 characters.\n // The check is the same on purpose, so a field added later cannot quietly\n // push it past the transport.\n assertMcpUrlWithinBudget(surface, url, ctx.topicId);\n if (agent === \"codex\") return { url };\n const queryBound =\n surface === \"session-comm\" &&\n (ctx.silent === true || ctx.peerBridge !== undefined || ctx.remoteSession !== undefined);\n const lifecycle = queryBound ? \"turn\" : surface === \"session-comm\" ? \"session\" : \"process\";\n return {\n type: \"sse\" as const,\n url,\n timeout: CLAUDE_MCP_TOOL_TIMEOUT_MS,\n ...(agent === \"maestro\"\n ? {\n lifecycle,\n cacheKey: hostedMcpCacheIdentity(surface, ctx),\n }\n : {}),\n };\n}\n",
|
|
18
18
|
"import type { ActorTopicScope } from \"#types\";\n\n/**\n * Hard caps on a hub-supplied room assertion.\n *\n * The assertion is not stored and forgotten: it rides the signed per-turn MCP\n * token, which every hosted built-in MCP server receives in the URL query\n * (`?token=`) of an `http://127.0.0.1` request, and — with\n * `NEGOTIUM_BUILTIN_MCP_TRANSPORT=stdio` — one base64url argv entry of the\n * session-comm child. The transport, not the database, is the tight bound:\n *\n * - `Bun.serve` answers 431 once the request line is too long (Bun 1.3.14:\n * a 16,205-character URL is served, 16,305 is refused). These caps alone\n * do not bound the URL — the token carries other fields — so the whole URL\n * is budgeted at `MCP_URL_BUDGET_CHARS` (14 KiB) in `runtime-spec.ts`,\n * where the numbers live. The 8 KiB assertion below becomes 10,924\n * base64url characters at most; with every other runtime-token field at\n * its largest (the prompt itself is not in the token — only the derived\n * `explicitAgentSwitchTargets`, at most three agent names) the URL is\n * ≤ ~13.4 KB.\n * - argv: `encodeActorTopicScopeArg` is the assertion alone, ≤ 10,924\n * characters, far below Linux `MAX_ARG_STRLEN` (128 KiB) for one argument\n * and macOS `ARG_MAX` (1 MiB) overall. The encoder re-validates before it\n * encodes, so an in-process caller that bypassed the gateway parser cannot\n * put an unbounded object into argv either.\n *\n * With UUID room ids (39 bytes each serialized) the byte cap admits roughly\n * 208 ids across both lists; the per-list count cap bounds the work done on\n * an assertion before its size is known, and the id length cap keeps a single\n * id from being the whole budget. Raising these means moving the assertion\n * out of the token (server-side per-turn context), not editing the numbers.\n */\nexport const ACTOR_TOPIC_SCOPE_LIMITS = Object.freeze({\n /** Ids per list, counted before de-duplication. */\n maxIdsPerList: 200,\n /** Characters per id, after trimming. */\n maxIdLength: 128,\n /** UTF-8 bytes of the normalized assertion as JSON. */\n maxSerializedBytes: 8 * 1024,\n});\n\nconst SCOPE_KEYS = [\"visibleNodeTopicIds\", \"ownedNodeTopicIds\"] as const;\nconst OPTIONAL_SCOPE_KEYS = [\"issuedAt\"] as const;\n\n/**\n * How long a hub room assertion is believed after it was issued.\n *\n * The assertion rides the per-turn MCP token, which lives for hours\n * (`HOSTED_MCP_TOKEN_TTL_MS`), and nothing on this node re-asks the hub\n * whether a person is still in a room. Without a bound, a person removed from\n * a room would keep reaching it for the whole token lifetime. Past this age\n * the assertion is stale and grants no cross-room reach (fail-closed, see\n * `isActorTopicScopeFresh`): a person removed from a room loses it on their\n * next turn (a fresh assertion), and at the latest this long after the\n * assertion was issued for a turn that is still running.\n *\n * Trade-off (product decision, safe default): a turn that runs longer than\n * this keeps its own room and its own lineage but can no longer list, tell,\n * ask or abort other rooms until the person speaks again.\n * `NEGOTIUM_ACTOR_TOPIC_SCOPE_MAX_AGE_MS` overrides it, clamped to\n * [0, `ACTOR_TOPIC_SCOPE_MAX_AGE_CEILING_MS`]; `0` disables cross-room reach.\n */\nexport const ACTOR_TOPIC_SCOPE_DEFAULT_MAX_AGE_MS = 10 * 60 * 1000;\n/** Never believe an assertion longer than a hosted MCP token lives. */\nexport const ACTOR_TOPIC_SCOPE_MAX_AGE_CEILING_MS = 4 * 60 * 60 * 1000;\n/** A stamp this far ahead of the local clock is not trusted as \"fresh\". */\nconst ACTOR_TOPIC_SCOPE_FUTURE_SKEW_MS = 60 * 1000;\n\nexport function actorTopicScopeMaxAgeMs(env: NodeJS.ProcessEnv = process.env): number {\n const raw = env.NEGOTIUM_ACTOR_TOPIC_SCOPE_MAX_AGE_MS?.trim();\n if (!raw || !/^\\d+$/.test(raw)) return ACTOR_TOPIC_SCOPE_DEFAULT_MAX_AGE_MS;\n return Math.min(Number(raw), ACTOR_TOPIC_SCOPE_MAX_AGE_CEILING_MS);\n}\n\n/**\n * Whether `scope` may still grant cross-room reach at `now`. An assertion\n * without `issuedAt` (a row or token written before the stamp existed) is\n * never fresh — the safe reading of \"we do not know how old this is\".\n */\nexport function isActorTopicScopeFresh(\n scope: ActorTopicScope,\n now: number = Date.now(),\n maxAgeMs: number = actorTopicScopeMaxAgeMs(),\n): boolean {\n const issuedAt = scope.issuedAt;\n if (issuedAt === undefined) return false;\n if (issuedAt > now + ACTOR_TOPIC_SCOPE_FUTURE_SKEW_MS) return false;\n return now - issuedAt <= maxAgeMs;\n}\n\n/**\n * Stamp an assertion as it enters this node. The node's receipt time is the\n * upper bound (a hub `issuedAt` in the future, e.g. clock skew, cannot extend\n * it); an older hub `issuedAt` is kept, so time the hub spent before sending\n * counts against the window.\n */\nexport function stampActorTopicScope(\n scope: ActorTopicScope,\n now: number = Date.now(),\n): ActorTopicScope {\n const issuedAt = scope.issuedAt === undefined ? now : Math.min(scope.issuedAt, now);\n return { ...scope, issuedAt };\n}\n\nexport type ActorTopicScopeValidation =\n | { ok: true; scope: ActorTopicScope | undefined }\n | { ok: false; error: string };\n\nfunction idList(value: unknown, name: string): string[] | string {\n if (!Array.isArray(value)) return `${name} must be an array of topic ids`;\n if (value.length > ACTOR_TOPIC_SCOPE_LIMITS.maxIdsPerList) {\n return `${name} has ${value.length} ids; at most ${ACTOR_TOPIC_SCOPE_LIMITS.maxIdsPerList} are allowed`;\n }\n const ids = new Set<string>();\n for (const item of value) {\n if (typeof item !== \"string\") return `${name} must contain only strings`;\n const id = item.trim();\n if (!id) return `${name} must not contain empty ids`;\n if (id.length > ACTOR_TOPIC_SCOPE_LIMITS.maxIdLength) {\n return `${name} contains an id longer than ${ACTOR_TOPIC_SCOPE_LIMITS.maxIdLength} characters`;\n }\n ids.add(id);\n }\n return [...ids];\n}\n\n/**\n * Validate a hub-supplied room assertion and say why it failed.\n *\n * `undefined` in means `undefined` out (no assertion, fail-closed downstream);\n * anything else must be exactly `{ visibleNodeTopicIds, ownedNodeTopicIds }`\n * plus an optional `issuedAt` (epoch ms) — a plain object with those own keys\n * and nothing else (so a stray\n * `__proto__` or `constructor` key is a rejection, not a property), each a\n * list of non-empty strings within {@link ACTOR_TOPIC_SCOPE_LIMITS} — or it is\n * rejected, so a malformed assertion can never be read as \"everything\".\n */\nexport function validateActorTopicScope(value: unknown): ActorTopicScopeValidation {\n if (value === undefined) return { ok: true, scope: undefined };\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return {\n ok: false,\n error:\n \"actorTopicScope must be { visibleNodeTopicIds: string[], ownedNodeTopicIds: string[] }\",\n };\n }\n const proto = Object.getPrototypeOf(value);\n if (proto !== Object.prototype && proto !== null) {\n return { ok: false, error: \"actorTopicScope must be a plain object\" };\n }\n const keys = Object.keys(value);\n const allowed: readonly string[] = [...SCOPE_KEYS, ...OPTIONAL_SCOPE_KEYS];\n const unknown = keys.filter((key) => !allowed.includes(key));\n const required = SCOPE_KEYS.filter((key) => keys.includes(key)).length;\n if (unknown.length || required !== SCOPE_KEYS.length) {\n return {\n ok: false,\n error: unknown.length\n ? `actorTopicScope has unexpected key(s): ${unknown.join(\", \")}`\n : \"actorTopicScope must have both visibleNodeTopicIds and ownedNodeTopicIds\",\n };\n }\n const record = value as Record<string, unknown>;\n const visible = idList(record.visibleNodeTopicIds, \"actorTopicScope.visibleNodeTopicIds\");\n if (typeof visible === \"string\") return { ok: false, error: visible };\n const owned = idList(record.ownedNodeTopicIds, \"actorTopicScope.ownedNodeTopicIds\");\n if (typeof owned === \"string\") return { ok: false, error: owned };\n const issuedAt = record.issuedAt;\n if (issuedAt !== undefined && (!Number.isSafeInteger(issuedAt) || (issuedAt as number) < 0)) {\n return { ok: false, error: \"actorTopicScope.issuedAt must be epoch milliseconds\" };\n }\n const scope: ActorTopicScope = {\n visibleNodeTopicIds: visible,\n ownedNodeTopicIds: owned,\n ...(issuedAt !== undefined ? { issuedAt: issuedAt as number } : {}),\n };\n const bytes = Buffer.byteLength(JSON.stringify(scope), \"utf-8\");\n if (bytes > ACTOR_TOPIC_SCOPE_LIMITS.maxSerializedBytes) {\n return {\n ok: false,\n error: `actorTopicScope is ${bytes} bytes serialized; at most ${ACTOR_TOPIC_SCOPE_LIMITS.maxSerializedBytes} are allowed`,\n };\n }\n return { ok: true, scope };\n}\n\n/**\n * Validate a hub-supplied room assertion.\n *\n * `undefined` in means `undefined` out (no assertion, fail-closed downstream);\n * anything else must pass {@link validateActorTopicScope} or it is rejected\n * with `null`. Every path an assertion can enter by — the gateway body, the\n * signed MCP tokens, the stdio argv — goes through this one parser, so the\n * limits cannot drift between them.\n */\nexport function parseActorTopicScope(value: unknown): ActorTopicScope | undefined | null {\n const validated = validateActorTopicScope(value);\n return validated.ok ? validated.scope : null;\n}\n\nexport function isActorTopicScope(value: unknown): value is ActorTopicScope {\n return parseActorTopicScope(value) != null;\n}\n\n/**\n * Read a validated assertion out of a persisted or signed context. Anything\n * that does not validate collapses to \"no assertion\" rather than throwing, so\n * a stale row cannot break a turn — it only narrows it to what a turn without\n * an assertion reaches: the current room plus its own subagent lineage.\n */\nexport function actorTopicScopeFrom(value: unknown): ActorTopicScope | undefined {\n return parseActorTopicScope(value) ?? undefined;\n}\n\n/**\n * The strictest assertion two requests agree on: an id is kept only when both\n * assert it, and a request without an assertion leaves the result without one\n * (fail-closed). Used when several pending requests of one actor fold into a\n * single turn, so the merged turn never reaches a room one of them could not.\n */\nexport function intersectActorTopicScopes(\n scopes: ReadonlyArray<ActorTopicScope | undefined>,\n): ActorTopicScope | undefined {\n if (scopes.length === 0 || scopes.some((scope) => scope === undefined)) return undefined;\n const all = scopes as ActorTopicScope[];\n const [first, ...rest] = all;\n const keep = (key: \"visibleNodeTopicIds\" | \"ownedNodeTopicIds\") =>\n first[key].filter((id) => rest.every((scope) => scope[key].includes(id)));\n // The oldest stamp wins; one unstamped request leaves the batch unstamped\n // (stale), never fresher than any folded assertion.\n const stamps = all.map((scope) => scope.issuedAt);\n const issuedAt = stamps.every((stamp) => stamp !== undefined)\n ? Math.min(...(stamps as number[]))\n : undefined;\n return {\n visibleNodeTopicIds: keep(\"visibleNodeTopicIds\"),\n ownedNodeTopicIds: keep(\"ownedNodeTopicIds\"),\n ...(issuedAt !== undefined ? { issuedAt } : {}),\n };\n}\n\n/**\n * Argv-safe encoding for the stdio session-comm server (`--actor-topic-scope=`).\n * Bounded by {@link ACTOR_TOPIC_SCOPE_LIMITS}: 8,192 bytes of JSON become at\n * most 10,924 base64url characters, see there. The input is put through\n * {@link validateActorTopicScope} first and an invalid or oversized assertion\n * throws — it is never truncated (which would narrow the turn silently) nor\n * passed on (which would let a typed in-process caller overflow argv).\n */\nexport function encodeActorTopicScopeArg(scope: ActorTopicScope): string {\n const validated = validateActorTopicScope(scope);\n if (!validated.ok) throw new Error(validated.error);\n if (!validated.scope) throw new Error(\"actorTopicScope is required\");\n return Buffer.from(JSON.stringify(validated.scope), \"utf-8\").toString(\"base64url\");\n}\n",
|
|
19
19
|
"import type { RemoteSessionGrant } from \"#types\";\n\n/**\n * Hard caps on a hub-supplied remote-session grant.\n *\n * Like the actor room assertion (`actor-topic-scope.ts`), the grant rides the\n * signed per-turn `session-comm` MCP token in a URL query and — with\n * `NEGOTIUM_BUILTIN_MCP_TRANSPORT=stdio` — one base64url argv entry, so the\n * transport bounds it, not the database. A capability is ≈330–440 characters\n * (`rsc1.<base64url JSON>.<base64url HMAC>`) and adds ≈680 URL characters\n * beside the maximal 8 KiB assertion (12,800 of the 14,336 budget, measured\n * in `hosted-runtime-spec.test.ts`). The caps below leave a hub room to grow\n * the payload, but a grant at both caps (≈3,475 URL characters) does not fit\n * beside the *maximal* assertion — `MCP_URL_BUDGET_CHARS` is the backstop and\n * refuses that mint loudly rather than dropping a field. A capability up to\n * ≈1,590 characters always fits.\n */\nexport const REMOTE_SESSION_GRANT_LIMITS = Object.freeze({\n /** Characters of `hubUrl`, after trimming. */\n maxHubUrlLength: 512,\n /** Characters of `capability`, after trimming. */\n maxCapabilityLength: 2 * 1024,\n /** The only capability format this node forwards. */\n capabilityPrefix: \"rsc1.\",\n});\n\nconst GRANT_KEYS = [\"hubUrl\", \"capability\"] as const;\nconst LOOPBACK_HOSTS = new Set([\"127.0.0.1\", \"::1\", \"[::1]\", \"localhost\"]);\n\nexport type RemoteSessionGrantValidation =\n | { ok: true; grant: RemoteSessionGrant | undefined }\n | { ok: false; error: string };\n\n/**\n * Normalize a hub URL the node may present a bearer to: loopback `http://`\n * or any `https://` origin, ≤ 512 characters, no credentials, no query or\n * fragment. Returns the canonical string (trailing slash dropped) or the\n * reason it is refused. The one rule for every hub URL the node stores — the\n * turn grant's `hubUrl` and an ask's `remoteReply.hubUrl` alike — so a\n * bearer can never be steered to an attacker-chosen host.\n */\nexport function normalizeHubUrl(\n raw: string,\n name = \"remoteSession.hubUrl\",\n): { url: string } | { error: string } {\n if (raw.length > REMOTE_SESSION_GRANT_LIMITS.maxHubUrlLength) {\n return {\n error: `${name} is longer than ${REMOTE_SESSION_GRANT_LIMITS.maxHubUrlLength} characters`,\n };\n }\n let url: URL;\n try {\n url = new URL(raw);\n } catch {\n return { error: `${name} must be an absolute URL` };\n }\n if (url.username || url.password) {\n return { error: `${name} must not carry credentials` };\n }\n if (url.search || url.hash || raw.includes(\"?\") || raw.includes(\"#\")) {\n return { error: `${name} must not carry a query or fragment` };\n }\n if (url.protocol === \"http:\") {\n if (!LOOPBACK_HOSTS.has(url.hostname)) {\n return { error: `${name} must be https:// or a loopback http:// origin` };\n }\n } else if (url.protocol !== \"https:\") {\n return { error: `${name} must be https:// or a loopback http:// origin` };\n }\n return { url: url.toString().replace(/\\/+$/, \"\") };\n}\n\n/** Shape of the hub's one-shot `rsr1` reply token; the node never verifies it. */\nexport const REMOTE_SESSION_REPLY_TOKEN_PATTERN = /^rsr1\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+$/;\n/** Same cap as the capability: the hub's tokens are ≈200 characters. */\nexport const MAX_REMOTE_SESSION_REPLY_TOKEN_LENGTH =\n REMOTE_SESSION_GRANT_LIMITS.maxCapabilityLength;\n\n/**\n * Validate a hub-supplied remote-session grant and say why it failed.\n *\n * `undefined` in means `undefined` out (no grant: remote session-comm stays\n * fail-closed on `otium`); anything else must be exactly\n * `{ hubUrl, capability }` — a plain object with those two own keys — with a\n * callable hub URL and an opaque `rsc1.` capability within\n * {@link REMOTE_SESSION_GRANT_LIMITS}. The node never decodes or verifies the\n * capability: it is a bearer the hub issued and only the hub can check.\n */\nexport function validateRemoteSessionGrant(value: unknown): RemoteSessionGrantValidation {\n if (value === undefined) return { ok: true, grant: undefined };\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return { ok: false, error: \"remoteSession must be { hubUrl: string, capability: string }\" };\n }\n const proto = Object.getPrototypeOf(value);\n if (proto !== Object.prototype && proto !== null) {\n return { ok: false, error: \"remoteSession must be a plain object\" };\n }\n const keys = Object.keys(value);\n const unknown = keys.filter((key) => !(GRANT_KEYS as readonly string[]).includes(key));\n if (unknown.length || keys.length !== GRANT_KEYS.length) {\n return {\n ok: false,\n error: unknown.length\n ? `remoteSession has unexpected key(s): ${unknown.join(\", \")}`\n : \"remoteSession must have both hubUrl and capability\",\n };\n }\n const record = value as Record<string, unknown>;\n if (typeof record.hubUrl !== \"string\" || !record.hubUrl.trim()) {\n return { ok: false, error: \"remoteSession.hubUrl must be a non-empty string\" };\n }\n const hubUrl = normalizeHubUrl(record.hubUrl.trim());\n if (\"error\" in hubUrl) return { ok: false, error: hubUrl.error };\n if (typeof record.capability !== \"string\" || !record.capability.trim()) {\n return { ok: false, error: \"remoteSession.capability must be a non-empty string\" };\n }\n const capability = record.capability.trim();\n if (capability.length > REMOTE_SESSION_GRANT_LIMITS.maxCapabilityLength) {\n return {\n ok: false,\n error: `remoteSession.capability is ${capability.length} characters; at most ${REMOTE_SESSION_GRANT_LIMITS.maxCapabilityLength} are allowed`,\n };\n }\n if (!capability.startsWith(REMOTE_SESSION_GRANT_LIMITS.capabilityPrefix)) {\n return {\n ok: false,\n error: `remoteSession.capability must start with \"${REMOTE_SESSION_GRANT_LIMITS.capabilityPrefix}\"`,\n };\n }\n // Three dot-separated base64url parts and nothing else, so a value that\n // is not even shaped like a capability never reaches the hub.\n if (!/^rsc1\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+$/.test(capability)) {\n return { ok: false, error: \"remoteSession.capability is malformed\" };\n }\n return { ok: true, grant: { hubUrl: hubUrl.url, capability } };\n}\n\n/** {@link validateRemoteSessionGrant} collapsed to `null` on failure. */\nexport function parseRemoteSessionGrant(value: unknown): RemoteSessionGrant | undefined | null {\n const validated = validateRemoteSessionGrant(value);\n return validated.ok ? validated.grant : null;\n}\n\nexport function isRemoteSessionGrant(value: unknown): value is RemoteSessionGrant {\n return parseRemoteSessionGrant(value) != null;\n}\n\n/**\n * Read a validated grant out of a persisted or signed context. Anything that\n * does not validate collapses to \"no grant\" rather than throwing: a stale row\n * only loses remote reach, it never breaks the turn.\n */\nexport function remoteSessionGrantFrom(value: unknown): RemoteSessionGrant | undefined {\n return parseRemoteSessionGrant(value) ?? undefined;\n}\n\n/**\n * Best-effort peek at the capability's expiry (`e`, epoch seconds), used only\n * to order grants when several requests fold into one turn. Untrusted: the\n * node never decides validity from it — the hub does.\n */\nexport function remoteSessionGrantExpiry(grant: RemoteSessionGrant): number | null {\n const payload = grant.capability.split(\".\")[1];\n if (!payload) return null;\n try {\n const decoded = JSON.parse(Buffer.from(payload, \"base64url\").toString(\"utf-8\")) as unknown;\n const exp = (decoded as { e?: unknown } | null)?.e;\n return typeof exp === \"number\" && Number.isFinite(exp) ? exp : null;\n } catch {\n return null;\n }\n}\n\n/**\n * The grant a merged turn runs with: symmetric to `intersectActorTopicScopes`\n * — a request without a grant leaves the batch without one (fail-closed), and\n * a batch of grants for one hub keeps the one that expires last so the merged\n * turn is not cut short by the oldest message's capability. Grants naming\n * different hubs never merge (the batch runs with none). The caller has\n * already ensured the folded requests speak for the same actor.\n */\nexport function mergeRemoteSessionGrants(\n grants: ReadonlyArray<RemoteSessionGrant | undefined>,\n): RemoteSessionGrant | undefined {\n if (grants.length === 0 || grants.some((grant) => grant === undefined)) return undefined;\n const present = grants as RemoteSessionGrant[];\n const hubUrl = present[0]!.hubUrl;\n if (present.some((grant) => grant.hubUrl !== hubUrl)) return undefined;\n let chosen = present[present.length - 1]!;\n let chosenExpiry = remoteSessionGrantExpiry(chosen);\n for (const grant of present) {\n const expiry = remoteSessionGrantExpiry(grant);\n if (expiry !== null && (chosenExpiry === null || expiry > chosenExpiry)) {\n chosen = grant;\n chosenExpiry = expiry;\n }\n }\n return chosen;\n}\n\n/**\n * Argv-safe encoding for the stdio session-comm server\n * (`--remote-session-grant=`). Re-validated before encoding, so an in-process\n * caller cannot put an unbounded or malformed grant into argv.\n */\nexport function encodeRemoteSessionGrantArg(grant: RemoteSessionGrant): string {\n const validated = validateRemoteSessionGrant(grant);\n if (!validated.ok) throw new Error(validated.error);\n if (!validated.grant) throw new Error(\"remoteSession is required\");\n return Buffer.from(JSON.stringify(validated.grant), \"utf-8\").toString(\"base64url\");\n}\n\n/** Inverse of {@link encodeRemoteSessionGrantArg}; `null` when malformed. */\nexport function decodeRemoteSessionGrantArg(value: string): RemoteSessionGrant | null {\n try {\n const decoded = JSON.parse(Buffer.from(value, \"base64url\").toString(\"utf-8\")) as unknown;\n return parseRemoteSessionGrant(decoded) ?? null;\n } catch {\n return null;\n }\n}\n",
|
|
20
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
21
|
"import { type ChildProcess, execFileSync, spawn } from \"node:child_process\";\nimport { randomBytes } from \"node:crypto\";\nimport {\n BASH_RS_BIN,\n BASH_RS_VERSION,\n BASHRS_SPILL_ROOT,\n BG_BASH_BASE_PORT,\n BG_BASH_MAX_PORT,\n} 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 /**\n * bash-rs executable. Defaults to the installed binary; injectable so a test\n * can drive the manager's bookkeeping with a fake `spawn` on a host that has\n * no binary at all.\n */\n bashRsBin?: 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 bashRsBin = options.bashRsBin ?? BASH_RS_BIN;\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 if (!response.ok) return false;\n // Confirm this port answers for *our* spawned process rather than a\n // stale one left behind by a previous manager instance.\n const body = await response.text();\n try {\n const parsed = JSON.parse(body);\n return (\n Boolean(parsed) && typeof parsed === \"object\" && parsed.instance_id === runtimeServerId\n );\n } catch {\n return false;\n }\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 // bash-rs is the only implementation. A TS server used to stand in when the\n // binary was absent, but the two agreed on the HTTP protocol while exposing\n // different MCP tool names (bash_run vs background_bash_run), so which one\n // spawned silently changed the tool surface an agent saw. Failing loudly\n // beats serving a different API than the caller was told to expect.\n //\n // Checked before allocating: the caller retries once per turn, and a port\n // reserved by a throw is never released, so allocating first leaked one\n // port per attempt until the range was exhausted and the real cause was\n // buried under \"No available ports\".\n if (!bashRsBin) {\n throw new Error(\n `background-bash requires the bash-rs ${BASH_RS_VERSION} binary; run install-bash-rs.mjs (or set NEGOTIUM_BASH_RS_BIN)`,\n );\n }\n const port = reservedPort ?? (await allocatePort(excludedPorts));\n const process = spawnImpl(bashRsBin, [String(port)], {\n stdio: \"ignore\",\n detached: false,\n // Long-lived background server — no console window on Windows. Ignored\n // on POSIX.\n windowsHide: true,\n env: {\n ...(options.env ?? globalThis.process.env),\n NEGOTIUM_BG_BASH_CAPABILITY: runtimeCapability,\n NEGOTIUM_BG_BASH_SERVER_ID: runtimeServerId,\n BASHRS_HTTP_CAPABILITY: runtimeCapability,\n BASHRS_INSTANCE_ID: runtimeServerId,\n BASHRS_SPILL_ROOT,\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
22
|
"export const delay = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));\n",
|
|
23
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 decision: { 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 // macOS desktop control via maestrojeong/cua-rs. Deliberately NOT\n // forumRequired: it advertises 12 tools, a meaningful slice of a turn's\n // tool budget, and most topics never touch a native app. Opt in per topic\n // through the enabled whitelist.\n \"cua-rs\": { scopes: [\"dm\", \"forum\", \"fork\"], forumRequired: false },\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",
|
|
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 decision: { 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 // macOS desktop control via maestrojeong/cua-rs. Deliberately NOT\n // forumRequired: it advertises 12 tools, a meaningful slice of a turn's\n // tool budget, and most topics never touch a native app. Opt in per topic\n // through the enabled whitelist.\n \"cua-rs\": { scopes: [\"dm\", \"forum\", \"fork\"], forumRequired: false },\n // Reads the append-only raw conversation manifest (survives /compact and\n // agent switches). Deliberately NOT forumRequired: most turns never need\n // to look past the active context, and it is a 3-tool surface most topics\n // will not touch. Opt in per topic through the enabled whitelist.\n \"session-history\": { scopes: [\"dm\", \"forum\", \"manager\"], forumRequired: false },\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
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
26
|
"import type { AgentKind } from \"#types\";\n\nimport { browserOwnerCapability } from \"./capability\";\n\nexport const CODEX_BROWSER_CAPABILITY_ENV = \"NEGOTIUM_BROWSER_CAPABILITY\";\n\n/** Build the authenticated Browser.rs transport for one agent turn. */\nexport function buildPlaywrightMcpTransport(\n port: number,\n owner: string,\n capability: string,\n agent?: AgentKind,\n): Record<string, unknown> {\n const query = new URLSearchParams({ owner });\n const ownerCapability = browserOwnerCapability(capability, owner);\n\n if (agent === \"codex\") {\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 if (agent === \"maestro\") {\n return {\n type: \"http\" as const,\n url: `http://127.0.0.1:${port}/mcp?${query}`,\n headers: { \"X-Browser-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",
|
|
27
27
|
"import { logger } from \"#platform/logger\";\nimport type { AgentKind } from \"#types\";\n\nexport interface CronSessionRef {\n sessionId: string;\n ownerUserId: string;\n}\n\nexport type CronSessionProvider = (topicId: string, agent: AgentKind) => CronSessionRef | null;\n\nconst providers: Array<{ provider: CronSessionProvider }> = [];\n\nexport function getRegisteredCronSession(topicId: string, agent: AgentKind): CronSessionRef | null {\n const registration = providers.at(-1);\n if (!registration) return null;\n try {\n return registration.provider(topicId, agent);\n } catch (error) {\n logger.warn({ err: error, topicId, agent }, \"cron-session: provider lookup failed\");\n return null;\n }\n}\n\n/** Register the optional Cron module's session lookup without coupling core to the module. */\nexport function registerCronSessionProvider(next: CronSessionProvider): () => void {\n const registration = { provider: next };\n providers.push(registration);\n let disposed = false;\n return () => {\n if (disposed) return;\n disposed = true;\n const index = providers.indexOf(registration);\n if (index >= 0) providers.splice(index, 1);\n };\n}\n",
|
|
@@ -33,7 +33,7 @@
|
|
|
33
33
|
"// Persistent message store for the REST/WS API channel (Otium).\n//\n// Replaces the previous in-memory `Map<topicId, MessageDto[]>` so messages\n// survive server restarts. Backed by the shared sessions SQLite DB — the same\n// database the Telegram channel uses — which is the foundation for unifying\n// conversation state across channels later.\n//\n// Ordering is by the implicit SQLite `rowid` (monotonic insert order). Cursor\n// pagination resolves the cursor id → its rowid and returns rows after it.\n\nimport { db } from \"#storage/forum-db\";\nimport { registerStorageSchemaInitializer } from \"#storage/storage-host\";\nimport type { AgentKind } from \"#types\";\nimport type { MessageDto } from \"#types/api\";\n\nfunction initializeApiMessagesSchema(): void {\n db.exec(`\n CREATE TABLE IF NOT EXISTS api_messages (\n id TEXT PRIMARY KEY,\n topic_id TEXT NOT NULL,\n parent_id TEXT,\n author_id TEXT NOT NULL,\n source_adapter TEXT,\n source_node TEXT,\n source_message_id TEXT,\n text TEXT NOT NULL,\n query_id TEXT,\n agent_type TEXT,\n model TEXT,\n attachments TEXT,\n usage TEXT,\n deleted INTEGER NOT NULL DEFAULT 0,\n edited_at TEXT,\n reactions TEXT,\n kind TEXT,\n ask_user_question TEXT,\n tell_card TEXT,\n mentions TEXT,\n thread_root_id TEXT,\n created_at TEXT NOT NULL\n )\n`);\n try {\n db.exec(\"ALTER TABLE api_messages ADD COLUMN source_adapter TEXT\");\n } catch {\n // Column already exists.\n }\n try {\n db.exec(\"ALTER TABLE api_messages ADD COLUMN source_node TEXT\");\n } catch {}\n try {\n db.exec(\"ALTER TABLE api_messages ADD COLUMN source_message_id TEXT\");\n } catch {}\n try {\n db.exec(\"ALTER TABLE api_messages ADD COLUMN deleted INTEGER NOT NULL DEFAULT 0\");\n } catch {}\n try {\n db.exec(\"ALTER TABLE api_messages ADD COLUMN edited_at TEXT\");\n } catch {}\n try {\n db.exec(\"ALTER TABLE api_messages ADD COLUMN reactions TEXT\");\n } catch {}\n try {\n db.exec(\"ALTER TABLE api_messages ADD COLUMN kind TEXT\");\n } catch {}\n try {\n db.exec(\"ALTER TABLE api_messages ADD COLUMN ask_user_question TEXT\");\n } catch {}\n try {\n db.exec(\"ALTER TABLE api_messages ADD COLUMN tell_card TEXT\");\n } catch {}\n try {\n db.exec(\"ALTER TABLE api_messages ADD COLUMN mentions TEXT\");\n } catch {}\n try {\n // Slack-style threads: a reply carries the ROOT message id (flat, no nesting).\n // Distinct from parent_id (which is a Telegram-style inline quote-reply).\n db.exec(\"ALTER TABLE api_messages ADD COLUMN thread_root_id TEXT\");\n } catch {}\n try {\n db.exec(\"ALTER TABLE api_messages ADD COLUMN subagent_card TEXT\");\n } catch {}\n try {\n db.exec(\"ALTER TABLE api_messages ADD COLUMN vault_secret_request TEXT\");\n } catch {}\n // Index on topic_id; SQLite appends the implicit rowid to every index entry,\n // so `WHERE topic_id=? AND rowid>? ORDER BY rowid` stays index-driven.\n db.exec(\"CREATE INDEX IF NOT EXISTS idx_api_messages_topic ON api_messages(topic_id)\");\n db.exec(\n \"CREATE INDEX IF NOT EXISTS idx_api_messages_thread_root ON api_messages(thread_root_id)\",\n );\n}\n\nregisterStorageSchemaInitializer(initializeApiMessagesSchema, 30);\n\nexport interface ApiMessageRow {\n id: string;\n topic_id: string;\n parent_id: string | null;\n author_id: string;\n source_adapter: string | null;\n source_node: string | null;\n source_message_id: string | null;\n text: string;\n query_id: string | null;\n agent_type: string | null;\n model: string | null;\n attachments: string | null;\n usage: string | null;\n deleted: number;\n edited_at: string | null;\n reactions: string | null;\n kind: string | null;\n ask_user_question: string | null;\n tell_card: string | null;\n subagent_card: string | null;\n vault_secret_request: string | null;\n mentions: string | null;\n thread_root_id: string | null;\n created_at: string;\n rowid?: number;\n}\n\nexport type ApiMessageAppendHook = (msg: MessageDto) => void | Promise<void>;\nconst appendHooks = new Set<ApiMessageAppendHook>();\n\nexport interface AppendApiMessageOptions {\n notify?: boolean;\n updateTopicLastMessageAt?: boolean;\n}\n\nexport function registerApiMessageAppendHook(hook: ApiMessageAppendHook): () => void {\n appendHooks.add(hook);\n return () => {\n appendHooks.delete(hook);\n };\n}\n\nfunction emitApiMessageAppended(msg: MessageDto): void {\n for (const hook of appendHooks) {\n queueMicrotask(() => {\n try {\n void Promise.resolve(hook(msg)).catch(() => undefined);\n } catch {\n // Hooks are post-persist side effects; never make message writes fail.\n }\n });\n }\n}\n\nfunction rowToDto(r: ApiMessageRow): MessageDto {\n return {\n id: r.id,\n topicId: r.topic_id,\n parentId: r.parent_id ?? undefined,\n authorId: r.author_id,\n sourceAdapter: r.source_adapter ?? undefined,\n sourceNode: r.source_node ?? undefined,\n sourceMessageId: r.source_message_id ?? undefined,\n text: r.text,\n queryId: r.query_id ?? undefined,\n agentType: (r.agent_type as AgentKind | null) ?? undefined,\n model: r.model ?? undefined,\n attachments: r.attachments ? JSON.parse(r.attachments) : undefined,\n usage: r.usage ? JSON.parse(r.usage) : undefined,\n deleted: r.deleted !== 0,\n editedAt: r.edited_at ?? undefined,\n reactions: r.reactions ? JSON.parse(r.reactions) : undefined,\n kind: (r.kind as MessageDto[\"kind\"] | null) ?? undefined,\n askUserQuestion: r.ask_user_question ? JSON.parse(r.ask_user_question) : undefined,\n tellCard: r.tell_card ? JSON.parse(r.tell_card) : undefined,\n subagentCard: r.subagent_card ? JSON.parse(r.subagent_card) : undefined,\n vaultSecretRequest: r.vault_secret_request ? JSON.parse(r.vault_secret_request) : undefined,\n mentions: r.mentions ? JSON.parse(r.mentions) : undefined,\n threadRootId: r.thread_root_id ?? undefined,\n createdAt: r.created_at,\n };\n}\n\nfunction attachmentListHasFileId(raw: string | null, fileId: string): boolean {\n if (!raw) return false;\n try {\n const attachments = JSON.parse(raw) as unknown;\n return (\n Array.isArray(attachments) &&\n attachments.some(\n (attachment) =>\n typeof attachment === \"object\" &&\n attachment !== null &&\n \"id\" in attachment &&\n attachment.id === fileId,\n )\n );\n } catch {\n return false;\n }\n}\n\n/** Persist a single message. Idempotent on id: duplicate appends do not rewrite edited/reaction state. */\nexport function appendApiMessage(msg: MessageDto, options: AppendApiMessageOptions = {}): void {\n const notify = options.notify ?? true;\n const updateTopicLastMessageAt = options.updateTopicLastMessageAt ?? true;\n let inserted = false;\n db.transaction(() => {\n const result = db\n .query(\n `INSERT INTO api_messages\n (id, topic_id, parent_id, author_id, source_adapter, source_node, source_message_id, text, query_id, agent_type, model, attachments, usage, deleted, edited_at, reactions, kind, ask_user_question, tell_card, subagent_card, vault_secret_request, mentions, thread_root_id, created_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(id) DO NOTHING`,\n )\n .run(\n msg.id,\n msg.topicId,\n msg.parentId ?? null,\n msg.authorId,\n msg.sourceAdapter ?? null,\n msg.sourceNode ?? null,\n msg.sourceMessageId ?? null,\n msg.text,\n msg.queryId ?? null,\n msg.agentType ?? null,\n msg.model ?? null,\n msg.attachments ? JSON.stringify(msg.attachments) : null,\n msg.usage ? JSON.stringify(msg.usage) : null,\n msg.deleted ? 1 : 0,\n msg.editedAt ?? null,\n msg.reactions?.length ? JSON.stringify(msg.reactions) : null,\n msg.kind ?? null,\n msg.askUserQuestion ? JSON.stringify(msg.askUserQuestion) : null,\n msg.tellCard ? JSON.stringify(msg.tellCard) : null,\n msg.subagentCard ? JSON.stringify(msg.subagentCard) : null,\n msg.vaultSecretRequest ? JSON.stringify(msg.vaultSecretRequest) : null,\n msg.mentions?.length ? JSON.stringify(msg.mentions) : null,\n msg.threadRootId ?? null,\n msg.createdAt,\n );\n inserted = Number(result.changes ?? 0) > 0;\n if (inserted && updateTopicLastMessageAt && !msg.deleted) {\n db.query(\n `UPDATE api_topics\n SET last_message_at = CASE\n WHEN last_message_at IS NULL OR last_message_at < ? THEN ?\n ELSE last_message_at\n END\n WHERE id = ?`,\n ).run(msg.createdAt, msg.createdAt, msg.topicId);\n }\n })();\n if (inserted && notify && !msg.deleted) emitApiMessageAppended(msg);\n}\n\nexport function getApiMessage(topicId: string, messageId: string): MessageDto | null {\n const row = db\n .query(\"SELECT * FROM api_messages WHERE topic_id = ? AND id = ?\")\n .get(topicId, messageId) as ApiMessageRow | undefined;\n return row ? rowToDto(row) : null;\n}\n\nexport function topicHasAttachmentFileId(topicId: string, fileId: string): boolean {\n const rows = db\n .query<{ attachments: string | null }, [string]>(\n \"SELECT attachments FROM api_messages WHERE topic_id = ? AND deleted = 0 AND attachments IS NOT NULL\",\n )\n .all(topicId);\n return rows.some((row) => attachmentListHasFileId(row.attachments, fileId));\n}\n\nexport function updateApiMessageText(\n topicId: string,\n messageId: string,\n text: string,\n editedAt = new Date().toISOString(),\n): MessageDto | null {\n const res = db\n .query(\n `UPDATE api_messages\n SET text = ?, edited_at = ?\n WHERE topic_id = ? AND id = ? AND deleted = 0`,\n )\n .run(text, editedAt, topicId, messageId);\n if (Number(res.changes ?? 0) === 0) return null;\n return getApiMessage(topicId, messageId);\n}\n\n/** Attach terminal turn usage to an already-persisted assistant segment. */\nexport function updateApiMessageUsage(\n topicId: string,\n messageId: string,\n usage: NonNullable<MessageDto[\"usage\"]>,\n): MessageDto | null {\n const res = db\n .query(\n `UPDATE api_messages\n SET usage = ?\n WHERE topic_id = ? AND id = ? AND deleted = 0`,\n )\n .run(JSON.stringify(usage), topicId, messageId);\n if (Number(res.changes ?? 0) === 0) return null;\n return getApiMessage(topicId, messageId);\n}\n\nexport function updateApiMessageAskUserQuestion(\n topicId: string,\n messageId: string,\n askUserQuestion: NonNullable<MessageDto[\"askUserQuestion\"]>,\n editedAt = new Date().toISOString(),\n): MessageDto | null {\n const res = db\n .query(\n `UPDATE api_messages\n SET ask_user_question = ?, edited_at = ?\n WHERE topic_id = ? AND id = ? AND deleted = 0 AND kind = 'ask_user_question'`,\n )\n .run(JSON.stringify(askUserQuestion), editedAt, topicId, messageId);\n if (Number(res.changes ?? 0) === 0) return null;\n return getApiMessage(topicId, messageId);\n}\n\nexport function updateApiMessageSubagentCard(\n topicId: string,\n messageId: string,\n subagentCard: NonNullable<MessageDto[\"subagentCard\"]>,\n editedAt = new Date().toISOString(),\n): MessageDto | null {\n const res = db\n .query(\n `UPDATE api_messages\n SET subagent_card = ?, edited_at = ?\n WHERE topic_id = ? AND id = ? AND deleted = 0 AND kind = 'subagent'`,\n )\n .run(JSON.stringify(subagentCard), editedAt, topicId, messageId);\n if (Number(res.changes ?? 0) === 0) return null;\n return getApiMessage(topicId, messageId);\n}\n\n/** All non-deleted messages of one kind, across topics (boot-time sweeps). */\nexport function listApiMessagesByKind(kind: NonNullable<MessageDto[\"kind\"]>): MessageDto[] {\n const rows = db\n .query(\"SELECT * FROM api_messages WHERE kind = ? AND deleted = 0\")\n .all(kind) as ApiMessageRow[];\n return rows.map(rowToDto);\n}\n\n/** Replace a message's full reactions array. Toggle logic lives in the route. */\nexport function setApiMessageReactions(\n topicId: string,\n messageId: string,\n reactions: NonNullable<MessageDto[\"reactions\"]>,\n): MessageDto | null {\n const res = db\n .query(\n `UPDATE api_messages\n SET reactions = ?\n WHERE topic_id = ? AND id = ? AND deleted = 0`,\n )\n .run(reactions.length ? JSON.stringify(reactions) : null, topicId, messageId);\n if (Number(res.changes ?? 0) === 0) return null;\n return getApiMessage(topicId, messageId);\n}\n\nexport function softDeleteApiMessage(topicId: string, messageId: string): MessageDto | null {\n const res = db\n .query(\n `UPDATE api_messages\n SET deleted = 1, text = ''\n WHERE topic_id = ? AND id = ? AND deleted = 0`,\n )\n .run(topicId, messageId);\n if (Number(res.changes ?? 0) === 0) return null;\n return getApiMessage(topicId, messageId);\n}\n\n/** Soft-delete every live message whose id starts with a caller-owned prefix. */\nexport function softDeleteApiMessagesByIdPrefix(topicId: string, prefix: string): string[] {\n if (!prefix) return [];\n const rows = db\n .query(\n `SELECT id FROM api_messages\n WHERE topic_id = ? AND deleted = 0 AND substr(id, 1, ?) = ?`,\n )\n .all(topicId, prefix.length, prefix) as { id: string }[];\n if (rows.length === 0) return [];\n db.query(\n `UPDATE api_messages\n SET deleted = 1, text = ''\n WHERE topic_id = ? AND deleted = 0 AND substr(id, 1, ?) = ?`,\n ).run(topicId, prefix.length, prefix);\n return rows.map((row) => row.id);\n}\n\nexport interface MessagePage {\n page: MessageDto[];\n cursor?: string;\n hasMore: boolean;\n}\n\nexport interface ListApiMessagesOptions {\n cursor?: string | null;\n limit?: number;\n}\n\n/**\n * List messages for a topic, NEWEST-FIRST by default (bug G).\n *\n * The chat client loads once on mount and renders whatever it gets, so the\n * initial page must be the *latest* N messages, not the oldest. We therefore\n * query newest→oldest (`ORDER BY rowid DESC`) and then reverse the page back to\n * chronological (oldest→newest) order for display.\n *\n * Pagination is BACKWARD (toward older history): pass the returned `cursor`\n * (the oldest id currently loaded) to fetch the page of messages *older* than\n * it. `hasMore` therefore means \"there are older messages above this page\".\n */\nexport function listApiMessages(topicId: string, options?: ListApiMessagesOptions): MessagePage {\n const limit = Math.max(1, Math.min(options?.limit ?? 50, 200));\n\n let anchorRowid: number | null = null;\n if (options?.cursor) {\n const cur = db\n .query(\"SELECT rowid AS rowid FROM api_messages WHERE topic_id = ? AND id = ?\")\n .get(topicId, options.cursor) as { rowid: number } | undefined;\n if (cur) anchorRowid = cur.rowid;\n }\n\n const rows = (\n anchorRowid !== null\n ? db\n .query(\n `SELECT *, rowid AS rowid FROM api_messages\n WHERE topic_id = ? AND deleted = 0 AND thread_root_id IS NULL AND rowid < ?\n ORDER BY rowid DESC\n LIMIT ?`,\n )\n .all(topicId, anchorRowid, limit + 1)\n : db\n .query(\n `SELECT *, rowid AS rowid FROM api_messages\n WHERE topic_id = ? AND deleted = 0 AND thread_root_id IS NULL\n ORDER BY rowid DESC\n LIMIT ?`,\n )\n .all(topicId, limit + 1)\n ) as (ApiMessageRow & { rowid: number })[];\n\n const hasMore = rows.length > limit;\n // rows are newest→oldest; trim the look-ahead row, then flip to chronological.\n const pageRows = (hasMore ? rows.slice(0, limit) : rows).reverse();\n const page = pageRows.map(rowToDto);\n\n // Stamp thread reply counts onto the messages that are thread roots.\n const summaries = getThreadSummaries(page.map((m) => m.id));\n if (summaries.size > 0) {\n for (const m of page) {\n const s = summaries.get(m.id);\n if (s) {\n m.threadReplyCount = s.replyCount;\n m.threadLastReplyAt = s.lastReplyAt;\n }\n }\n }\n\n return {\n page,\n // Oldest loaded id — pass back as `cursor` to load the previous (older) page.\n cursor: page.length > 0 ? page[0].id : undefined,\n hasMore,\n };\n}\n\n/**\n * Reply count + last reply time per thread root, computed on read (no\n * denormalized counters to drift). Only non-deleted replies are counted.\n */\nexport function getThreadSummaries(\n rootIds: readonly string[],\n): Map<string, { replyCount: number; lastReplyAt: string }> {\n const out = new Map<string, { replyCount: number; lastReplyAt: string }>();\n const ids = [...new Set(rootIds)].filter(Boolean);\n if (ids.length === 0) return out;\n const rows = db\n .query(\n `SELECT thread_root_id AS rootId, COUNT(*) AS replyCount, MAX(created_at) AS lastReplyAt\n FROM api_messages\n WHERE thread_root_id IN (${ids.map(() => \"?\").join(\",\")}) AND deleted = 0\n GROUP BY thread_root_id`,\n )\n .all(...ids) as { rootId: string; replyCount: number; lastReplyAt: string }[];\n for (const r of rows) {\n out.set(r.rootId, { replyCount: Number(r.replyCount), lastReplyAt: r.lastReplyAt });\n }\n return out;\n}\n\n/** The root message plus its thread replies (chronological). */\nexport function listThreadMessages(\n topicId: string,\n rootId: string,\n): { root: MessageDto | null; replies: MessageDto[] } {\n const root = getApiMessage(topicId, rootId);\n const rows = db\n .query(\n `SELECT *, rowid AS rowid FROM api_messages\n WHERE topic_id = ? AND thread_root_id = ? AND deleted = 0\n ORDER BY rowid ASC\n LIMIT 200`,\n )\n .all(topicId, rootId) as ApiMessageRow[];\n return { root, replies: rows.map(rowToDto) };\n}\n\n/**\n * The root message and its replies as raw rows, oldest first.\n *\n * Row-shaped rather than DTO-shaped because the caller renders them with\n * `formatChannelTranscriptLine`, so a thread read to the model looks exactly\n * like the channel transcript it may appear next to.\n */\nexport function listThreadMessageRows(\n topicId: string,\n rootId: string,\n limit = 200,\n): { root: ApiMessageRow | null; replies: ApiMessageRow[] } {\n const root =\n (db\n .query(\"SELECT *, rowid AS rowid FROM api_messages WHERE topic_id = ? AND id = ?\")\n .get(topicId, rootId) as ApiMessageRow | null) ?? null;\n // Newest-first with a LIMIT, then reversed: when a thread is longer than the\n // budget the recent end is the part worth keeping.\n const rows = db\n .query(\n `SELECT *, rowid AS rowid FROM api_messages\n WHERE topic_id = ? AND thread_root_id = ? AND deleted = 0\n ORDER BY rowid DESC\n LIMIT ?`,\n )\n .all(topicId, rootId, Math.max(1, limit)) as ApiMessageRow[];\n return { root, replies: rows.reverse() };\n}\n\n/** Total undeleted replies in a thread, for reporting what a read left out. */\nexport function countThreadReplies(topicId: string, rootId: string): number {\n const row = db\n .query(\n `SELECT COUNT(*) AS n FROM api_messages\n WHERE topic_id = ? AND thread_root_id = ? AND deleted = 0`,\n )\n .get(topicId, rootId) as { n: number } | null;\n return Number(row?.n ?? 0);\n}\n\n/**\n * Thread roots in a topic whose id starts with `prefix`, ignoring separators.\n *\n * Resolved in SQL over the whole topic rather than over a page of recent\n * threads: the short tag a model reads in a transcript may belong to a thread\n * that has not been touched in months, and a capped scan reports that thread as\n * nonexistent. Returns every match so the caller can refuse an ambiguous\n * prefix instead of guessing a room's newest thread.\n */\nexport function findThreadRootsByPrefix(topicId: string, prefix: string): string[] {\n const bare = prefix.replace(/[^0-9A-Za-z]/g, \"\");\n if (!bare) return [];\n const rows = db\n .query(\n `SELECT DISTINCT thread_root_id AS rootId FROM api_messages\n WHERE topic_id = ? AND thread_root_id IS NOT NULL AND deleted = 0`,\n )\n .all(topicId) as { rootId: string }[];\n return rows\n .filter((row) => row.rootId.replace(/[^0-9A-Za-z]/g, \"\").startsWith(bare))\n .map((row) => row.rootId);\n}\n\n/** Threads in a topic that have at least one reply, most recently active first. */\nexport function listTopicThreadRoots(\n topicId: string,\n limit = 20,\n): { rootId: string; replyCount: number; lastReplyAt: string }[] {\n return db\n .query(\n `SELECT thread_root_id AS rootId, COUNT(*) AS replyCount, MAX(created_at) AS lastReplyAt\n FROM api_messages\n WHERE topic_id = ? AND thread_root_id IS NOT NULL AND deleted = 0\n GROUP BY thread_root_id\n ORDER BY lastReplyAt DESC\n LIMIT ?`,\n )\n .all(topicId, Math.max(1, limit)) as {\n rootId: string;\n replyCount: number;\n lastReplyAt: string;\n }[];\n}\n\n/**\n * Find the newest same-user/same-text message that is recent enough to be the\n * message just posted before a follow-up `/ai` call. This is a compatibility\n * fallback for clients that persist attachments through `/messages` but do not\n * repeat their file ids in the `/ai` request body.\n */\nexport function findRecentUserMessage(\n topicId: string,\n authorId: string,\n text: string,\n maxAgeMs: number,\n): MessageDto | undefined {\n const row = db\n .query(\n `SELECT * FROM api_messages\n WHERE topic_id = ? AND author_id = ? AND text = ?\n AND deleted = 0\n ORDER BY rowid DESC\n LIMIT 1`,\n )\n .get(topicId, authorId, text) as ApiMessageRow | undefined;\n if (!row) return undefined;\n\n const createdMs = Date.parse(row.created_at);\n if (!Number.isFinite(createdMs) || Date.now() - createdMs > maxAgeMs) return undefined;\n return rowToDto(row);\n}\n\n/**\n * Latest message text per topic, keyed by topic_id. Used to render a preview\n * subtitle in the topic list. One index-driven query (MAX(rowid) per topic)\n * instead of N round-trips. Empty topics are simply absent from the map.\n */\nexport function getLastMessagePreviews(topicIds?: readonly string[]): Map<string, string> {\n const uniqueTopicIds = topicIds ? [...new Set(topicIds)] : undefined;\n if (uniqueTopicIds && uniqueTopicIds.length === 0) return new Map();\n const topicFilter = uniqueTopicIds\n ? `AND topic_id IN (${uniqueTopicIds.map(() => \"?\").join(\",\")})`\n : \"\";\n const rows = db\n .query(\n `SELECT m.topic_id AS topic_id, m.text AS text\n FROM api_messages m\n JOIN (\n SELECT topic_id, MAX(rowid) AS mx FROM api_messages\n WHERE deleted = 0 AND thread_root_id IS NULL\n ${topicFilter}\n GROUP BY topic_id\n ) last ON m.topic_id = last.topic_id AND m.rowid = last.mx`,\n )\n .all(...(uniqueTopicIds ?? [])) as { topic_id: string; text: string }[];\n\n const out = new Map<string, string>();\n for (const r of rows) {\n const preview = (r.text ?? \"\").replace(/\\s+/g, \" \").trim().slice(0, 120);\n if (preview) out.set(r.topic_id, preview);\n }\n return out;\n}\n\n/** Hard-delete every message in a topic (used when a topic is deleted). */\nexport function deleteMessagesForTopic(topicId: string): number {\n const res = db.query(\"DELETE FROM api_messages WHERE topic_id = ?\").run(topicId);\n return Number(res.changes ?? 0);\n}\n\n/** Anonymize all messages authored by a deleted user. */\nexport function anonymizeApiMessages(userId: string): void {\n db.query(\"UPDATE api_messages SET author_id = 'deleted-user' WHERE author_id = ?\").run(userId);\n}\n\n/** Topic ids whose persisted attachment JSON references this exact upload id.\n * Used only as a compatibility bridge for uploads created before ACL metadata\n * was introduced. JSON UUIDs are quoted, avoiding substring matches. */\nexport function listTopicIdsForAttachment(fileId: string): string[] {\n const needle = `%\"${fileId.replace(/[\\\\%_]/g, (char) => `\\\\${char}`)}\"%`;\n // The ESCAPE literal must reach SQLite as a SINGLE backslash. SQLite string\n // literals do no backslash processing, so '\\\\' there is two characters and\n // fails at row-evaluation time (\"ESCAPE expression must be a single\n // character\") — which only surfaces once api_messages has any rows.\n const rows = db\n .query<{ topic_id: string }, [string]>(\n \"SELECT DISTINCT topic_id FROM api_messages WHERE attachments LIKE ? ESCAPE '\\\\'\",\n )\n .all(needle);\n return rows.map((row) => row.topic_id);\n}\n\n/**\n * Copy all messages from one topic to another (used by fork).\n * Each message gets a new UUID but retains original content, author, and timestamps.\n * Returns the number of messages copied.\n */\nexport function copyMessagesForTopic(sourceTopicId: string, targetTopicId: string): number {\n return copyMessageSnapshotToTopic(captureMessageSnapshotForTopic(sourceTopicId), targetTopicId);\n}\n\nexport interface TopicMessageSnapshot {\n sourceTopicId: string;\n rows: ApiMessageRow[];\n capturedAt: string;\n maxRowid: number;\n}\n\n/** Capture immutable message rows for point-in-time fork/compaction work. */\nexport function captureMessageSnapshotForTopic(topicId: string): TopicMessageSnapshot {\n const rows = db\n .query(\n \"SELECT *, rowid AS rowid FROM api_messages WHERE topic_id = ? AND deleted = 0 ORDER BY rowid ASC\",\n )\n .all(topicId) as ApiMessageRow[];\n return {\n sourceTopicId: topicId,\n rows: rows.map((row) => ({ ...row })),\n capturedAt: new Date().toISOString(),\n maxRowid: rows.at(-1)?.rowid ?? 0,\n };\n}\n\n/** Copy only rows captured by captureMessageSnapshotForTopic; never re-read the source. */\nexport function copyMessageSnapshotToTopic(\n snapshot: TopicMessageSnapshot,\n targetTopicId: string,\n): number {\n const { rows } = snapshot;\n if (rows.length === 0) return 0;\n\n const idMap = new Map(rows.map((r) => [r.id, crypto.randomUUID()]));\n let copied = 0;\n for (const r of rows) {\n const newId = idMap.get(r.id);\n if (!newId) continue;\n appendApiMessage(\n {\n ...rowToDto(r),\n id: newId,\n topicId: targetTopicId,\n parentId: r.parent_id ? (idMap.get(r.parent_id) ?? r.parent_id) : undefined,\n threadRootId: r.thread_root_id\n ? (idMap.get(r.thread_root_id) ?? r.thread_root_id)\n : undefined,\n },\n { notify: false, updateTopicLastMessageAt: false },\n );\n copied++;\n }\n\n return copied;\n}\n\n/**\n * Get all messages for a topic in chronological order (used by export).\n */\nexport function getAllMessagesForTopic(topicId: string): ApiMessageRow[] {\n return db\n .query(\n \"SELECT *, rowid AS rowid FROM api_messages WHERE topic_id = ? AND deleted = 0 ORDER BY rowid ASC\",\n )\n .all(topicId) as ApiMessageRow[];\n}\n\nexport function getMessagesForTopicAfterRowid(\n topicId: string,\n afterRowid: number,\n): ApiMessageRow[] {\n return db\n .query(\n \"SELECT *, rowid AS rowid FROM api_messages WHERE topic_id = ? AND rowid > ? AND deleted = 0 ORDER BY rowid ASC\",\n )\n .all(topicId, afterRowid) as ApiMessageRow[];\n}\n",
|
|
34
34
|
"/**\n * Durable evidence for the hub↔node topic link (topic-link design v2 §4.2,\n * §4.5, PR7). Two tables, both written by the node and only ever read by a\n * host through the authenticated Runtime Gateway:\n *\n * - `api_topic_create_claims` — one row per host `requestId` on a room-creating\n * request (`POST /topics`, `POST /topics/:id/derive`). Written inside the same\n * SQLite transaction that inserts the topic, so a response lost after commit\n * can always be replayed by id instead of being guessed at (title/parent\n * heuristics are forbidden by the design).\n * - `api_topic_tombstones` — one row per topic that left the host-visible\n * surface, stamped with THIS node's identity. Written by SQLite triggers on\n * `api_topics`, so every delete path (gateway, MCP, CLI, account deletion,\n * future ones) records it in the very statement that removes the row; there\n * is no code path that can delete a topic and forget the tombstone.\n *\n * `api_node_identity` holds the node id the triggers stamp. The node process\n * records its `NODE_ID` there at start (and the delete cascade re-asserts it)\n * via {@link recordTopicLinkNodeIdentity}: a database copied to another install\n * keeps the old id on its old tombstones, so the existence API — which only\n * answers `gone` for a tombstone written under the identity it is answering\n * as — can never turn a copied store's history into a delete on the new node.\n * Until an identity is recorded, tombstones carry NULL and never count as\n * `gone` (fail-safe). This module deliberately does not import\n * `#platform/config`: that would create state paths merely by importing the\n * public storage facade.\n */\n\nimport { createHash } from \"node:crypto\";\nimport { GENERAL_TOPIC_ID } from \"#platform/constants\";\n// Side effect: registers `api_messages`, which the message fence trigger\n// guards (and orders it before this schema).\nimport \"#storage/api-messages\";\nimport { db } from \"#storage/forum-db\";\n// Side effect: registers `runtime_topic_state`, which the message fence\n// trigger reads (and orders it before this schema).\nimport \"#storage/runtime-topic-state\";\nimport { registerStorageSchemaInitializer } from \"#storage/storage-host\";\n\nexport type TopicCreateClaimOp = \"create\" | \"derive\" | \"abort\";\nexport type TopicCreateClaimState = \"committed\" | \"aborted\";\nexport type TopicTombstoneReason = \"deleted\" | \"unshared\";\n\nexport interface TopicCreateClaim {\n principalKey: string;\n requestId: string;\n op: TopicCreateClaimOp;\n payloadHash: string;\n topicId: string | null;\n state: TopicCreateClaimState;\n nodeId: string | null;\n /** Highest `api_messages.rowid` of the topic when the claim committed (seeded history). */\n seedMaxMessageRowid: number;\n /** Derive only: the source topic the claim was made for (null on create / legacy rows). */\n sourceTopicId: string | null;\n /** Message count of the topic when the claim committed (null on legacy rows). */\n seedMessageCount: number | null;\n /** sha256 of the sorted message ids at claim time (null on legacy rows). */\n seedMessageIdsHash: string | null;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface TopicTombstone {\n seq: number;\n topicId: string;\n nodeId: string | null;\n reason: TopicTombstoneReason;\n surface: string | null;\n surfaceScope: string | null;\n deletedAt: string;\n /**\n * Present on feed entries that come from `api_topic_scope_moves`: the room\n * was moved OUT of `surfaceScope` by an admin scope repair (reported to the\n * old scope as `unshared`). Not a row of `api_topic_tombstones`.\n */\n scopeMoved?: true;\n}\n\ninterface ClaimRow {\n principal_key: string;\n request_id: string;\n op: string;\n payload_hash: string;\n topic_id: string | null;\n state: string;\n node_id: string | null;\n seed_max_message_rowid: number | bigint | null;\n source_topic_id?: string | null;\n seed_message_count?: number | bigint | null;\n seed_message_ids_hash?: string | null;\n created_at: string;\n updated_at: string;\n}\n\ninterface TombstoneRow {\n seq: number | bigint;\n topic_id: string;\n node_id: string | null;\n reason: string;\n surface: string | null;\n surface_scope: string | null;\n deleted_at: string;\n}\n\n/** Claims are kept at least this long (design v2 §4.2: ≥ 30 days). */\nexport const TOPIC_CREATE_CLAIM_RETENTION_MS = 30 * 24 * 60 * 60_000;\n\nconst NODE_IDENTITY_SQL = \"(SELECT node_id FROM api_node_identity WHERE singleton = 1)\";\nconst NOW_SQL = \"strftime('%Y-%m-%dT%H:%M:%fZ','now')\";\nconst TOMBSTONE_SEQ_SQL = \"(SELECT seq FROM api_topic_tombstone_seq WHERE singleton = 1)\";\n// Advances the never-decreasing tombstone sequence. Runs as the first\n// statement of every tombstone-writing trigger, so the new row's seq is read\n// back from the counter within the same statement/transaction.\nconst BUMP_TOMBSTONE_SEQ_SQL =\n \"UPDATE api_topic_tombstone_seq SET seq = seq + 1 WHERE singleton = 1\";\nconst NEW_EPOCH_SQL = \"lower(hex(randomblob(16)))\";\n\n/**\n * Owner-id prefix of the runtime maintenance fence a claim abort holds while\n * it deletes the claimed topic. While such a fence is live, the\n * `api_messages_claim_abort_fence` trigger refuses every message insert into\n * that topic (any writer, any process), so nothing can land between the\n * abort's \"no new messages\" check and the delete.\n */\nexport const TOPIC_CLAIM_ABORT_OWNER_PREFIX = \"topic-link-abort:\";\n/** The message the fence trigger raises; matched by ingress to answer 409. */\nexport const TOPIC_CLAIM_ABORT_FENCE_ERROR = \"topic_claim_abort_in_progress\";\n// Same staleness rule as `runtime-topic-state` (TOPIC_MAINTENANCE_STALE_MS):\n// a crashed abort never blocks a room for longer than a stale fence.\nconst CLAIM_ABORT_FENCE_STALE_MS = 30_000;\nconst NOW_MS_SQL = \"CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)\";\nconst CLAIM_ABORT_FENCE_PREDICATE = `maintenance = 1\n AND maintenance_owner LIKE '${TOPIC_CLAIM_ABORT_OWNER_PREFIX}%'\n AND heartbeat_at IS NOT NULL\n AND heartbeat_at >= ${NOW_MS_SQL} - ${CLAIM_ABORT_FENCE_STALE_MS}`;\n\ntype SchemaDatabase = {\n exec(sql: string): unknown;\n transaction<T>(fn: () => T): (() => T) & { immediate?: () => T };\n query(sql: string): { all(...params: never[]): unknown[] };\n};\n\nconst SCHEMA_TABLES = [\n \"api_node_identity\",\n \"api_topic_create_claims\",\n \"api_topic_tombstones\",\n \"api_topic_tombstone_seq\",\n \"api_topic_scope_repair_grants\",\n \"api_topic_scope_moves\",\n];\nconst SCHEMA_INDEXES = [\n \"idx_api_topic_create_claims_topic\",\n \"idx_api_topic_create_claims_created\",\n \"idx_api_topic_create_claims_principal\",\n \"idx_api_topic_create_claims_settled_at\",\n \"idx_api_topic_scope_moves_seq\",\n];\n/** Columns added to `api_topic_create_claims` after its first release. */\nconst CLAIM_ADDED_COLUMNS: Record<string, string> = {\n source_topic_id: \"TEXT\",\n seed_message_count: \"INTEGER\",\n seed_message_ids_hash: \"TEXT\",\n settled_at: \"TEXT\",\n};\nconst SCHEMA_INDEXES_TOMBSTONES = [\"idx_api_topic_tombstones_seq\"];\n/** Trigger → a marker its current SQL must contain (older builds lack it). */\nconst SCHEMA_TRIGGERS: Record<string, string> = {\n api_topics_tombstone_on_delete: \"api_topic_tombstone_seq\",\n api_topics_tombstone_on_unshare: \"api_topic_tombstone_seq\",\n api_topics_tombstone_on_reshare: \"surface_scope IS NEW.surface_scope\",\n api_topics_tombstone_on_insert: \"api_topic_tombstones\",\n api_messages_claim_abort_fence: TOPIC_CLAIM_ABORT_OWNER_PREFIX,\n api_topics_otium_scope_immutable: \"api_topic_scope_repair_grants\",\n};\n\n/** The message the scope-immutability trigger raises. */\nexport const OTIUM_TOPIC_SCOPE_IMMUTABLE_ERROR = \"otium_topic_scope_immutable\";\n\n/**\n * Read-only: whether the schema (and identity) is already current. Every\n * process start runs the initializer, so the common path must not write — a\n * write here would take the database lock on every boot and can fail with\n * SQLITE_BUSY while other processes start concurrently.\n */\nfunction topicLinkSchemaIsCurrent(database: SchemaDatabase, nodeId?: string): boolean {\n const objects = new Map(\n (\n database\n .query(\"SELECT name, sql FROM sqlite_master WHERE type IN ('table','index','trigger')\")\n .all() as Array<{ name: string; sql: string | null }>\n ).map((row) => [row.name, row.sql ?? \"\"]),\n );\n for (const name of [...SCHEMA_TABLES, ...SCHEMA_INDEXES, ...SCHEMA_INDEXES_TOMBSTONES]) {\n if (!objects.has(name)) return false;\n }\n for (const [name, marker] of Object.entries(SCHEMA_TRIGGERS)) {\n if (!objects.get(name)?.includes(marker)) return false;\n }\n if (!columnNames(database, \"api_node_identity\").has(\"epoch_id\")) return false;\n const claimColumns = columnNames(database, \"api_topic_create_claims\");\n for (const column of Object.keys(CLAIM_ADDED_COLUMNS)) {\n if (!claimColumns.has(column)) return false;\n }\n const identity = database\n .query(\"SELECT node_id, epoch_id FROM api_node_identity WHERE singleton = 1\")\n .all() as Array<{ node_id: string; epoch_id: string | null }>;\n if (identity.some((row) => row.epoch_id === null)) return false;\n if (nodeId && identity[0]?.node_id !== nodeId) return false;\n const counter = database\n .query(\n `SELECT (SELECT seq FROM api_topic_tombstone_seq WHERE singleton = 1) AS counter,\n MAX((SELECT COALESCE(MAX(seq), 0) FROM api_topic_tombstones),\n (SELECT COALESCE(MAX(seq), 0) FROM api_topic_scope_moves)) AS max_seq`,\n )\n .all() as Array<{ counter: number | bigint | null; max_seq: number | bigint }>;\n const row = counter[0];\n return row?.counter !== null && row?.counter !== undefined && row.counter >= row.max_seq;\n}\n\nfunction columnNames(database: SchemaDatabase, table: string): Set<string> {\n const rows = database.query(`PRAGMA table_info(${table})`).all() as Array<{ name: string }>;\n return new Set(rows.map((row) => row.name));\n}\n\n/**\n * Idempotent, and all-or-nothing: every statement is `IF NOT EXISTS` / an\n * upsert / a drop-and-recreate of a trigger, and the whole set runs in one\n * transaction so a crash half-way never leaves triggers without the table\n * they write to.\n */\nexport function initializeTopicLinkRecordsSchema(database: SchemaDatabase, nodeId?: string): void {\n if (topicLinkSchemaIsCurrent(database, nodeId)) return;\n const migrate = database.transaction(() => {\n database.exec(`\n CREATE TABLE IF NOT EXISTS api_node_identity (\n singleton INTEGER PRIMARY KEY CHECK (singleton = 1),\n node_id TEXT NOT NULL,\n epoch_id TEXT,\n updated_at TEXT NOT NULL\n )\n `);\n // PR7 fix: a random id minted when this store first records an identity.\n // Survives NODE_ID changes; a wiped/recreated store gets a new one.\n if (!columnNames(database, \"api_node_identity\").has(\"epoch_id\")) {\n database.exec(\"ALTER TABLE api_node_identity ADD COLUMN epoch_id TEXT\");\n }\n database.exec(\n `UPDATE api_node_identity SET epoch_id = ${NEW_EPOCH_SQL} WHERE epoch_id IS NULL`,\n );\n database.exec(`\n CREATE TABLE IF NOT EXISTS api_topic_create_claims (\n principal_key TEXT NOT NULL,\n request_id TEXT NOT NULL,\n op TEXT NOT NULL CHECK (op IN ('create','derive','abort')),\n payload_hash TEXT NOT NULL,\n topic_id TEXT,\n state TEXT NOT NULL CHECK (state IN ('committed','aborted')),\n node_id TEXT,\n seed_max_message_rowid INTEGER NOT NULL DEFAULT 0,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n source_topic_id TEXT,\n seed_message_count INTEGER,\n seed_message_ids_hash TEXT,\n settled_at TEXT,\n PRIMARY KEY (principal_key, request_id)\n )\n `);\n // Review fixes (additive): the derive source a claim was made for, and the\n // exact message set the created topic was seeded with.\n const claimColumns = columnNames(database, \"api_topic_create_claims\");\n for (const [column, type] of Object.entries(CLAIM_ADDED_COLUMNS)) {\n if (!claimColumns.has(column)) {\n database.exec(`ALTER TABLE api_topic_create_claims ADD COLUMN ${column} ${type}`);\n }\n }\n database.exec(\n `CREATE INDEX IF NOT EXISTS idx_api_topic_create_claims_principal\n ON api_topic_create_claims(principal_key, state, topic_id)`,\n );\n // Retention anchor of a settled (aborted) claim is its settlement time.\n database.exec(\n `CREATE INDEX IF NOT EXISTS idx_api_topic_create_claims_settled_at\n ON api_topic_create_claims(state, settled_at)`,\n );\n // Scope repair (review fix 6): the one sanctioned way to change an otium\n // topic's surface_scope. A grant row exists only inside the repair's own\n // transaction (inserted and deleted before commit), so no other\n // connection ever observes it.\n database.exec(`\n CREATE TABLE IF NOT EXISTS api_topic_scope_repair_grants (\n topic_id TEXT PRIMARY KEY\n )\n `);\n // Scope move history + audit (one row per admin repair). Its seq comes\n // from the tombstone counter, so moves merge into the tombstone feed in\n // order: a hub bound to the OLD scope sees the move as `unshared`.\n database.exec(`\n CREATE TABLE IF NOT EXISTS api_topic_scope_moves (\n seq INTEGER PRIMARY KEY,\n topic_id TEXT NOT NULL,\n node_id TEXT,\n from_scope TEXT,\n to_scope TEXT NOT NULL,\n actor TEXT NOT NULL,\n reason TEXT NOT NULL,\n claims_left INTEGER NOT NULL,\n moved_at TEXT NOT NULL\n )\n `);\n database.exec(\n \"CREATE INDEX IF NOT EXISTS idx_api_topic_scope_moves_seq ON api_topic_scope_moves(topic_id, seq)\",\n );\n database.exec(\n \"CREATE INDEX IF NOT EXISTS idx_api_topic_create_claims_topic ON api_topic_create_claims(topic_id)\",\n );\n database.exec(\n \"CREATE INDEX IF NOT EXISTS idx_api_topic_create_claims_created ON api_topic_create_claims(created_at)\",\n );\n database.exec(`\n CREATE TABLE IF NOT EXISTS api_topic_tombstones (\n topic_id TEXT PRIMARY KEY,\n seq INTEGER NOT NULL,\n node_id TEXT,\n reason TEXT NOT NULL CHECK (reason IN ('deleted','unshared')),\n surface TEXT,\n surface_scope TEXT,\n deleted_at TEXT NOT NULL\n )\n `);\n database.exec(\n \"CREATE INDEX IF NOT EXISTS idx_api_topic_tombstones_seq ON api_topic_tombstones(seq)\",\n );\n // Never-decreasing tombstone sequence (PR7 fix). `api_topic_tombstones` is\n // a current-state table whose rows are deleted on reshare/reinsert, so\n // MAX(seq)+1 could hand out a seq a cursor already passed. Seeded from the\n // table on every init, and never lowered.\n database.exec(`\n CREATE TABLE IF NOT EXISTS api_topic_tombstone_seq (\n singleton INTEGER PRIMARY KEY CHECK (singleton = 1),\n seq INTEGER NOT NULL\n )\n `);\n database.exec(`\n INSERT INTO api_topic_tombstone_seq (singleton, seq)\n VALUES (1, (SELECT MAX(\n (SELECT COALESCE(MAX(seq), 0) FROM api_topic_tombstones),\n (SELECT COALESCE(MAX(seq), 0) FROM api_topic_scope_moves))))\n ON CONFLICT(singleton) DO UPDATE SET seq = MAX(api_topic_tombstone_seq.seq, excluded.seq)\n `);\n // Recreated on every init so a store migrated by an earlier build (whose\n // triggers computed MAX(seq)+1) gets the counter-based versions.\n for (const name of [\n \"api_topics_tombstone_on_delete\",\n \"api_topics_tombstone_on_unshare\",\n \"api_topics_tombstone_on_reshare\",\n \"api_topics_tombstone_on_insert\",\n \"api_messages_claim_abort_fence\",\n \"api_topics_otium_scope_immutable\",\n ]) {\n database.exec(`DROP TRIGGER IF EXISTS ${name}`);\n }\n // Hard delete, from any writer. `DROP TABLE` (the legacy schema rebuild)\n // does not fire row triggers, so a migration never fabricates tombstones.\n database.exec(`\n CREATE TRIGGER api_topics_tombstone_on_delete\n AFTER DELETE ON api_topics\n BEGIN\n ${BUMP_TOMBSTONE_SEQ_SQL};\n INSERT OR REPLACE INTO api_topic_tombstones\n (topic_id, seq, node_id, reason, surface, surface_scope, deleted_at)\n VALUES\n (OLD.id, ${TOMBSTONE_SEQ_SQL}, ${NODE_IDENTITY_SQL}, 'deleted',\n OLD.surface, OLD.surface_scope, ${NOW_SQL});\n END\n `);\n // Left the Otium surface (moved to another surface or hidden). Evidence of\n // a withdrawal, never of a deletion: the existence API still answers\n // `present` for such a topic.\n database.exec(`\n CREATE TRIGGER api_topics_tombstone_on_unshare\n AFTER UPDATE OF surface, visibility ON api_topics\n WHEN OLD.surface = 'otium' AND COALESCE(OLD.visibility, 'visible') != 'hidden'\n AND (NEW.surface IS NOT 'otium' OR NEW.visibility = 'hidden')\n BEGIN\n ${BUMP_TOMBSTONE_SEQ_SQL};\n INSERT OR REPLACE INTO api_topic_tombstones\n (topic_id, seq, node_id, reason, surface, surface_scope, deleted_at)\n VALUES\n (OLD.id, ${TOMBSTONE_SEQ_SQL}, ${NODE_IDENTITY_SQL}, 'unshared',\n OLD.surface, OLD.surface_scope, ${NOW_SQL});\n END\n `);\n database.exec(`\n CREATE TRIGGER api_topics_tombstone_on_reshare\n AFTER UPDATE OF surface, visibility ON api_topics\n WHEN NEW.surface = 'otium' AND COALESCE(NEW.visibility, 'visible') != 'hidden'\n BEGIN\n -- Only the withdrawal from the scope the room is back in is undone; an\n -- unshare from another workspace stays that workspace's evidence.\n DELETE FROM api_topic_tombstones\n WHERE topic_id = NEW.id AND reason = 'unshared' AND surface_scope IS NEW.surface_scope;\n END\n `);\n // An otium room's workspace is fixed (review fix 6): a claim, a tombstone\n // and the host's mapping all bind to it, and one topic_id-keyed tombstone\n // cannot express several past scopes. Only the audited scope repair\n // (`adminRepairOtiumTopicScope`) may change it, through a grant row that exists\n // only inside its own transaction. Leaving the otium surface is allowed\n // (that is an unshare, tombstoned with the old scope).\n database.exec(`\n CREATE TRIGGER api_topics_otium_scope_immutable\n BEFORE UPDATE OF surface, surface_scope ON api_topics\n WHEN NEW.surface = 'otium'\n AND OLD.surface_scope IS NOT NEW.surface_scope\n AND NOT EXISTS (SELECT 1 FROM api_topic_scope_repair_grants WHERE topic_id = OLD.id)\n BEGIN\n SELECT RAISE(ABORT, '${OTIUM_TOPIC_SCOPE_IMMUTABLE_ERROR}');\n END\n `);\n // A row that exists again (restored or re-inserted id) is not gone.\n database.exec(`\n CREATE TRIGGER api_topics_tombstone_on_insert\n AFTER INSERT ON api_topics\n BEGIN\n DELETE FROM api_topic_tombstones WHERE topic_id = NEW.id;\n END\n `);\n // A topic a claim abort is deleting accepts no message (PR7 fix): see\n // TOPIC_CLAIM_ABORT_OWNER_PREFIX. Checked by SQLite on every insert path,\n // atomically with the insert itself.\n database.exec(`\n CREATE TRIGGER api_messages_claim_abort_fence\n BEFORE INSERT ON api_messages\n WHEN EXISTS (SELECT 1 FROM runtime_topic_state\n WHERE topic_id = NEW.topic_id AND ${CLAIM_ABORT_FENCE_PREDICATE})\n BEGIN\n SELECT RAISE(ABORT, '${TOPIC_CLAIM_ABORT_FENCE_ERROR}');\n END\n `);\n if (nodeId) {\n database.exec(\n `INSERT INTO api_node_identity (singleton, node_id, epoch_id, updated_at)\n VALUES (1, '${nodeId.replaceAll(\"'\", \"''\")}', ${NEW_EPOCH_SQL}, ${NOW_SQL})\n ON CONFLICT(singleton) DO UPDATE SET node_id = excluded.node_id, updated_at = excluded.updated_at\n WHERE api_node_identity.node_id IS NOT excluded.node_id`,\n );\n }\n });\n // BEGIN IMMEDIATE when available: a migrating process waits on the busy\n // timeout for another one instead of failing its read→write upgrade.\n if (migrate.immediate) migrate.immediate();\n else migrate();\n}\n\n// After api_topics (20), api_messages (30) and runtime_topic_state (32): the\n// triggers name their columns, so the tables must already have their shape.\nregisterStorageSchemaInitializer((database) => initializeTopicLinkRecordsSchema(database), 45);\n\n// ── canonical payload hash ────────────────────────────────────────────────\n\nfunction canonicalJson(value: unknown): string {\n if (Array.isArray(value)) return `[${value.map(canonicalJson).join(\",\")}]`;\n if (value && typeof value === \"object\") {\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, entry]) => entry !== undefined)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));\n return `{${entries.map(([key, entry]) => `${JSON.stringify(key)}:${canonicalJson(entry)}`).join(\",\")}}`;\n }\n return JSON.stringify(value ?? null);\n}\n\n/**\n * sha256 (hex) of the canonical JSON of a room-creating request body without\n * the saga's own `requestId`/`payloadHash` — byte-for-byte the hub's\n * `linkPayloadHash` (otium `link/link-intents.ts`): keys sorted at every depth\n * by UTF-16 code unit, compact separators, `undefined` members dropped.\n *\n * For derive the caller passes `{ sourceTopicId: <path id>, ...body }` (the\n * same body forked from two parents must not hash equal).\n */\nexport function topicLinkPayloadHash(body: Record<string, unknown>): string {\n const { requestId: _requestId, payloadHash: _payloadHash, ...payload } = body;\n return createHash(\"sha256\").update(canonicalJson(payload)).digest(\"hex\");\n}\n\n// ── node identity ─────────────────────────────────────────────────────────\n\n/** Record the identity new tombstones and claims are stamped with (no-op when unchanged). */\nexport function recordTopicLinkNodeIdentity(nodeId: string): void {\n const id = nodeId.trim();\n if (!id) return;\n db.query(\n `INSERT INTO api_node_identity (singleton, node_id, epoch_id, updated_at)\n VALUES (1, ?, ${NEW_EPOCH_SQL}, ${NOW_SQL})\n ON CONFLICT(singleton) DO UPDATE SET node_id = excluded.node_id, updated_at = excluded.updated_at\n WHERE api_node_identity.node_id IS NOT excluded.node_id`,\n ).run(id);\n}\n\n/**\n * Random id minted when this store first recorded an identity (`dbEpoch` on\n * the wire). A wiped/recreated store answering under the same `NODE_ID` has a\n * different one; a restore of a backup of the SAME store does not (residual\n * risk, see the contract). Null until an identity is recorded.\n */\nexport function topicLinkDbEpoch(): string | null {\n return (\n db\n .query<{ epoch_id: string | null }, []>(\n \"SELECT epoch_id FROM api_node_identity WHERE singleton = 1\",\n )\n .get()?.epoch_id ?? null\n );\n}\n\n/**\n * The highest tombstone seq ever handed out (never decreases, also counts\n * rows later removed by a reshare/reinsert). A hub whose recorded cursor is\n * above this value is talking to a rolled-back store.\n */\nexport function topicTombstoneHighWater(): number {\n const row = db\n .query<{ seq: number | bigint }, []>(\n \"SELECT seq FROM api_topic_tombstone_seq WHERE singleton = 1\",\n )\n .get();\n return Number(row?.seq ?? 0);\n}\n\n/** The identity new tombstones and claims are stamped with. */\nexport function topicLinkNodeIdentity(): string | null {\n return (\n db\n .query<{ node_id: string }, []>(\"SELECT node_id FROM api_node_identity WHERE singleton = 1\")\n .get()?.node_id ?? null\n );\n}\n\n// ── create claims ─────────────────────────────────────────────────────────\n\nfunction toClaim(row: ClaimRow): TopicCreateClaim {\n return {\n principalKey: row.principal_key,\n requestId: row.request_id,\n op: row.op as TopicCreateClaimOp,\n payloadHash: row.payload_hash,\n topicId: row.topic_id,\n state: row.state as TopicCreateClaimState,\n nodeId: row.node_id,\n seedMaxMessageRowid: Number(row.seed_max_message_rowid ?? 0),\n sourceTopicId: row.source_topic_id ?? null,\n seedMessageCount:\n row.seed_message_count === null || row.seed_message_count === undefined\n ? null\n : Number(row.seed_message_count),\n seedMessageIdsHash: row.seed_message_ids_hash ?? null,\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n };\n}\n\nexport function getTopicCreateClaim(\n principalKey: string,\n requestId: string,\n): TopicCreateClaim | null {\n const row = db\n .query<ClaimRow, [string, string]>(\n \"SELECT * FROM api_topic_create_claims WHERE principal_key = ? AND request_id = ?\",\n )\n .get(principalKey, requestId);\n return row ? toClaim(row) : null;\n}\n\n/**\n * Committed claims of one principal for exactly these topics — for\n * `hostCreate` on topic DTOs. Bounded by the ids asked for (index\n * `(principal_key, state, topic_id)`), never the principal's whole history.\n */\nexport function committedClaimsByTopic(\n principalKey: string,\n topicIds: readonly string[],\n): Map<string, TopicCreateClaim> {\n const byTopic = new Map<string, TopicCreateClaim>();\n const unique = [...new Set(topicIds)];\n for (let start = 0; start < unique.length; start += 500) {\n const chunk = unique.slice(start, start + 500);\n const rows = db\n .query<ClaimRow, string[]>(\n `SELECT * FROM api_topic_create_claims\n WHERE principal_key = ? AND state = 'committed'\n AND topic_id IN (${chunk.map(() => \"?\").join(\",\")})`,\n )\n .all(principalKey, ...chunk);\n for (const row of rows) if (row.topic_id) byTopic.set(row.topic_id, toClaim(row));\n }\n return byTopic;\n}\n\nfunction maxMessageRowid(topicId: string): number {\n const row = db\n .query<{ max_rowid: number | bigint | null }, [string]>(\n \"SELECT MAX(rowid) AS max_rowid FROM api_messages WHERE topic_id = ?\",\n )\n .get(topicId);\n return Number(row?.max_rowid ?? 0);\n}\n\n/** Count and sha256 of the sorted message ids of a topic: its exact message set. */\nfunction messageSetOf(topicId: string): { count: number; hash: string } {\n const ids = db\n .query<{ id: string }, [string]>(\"SELECT id FROM api_messages WHERE topic_id = ? ORDER BY id\")\n .all(topicId)\n .map((row) => row.id);\n return { count: ids.length, hash: createHash(\"sha256\").update(ids.join(\"\\n\")).digest(\"hex\") };\n}\n\n/**\n * Record a committed claim. MUST be called inside the transaction that inserts\n * the topic row (the `withinCreateTransaction` hook of `registerTopic` /\n * `createDerivedTopic`): a plain INSERT, so a concurrent second request with\n * the same key fails the primary key and rolls its own topic back.\n */\nexport function insertCommittedTopicCreateClaim(input: {\n principalKey: string;\n requestId: string;\n op: \"create\" | \"derive\";\n payloadHash: string;\n topicId: string;\n /** Derive: the path source topic the claim is bound to. */\n sourceTopicId?: string;\n}): TopicCreateClaim {\n const now = new Date().toISOString();\n const seed = maxMessageRowid(input.topicId);\n const seeded = messageSetOf(input.topicId);\n db.query(\n `INSERT INTO api_topic_create_claims\n (principal_key, request_id, op, payload_hash, topic_id, state, node_id,\n seed_max_message_rowid, created_at, updated_at,\n source_topic_id, seed_message_count, seed_message_ids_hash)\n VALUES (?, ?, ?, ?, ?, 'committed', ${NODE_IDENTITY_SQL}, ?, ?, ?, ?, ?, ?)`,\n ).run(\n input.principalKey,\n input.requestId,\n input.op,\n input.payloadHash,\n input.topicId,\n seed,\n now,\n now,\n input.sourceTopicId ?? null,\n seeded.count,\n seeded.hash,\n );\n const claim = getTopicCreateClaim(input.principalKey, input.requestId);\n if (!claim) throw new Error(\"topic create claim was not recorded\");\n return claim;\n}\n\n/**\n * Write the aborted fence for a key that has no claim yet, so a create that\n * arrives after the abort is refused rather than orphaned. No-op (false) when\n * any claim already exists for the key. Callers deciding \"no claim\" MUST do so\n * in the same transaction (see `abortTopicCreateClaim`).\n */\nexport function insertTopicCreateAbortFence(principalKey: string, requestId: string): boolean {\n const now = new Date().toISOString();\n const inserted = db\n .query(\n `INSERT OR IGNORE INTO api_topic_create_claims\n (principal_key, request_id, op, payload_hash, topic_id, state, node_id,\n seed_max_message_rowid, created_at, updated_at, settled_at)\n VALUES (?, ?, 'abort', '', NULL, 'aborted', ${NODE_IDENTITY_SQL}, 0, ?, ?, ?)`,\n )\n .run(principalKey, requestId, now, now, now);\n return Number(inserted.changes ?? 0) > 0;\n}\n\n/**\n * CAS a committed claim to aborted. Only for a caller that has decided the\n * claim's topic in the same transaction (deleted it, or found it gone): a\n * committed claim must never become aborted while its topic lives on.\n */\nexport function flipCommittedTopicCreateClaimToAborted(\n principalKey: string,\n requestId: string,\n): boolean {\n const updated = db\n .query(\n `UPDATE api_topic_create_claims SET state = 'aborted', updated_at = ?1, settled_at = ?1\n WHERE principal_key = ?2 AND request_id = ?3 AND state = 'committed'`,\n )\n .run(new Date().toISOString(), principalKey, requestId);\n return Number(updated.changes ?? 0) > 0;\n}\n\n/**\n * Settle a claim as aborted where that is safe without deleting anything, in\n * one `BEGIN IMMEDIATE`: no claim → aborted fence; committed claim whose topic\n * row is already gone → aborted. A committed claim whose topic still exists is\n * returned UNCHANGED (deleting it is `abortTopicCreateClaim`'s job). Returns\n * the stored claim.\n */\nexport function markTopicCreateClaimAborted(\n principalKey: string,\n requestId: string,\n): TopicCreateClaim {\n return db\n .transaction(() => {\n const current = getTopicCreateClaim(principalKey, requestId);\n if (!current) {\n insertTopicCreateAbortFence(principalKey, requestId);\n } else if (current.state === \"committed\" && !topicRowExists(current.topicId)) {\n flipCommittedTopicCreateClaimToAborted(principalKey, requestId);\n }\n const claim = getTopicCreateClaim(principalKey, requestId);\n if (!claim) throw new Error(\"topic create claim abort was not recorded\");\n return claim;\n })\n .immediate();\n}\n\nfunction topicRowExists(topicId: string | null): boolean {\n if (!topicId) return false;\n return Boolean(\n db\n .query<{ found: number }, [string]>(\"SELECT 1 AS found FROM api_topics WHERE id = ?\")\n .get(topicId),\n );\n}\n\n/** Whether a live claim-abort fence currently refuses messages into this topic. */\nexport function isTopicClaimAbortFenced(topicId: string): boolean {\n return Boolean(\n db\n .query<{ found: number }, [string]>(\n `SELECT 1 AS found FROM runtime_topic_state WHERE topic_id = ? AND ${CLAIM_ABORT_FENCE_PREDICATE}`,\n )\n .get(topicId),\n );\n}\n\n/** Whether an error is the message fence trigger's refusal. */\nexport function isTopicClaimAbortFenceError(error: unknown): boolean {\n return error instanceof Error && error.message.includes(TOPIC_CLAIM_ABORT_FENCE_ERROR);\n}\n\n/**\n * Whether the claimed topic's messages differ from what it was created with.\n *\n * Compared as an exact SET (count + hash of the sorted ids recorded at claim\n * time), not by rowid: a logical dump/import or a VACUUM that renumbers rowids\n * cannot make a post-create message look seeded. Any difference — a new\n * message, a hard-deleted one — counts, so an abort only ever deletes a topic\n * holding exactly its seeded history. Legacy claims without a recorded set fall\n * back to the rowid boundary.\n */\nexport function topicHasMessagesAfterClaim(claim: TopicCreateClaim): boolean {\n if (!claim.topicId) return false;\n if (claim.seedMessageCount !== null && claim.seedMessageIdsHash !== null) {\n const current = messageSetOf(claim.topicId);\n return current.count !== claim.seedMessageCount || current.hash !== claim.seedMessageIdsHash;\n }\n const row = db\n .query<{ found: number }, [string, number]>(\n \"SELECT 1 AS found FROM api_messages WHERE topic_id = ? AND rowid > ? LIMIT 1\",\n )\n .get(claim.topicId, claim.seedMaxMessageRowid);\n return Boolean(row);\n}\n\n/** Upper bound of claims one prune call removes (bounded work per request). */\nexport const TOPIC_CREATE_CLAIM_PRUNE_BATCH = 500;\n\n/**\n * Drop claims past the retention window. Returns the number removed.\n *\n * The retention anchor is the claim's LAST settlement: a committed claim is\n * kept from its `created_at`, an aborted one (fence) from its `settled_at` —\n * the moment it became aborted (rows settled before that column existed fall\n * back to `updated_at`). An old committed claim aborted today therefore\n * keeps refusing a late create with the same requestId for a full window.\n * Removes at most `batch` rows per call.\n */\nexport function pruneTopicCreateClaims(\n now: number = Date.now(),\n retentionMs: number = TOPIC_CREATE_CLAIM_RETENTION_MS,\n batch: number = TOPIC_CREATE_CLAIM_PRUNE_BATCH,\n): number {\n const cutoff = new Date(now - retentionMs).toISOString();\n const result = db\n .query(\n `DELETE FROM api_topic_create_claims WHERE rowid IN (\n SELECT rowid FROM api_topic_create_claims\n WHERE (state = 'committed' AND created_at < ?)\n OR (state = 'aborted' AND COALESCE(settled_at, updated_at) < ?)\n LIMIT ?)`,\n )\n .run(cutoff, cutoff, batch);\n return Number(result.changes ?? 0);\n}\n\n// ── tombstones ────────────────────────────────────────────────────────────\n\nfunction toTombstone(row: TombstoneRow): TopicTombstone {\n return {\n seq: Number(row.seq),\n topicId: row.topic_id,\n nodeId: row.node_id,\n reason: row.reason as TopicTombstoneReason,\n surface: row.surface,\n surfaceScope: row.surface_scope,\n deletedAt: row.deleted_at,\n };\n}\n\nexport function getTopicTombstone(topicId: string): TopicTombstone | null {\n const row = db\n .query<TombstoneRow, [string]>(\"SELECT * FROM api_topic_tombstones WHERE topic_id = ?\")\n .get(topicId);\n return row ? toTombstone(row) : null;\n}\n\n/** Tombstones after a cursor, oldest first. */\n/**\n * The tombstone feed after a cursor, oldest first: current tombstones merged\n * with scope moves (as `unshared` for the OLD scope, `scopeMoved: true`). Both\n * take their seq from the same never-decreasing counter.\n */\nexport function listTopicTombstonesAfter(after: number, limit: number): TopicTombstone[] {\n return db\n .query<TombstoneRow & { scope_moved: number }, [number, number, number]>(\n `SELECT seq, topic_id, node_id, reason, surface, surface_scope, deleted_at, 0 AS scope_moved\n FROM api_topic_tombstones WHERE seq > ?1\n UNION ALL\n SELECT seq, topic_id, node_id, 'unshared', 'otium', from_scope, moved_at, 1\n FROM api_topic_scope_moves WHERE seq > ?2\n ORDER BY seq ASC LIMIT ?3`,\n )\n .all(after, after, limit)\n .map((row) => ({\n ...toTombstone(row),\n ...(row.scope_moved ? { scopeMoved: true as const } : {}),\n }));\n}\n\n/** The latest admin scope move of a topic (the scope it was moved out of), if any. */\nexport function latestTopicScopeMove(topicId: string): TopicTombstone | null {\n const row = db\n .query<\n { seq: number | bigint; node_id: string | null; from_scope: string | null; moved_at: string },\n [string]\n >(\n `SELECT seq, node_id, from_scope, moved_at FROM api_topic_scope_moves\n WHERE topic_id = ? ORDER BY seq DESC LIMIT 1`,\n )\n .get(topicId);\n if (!row) return null;\n return {\n seq: Number(row.seq),\n topicId,\n nodeId: row.node_id,\n reason: \"unshared\",\n surface: \"otium\",\n surfaceScope: row.from_scope,\n deletedAt: row.moved_at,\n scopeMoved: true,\n };\n}\n\n// ── otium scope repair (review fix 6 / PR12 admin repair) ────────────────\n\nexport interface AdminRepairOtiumTopicScopeInput {\n topicId: string;\n /** Only an unscoped room can be repaired: must be `null`. */\n fromScope: null;\n /** Non-empty, no leading/trailing whitespace. */\n toScope: string;\n /**\n * The row the operator observed — compare-and-set. `surface`/`surfaceScope`\n * are required; `createdAt`/`title` pin the exact row when given.\n */\n expectedRow: { surface: \"otium\"; surfaceScope: null; createdAt?: string; title?: string };\n /** Who asked (operator/CLI user, `m9-stamp`). Recorded in the history row. */\n actor: string;\n reason: string;\n}\n\nexport type AdminRepairOtiumTopicScopeRefusal =\n | \"invalid_scope\"\n | \"not_found\"\n | \"not_otium\"\n | \"scope_not_null\"\n | \"row_changed\"\n | \"title_conflict\"\n | \"duplicate_manager\"\n | \"maintenance_in_progress\";\n\nexport type AdminRepairOtiumTopicScopeResult =\n | {\n ok: true;\n topicId: string;\n fromScope: null;\n toScope: string;\n /**\n * Committed create claims of the topic, left on their ORIGINAL principal\n * (never re-bound). A claim whose principal no longer covers the new\n * scope answers `409 claim_topic_moved` on replay/abort.\n */\n claimsLeft: number;\n /** seq of the scope-move entry in the tombstone feed (also the audit id). */\n moveSeq: number;\n }\n | { ok: false; topicId: string; reason: AdminRepairOtiumTopicScopeRefusal; detail?: string };\n\ninterface RepairTopicRow {\n id: string;\n title: string;\n kind: string;\n surface: string;\n surface_scope: string | null;\n created_at: string;\n}\n\nfunction repairOneTopicScope(\n input: AdminRepairOtiumTopicScopeInput,\n): AdminRepairOtiumTopicScopeResult {\n const { topicId } = input;\n const refuse = (reason: AdminRepairOtiumTopicScopeRefusal, detail?: string) =>\n ({ ok: false, topicId, reason, ...(detail ? { detail } : {}) }) as const;\n const toScope = typeof input.toScope === \"string\" ? input.toScope : \"\";\n if (!toScope || toScope !== toScope.trim() || input.fromScope !== null) {\n return refuse(\"invalid_scope\");\n }\n const row = db\n .query<RepairTopicRow, [string]>(\n \"SELECT id, title, kind, surface, surface_scope, created_at FROM api_topics WHERE id = ?\",\n )\n .get(topicId);\n if (!row) return refuse(\"not_found\");\n if (row.surface !== \"otium\" || input.expectedRow.surface !== \"otium\") return refuse(\"not_otium\");\n if (row.surface_scope !== null || input.expectedRow.surfaceScope !== null) {\n return refuse(\"scope_not_null\", row.surface_scope ?? undefined);\n }\n if (\n (input.expectedRow.createdAt !== undefined && input.expectedRow.createdAt !== row.created_at) ||\n (input.expectedRow.title !== undefined && input.expectedRow.title !== row.title)\n ) {\n return refuse(\"row_changed\");\n }\n // A claim abort (or any delete/reset/compact) holds the topic right now.\n const busy = db\n .query<{ found: number }, [string, number]>(\n `SELECT 1 AS found FROM runtime_topic_state\n WHERE topic_id = ? AND maintenance = 1 AND heartbeat_at >= ?`,\n )\n .get(topicId, Date.now() - CLAIM_ABORT_FENCE_STALE_MS);\n if (busy) return refuse(\"maintenance_in_progress\");\n if (row.kind === \"manager\") {\n // Manager rooms are one-per-user and all titled \"General\", so — exactly as\n // in `findTopicTitleConflict` — they take no part in title conflicts.\n // What must not happen is a SECOND manager room for the same owner in one\n // scope (the PR12 CLI and hub audit D7 enforce it too; this is the\n // primitive's own guard so no caller can create one silently).\n const duplicate = db\n .query<{ id: string }, [string, string, string, string]>(\n `SELECT t.id FROM api_topics t\n JOIN topic_members m ON m.topic_id = t.id AND m.role = 'owner'\n WHERE t.kind = 'manager' AND t.surface = 'otium' AND t.surface_scope IS ?\n AND t.id != ? AND t.id != ?\n AND m.user_id IN (\n SELECT user_id FROM topic_members WHERE topic_id = ? AND role = 'owner'\n )\n LIMIT 1`,\n )\n .get(toScope, topicId, GENERAL_TOPIC_ID, topicId);\n if (duplicate) return refuse(\"duplicate_manager\", duplicate.id);\n } else {\n // Same rule as `findTopicTitleConflict`: manager rooms are not title\n // peers, except the reserved shared `general` row.\n const conflict = db\n .query<{ id: string }, [string, string, string, string]>(\n `SELECT id FROM api_topics\n WHERE LOWER(TRIM(title)) = LOWER(TRIM(?)) AND surface = 'otium' AND surface_scope IS ?\n AND id != ? AND (kind != 'manager' OR id = ?) LIMIT 1`,\n )\n .get(row.title, toScope, topicId, GENERAL_TOPIC_ID);\n if (conflict) return refuse(\"title_conflict\", conflict.id);\n }\n\n const claimsLeft = Number(\n db\n .query<{ n: number }, [string]>(\n `SELECT COUNT(*) AS n FROM api_topic_create_claims\n WHERE topic_id = ? AND state = 'committed'`,\n )\n .get(topicId)?.n ?? 0,\n );\n db.query(\"INSERT INTO api_topic_scope_repair_grants (topic_id) VALUES (?)\").run(topicId);\n const updated = db\n .query(\n `UPDATE api_topics SET surface_scope = ?\n WHERE id = ? AND surface = 'otium' AND surface_scope IS NULL`,\n )\n .run(toScope, topicId);\n db.query(\"DELETE FROM api_topic_scope_repair_grants WHERE topic_id = ?\").run(topicId);\n if (Number(updated.changes ?? 0) !== 1) throw new Error(\"scope repair CAS lost the row\");\n db.query(BUMP_TOMBSTONE_SEQ_SQL).run();\n db.query(\n `INSERT INTO api_topic_scope_moves\n (seq, topic_id, node_id, from_scope, to_scope, actor, reason, claims_left, moved_at)\n VALUES (${TOMBSTONE_SEQ_SQL}, ?, ${NODE_IDENTITY_SQL}, NULL, ?, ?, ?, ?, ?)`,\n ).run(topicId, toScope, input.actor, input.reason, claimsLeft, new Date().toISOString());\n const moveSeq = Number(\n db.query<{ seq: number }, []>(`SELECT ${TOMBSTONE_SEQ_SQL} AS seq`).get()?.seq ?? 0,\n );\n return { ok: true, topicId, fromScope: null, toScope, claimsLeft, moveSeq };\n}\n\n/**\n * The ONLY sanctioned way to change an otium topic's `surface_scope` after\n * creation — the `api_topics_otium_scope_immutable` trigger refuses every other\n * writer. One-shot, audited, one `BEGIN IMMEDIATE` (joins the caller's\n * transaction when there is one):\n *\n * - only `NULL → <non-empty scope>` on a `surface='otium'` row, compare-and-set\n * against `expectedRow`; any refusal changes nothing;\n * - create claims are NOT re-bound: they stay on their original principal, and\n * replay/abort re-verify that the topic's current scope still belongs to the\n * claim's principal (else `409 claim_topic_moved`). Re-binding would let the\n * new scope's principal delete a room another caller created, and that\n * caller's retry would then create a duplicate;\n * - the move is recorded in `api_topic_scope_moves` (history + audit) with a\n * seq from the tombstone counter, and appears in the tombstone feed as an\n * `unshared` entry for the OLD scope (`scopeMoved: true`);\n * - tombstones are not rewritten.\n *\n * No HTTP route: storage / admin CLI only.\n */\nexport function adminRepairOtiumTopicScope(\n input: AdminRepairOtiumTopicScopeInput,\n): AdminRepairOtiumTopicScopeResult {\n return db.transaction(() => repairOneTopicScope(input)).immediate();\n}\n\n/**\n * M-9 bulk variant: stamp every unscoped otium room with `toScope` through the\n * same per-topic repair (history recorded, claims untouched). Rooms that are\n * refused (busy, title conflict, duplicate manager) are skipped and reported — the caller decides\n * whether that leaves its migration incomplete (it must, revision 5).\n *\n * `topicIds` narrows the pass to those rooms (the M-9 retry of its pending\n * set); ids that are no longer unscoped otium rooms are simply not selected.\n */\nexport function repairUnscopedOtiumTopicScopes(\n toScope: string,\n actor: string,\n reason: string,\n options: { topicIds?: readonly string[] } = {},\n): { stamped: number; skipped: AdminRepairOtiumTopicScopeResult[] } {\n const skipped: AdminRepairOtiumTopicScopeResult[] = [];\n let stamped = 0;\n const all = db\n .query<RepairTopicRow, []>(\n `SELECT id, title, kind, surface, surface_scope, created_at FROM api_topics\n WHERE surface = 'otium' AND surface_scope IS NULL`,\n )\n .all();\n const only = options.topicIds ? new Set(options.topicIds) : null;\n const rows = only ? all.filter((row) => only.has(row.id)) : all;\n for (const row of rows) {\n const result = repairOneTopicScope({\n topicId: row.id,\n fromScope: null,\n toScope,\n expectedRow: { surface: \"otium\", surfaceScope: null, createdAt: row.created_at },\n actor,\n reason,\n });\n if (result.ok) stamped += 1;\n else skipped.push(result);\n }\n return { stamped, skipped };\n}\n",
|
|
35
35
|
"// Persistent topic store backed by shared SQLite.\n\nimport { resolveFallbackAgent } from \"#platform/config-helpers\";\nimport { GENERAL_TOPIC_ID } from \"#platform/constants\";\nimport { logger } from \"#platform/logger\";\nimport { db } from \"#storage/forum-db\";\nimport { onRuntimeTopicMaintenanceReleased } from \"#storage/runtime-topic-state\";\nimport { registerStorageSchemaInitializer } from \"#storage/storage-host\";\n// Also registers the claim/tombstone schema and the api_topics tombstone and\n// scope-immutability triggers wherever topics can be written (topic-link PR7).\nimport { repairUnscopedOtiumTopicScopes } from \"#storage/topic-link-records\";\nimport type { AgentKind, EffortLevel } from \"#types\";\nimport type {\n AiMode,\n ParticipantDto,\n SubagentReportMode,\n TopicDto,\n TopicKind,\n TopicSurface,\n TopicVisibility,\n} from \"#types/api\";\n\n/**\n * Surface used when a caller does not name one — and the value every existing\n * row is backfilled with on first boot after the surface migration.\n *\n * Hosts that only ever serve one surface declare it once in their environment\n * (`NEGOTIUM_DEFAULT_SURFACE=otium` on the Otium hub and worker); a developer\n * Mac leaves it unset and gets `terminal`, with the telegram adapter\n * reclassifying its own mapped rooms afterwards.\n */\nexport function defaultTopicSurface(): TopicSurface {\n return normalizeTopicSurface(process.env.NEGOTIUM_DEFAULT_SURFACE);\n}\n\nexport function normalizeTopicSurface(value: unknown): TopicSurface {\n return value === \"telegram\" || value === \"otium\" || value === \"terminal\" ? value : \"terminal\";\n}\n\n/**\n * The surface instance new rooms are filed under when the caller names none.\n *\n * `surface` alone is not enough once a node may be attached to several Otium\n * workspaces (M-2): two workspaces are two independent namespaces on the same\n * surface. The adapter that owns the attachment installs the active scope at\n * mount time; `terminal` and `telegram` are singletons and stay null.\n *\n * Kept as process state rather than an argument threaded through every creation\n * path because the value is a property of *this process's attachment*, not of\n * any individual call — the same reason `defaultTopicSurface()` exists.\n */\nlet activeSurfaceScope: string | null = null;\n\nexport function normalizeSurfaceScope(value: unknown): string | null {\n if (typeof value !== \"string\") return null;\n const trimmed = value.trim();\n return trimmed ? trimmed : null;\n}\n\nexport function defaultSurfaceScope(): string | null {\n return activeSurfaceScope ?? normalizeSurfaceScope(process.env.NEGOTIUM_SURFACE_SCOPE);\n}\n\n/** Install (or clear) the scope new rooms inherit. Returns the previous value. */\nexport function setDefaultSurfaceScope(scope: string | null): string | null {\n const previous = activeSurfaceScope;\n activeSurfaceScope = normalizeSurfaceScope(scope);\n return previous;\n}\n\n/**\n * Whether an Otium room must name a workspace to be created at all (M-3).\n *\n * Off by default, and off for every single-workspace host: an unscoped room is\n * then legacy, reachable, and perfectly usable. The adapter turns it on only\n * while several workspaces are attached, because there an unscoped room is\n * reachable from none of them (M-10) — a room nobody can see is worse than a\n * refusal that says so.\n */\nlet surfaceScopeRequired = false;\n\nexport function setSurfaceScopeRequired(required: boolean): void {\n surfaceScopeRequired = required;\n}\n\nexport function isSurfaceScopeRequired(): boolean {\n return surfaceScopeRequired;\n}\n\n/**\n * How many Otium workspaces the adapter currently has mounted, or null when no\n * adapter ever reported (a node without the Otium adapter). Lets a loopback\n * caller tell \"one workspace, scope not resolved yet\" apart from \"no\n * workspace at all\" (topic-link design v2 §4.6, `GET /surface-scope`).\n */\nlet mountedSurfaceScopeCount: number | null = null;\n\nexport function setMountedSurfaceScopeCount(count: number | null): void {\n mountedSurfaceScopeCount = count === null ? null : Math.max(0, Math.floor(count));\n}\n\nexport interface LocalSurfaceScopeStatus {\n /** The workspace an unscoped (loopback) caller's otium rooms are filed under. */\n surfaceScope: string | null;\n /** False while the scope cannot be stated (several workspaces, or one not resolved yet). */\n resolved: boolean;\n /** True while several workspaces are mounted: a room must name one. */\n scopeRequired: boolean;\n /** Mounted Otium workspaces; 0 when no adapter reported. */\n joinsMounted: number;\n}\n\n/** The scope a loopback (no scope header) gateway caller gets. */\nexport function localSurfaceScopeStatus(): LocalSurfaceScopeStatus {\n const joinsMounted = mountedSurfaceScopeCount ?? 0;\n if (surfaceScopeRequired) {\n return { surfaceScope: null, resolved: false, scopeRequired: true, joinsMounted };\n }\n const surfaceScope = defaultSurfaceScope();\n return {\n surfaceScope,\n resolved: joinsMounted === 1 ? surfaceScope !== null : true,\n scopeRequired: false,\n joinsMounted,\n };\n}\n\nfunction tableColumns(table: string): Set<string> {\n const rows = db.query(`PRAGMA table_info(${table})`).all() as Array<{ name: string }>;\n return new Set(rows.map((row) => row.name));\n}\n\n/** Persist the authoritative agent and, when supplied, its normalized base defaults. */\nexport function setApiTopicAgent(\n topicId: string,\n agent: AgentKind,\n defaults?: { model: string; effort?: EffortLevel },\n): void {\n if (!defaults) {\n db.query(\"UPDATE api_topics SET agent = ? WHERE id = ?\").run(agent, topicId);\n return;\n }\n db.query(\"UPDATE api_topics SET agent = ?, base_model = ?, base_effort = ? WHERE id = ?\").run(\n agent,\n defaults.model,\n defaults.effort ?? null,\n topicId,\n );\n}\n\nfunction initializeApiTopicsSchema(): void {\n db.exec(`\n CREATE TABLE IF NOT EXISTS api_topics (\n id TEXT PRIMARY KEY,\n title TEXT NOT NULL,\n kind TEXT NOT NULL DEFAULT 'channel',\n description TEXT,\n agent TEXT,\n default_model TEXT,\n default_effort TEXT,\n participants TEXT,\n created_at TEXT NOT NULL,\n last_message_at TEXT,\n is_archived INTEGER NOT NULL DEFAULT 0,\n ai_mention INTEGER NOT NULL DEFAULT 0,\n ai_mode TEXT\n )\n`);\n\n const initialTopicColumns = tableColumns(\"api_topics\");\n const legacyTopicSchema = !initialTopicColumns.has(\"response_policy\");\n const needsCanonicalTopicRebuild = legacyTopicSchema || !initialTopicColumns.has(\"agent\");\n if (legacyTopicSchema) {\n // Rename the legacy column once; new databases are created with `agent`.\n try {\n db.exec(\"ALTER TABLE api_topics RENAME COLUMN default_agent TO agent\");\n } catch {\n // Already migrated or freshly created.\n }\n\n // Migrate existing DBs that predate the ai_mention column (team-mode topics).\n try {\n db.exec(\"ALTER TABLE api_topics ADD COLUMN ai_mention INTEGER NOT NULL DEFAULT 0\");\n } catch {\n // Column already exists — nothing to do.\n }\n\n // Migrate for spawn/fork tracking (R1).\n try {\n db.exec(\"ALTER TABLE api_topics ADD COLUMN parent_topic_id TEXT\");\n } catch {}\n try {\n db.exec(\"ALTER TABLE api_topics ADD COLUMN is_fork INTEGER NOT NULL DEFAULT 0\");\n } catch {}\n\n // Migrate for agent-spawned subagent worker rooms.\n try {\n db.exec(\"ALTER TABLE api_topics ADD COLUMN is_subagent INTEGER NOT NULL DEFAULT 0\");\n } catch {}\n\n // Migrate for session persistence.\n try {\n db.exec(\"ALTER TABLE api_topics ADD COLUMN session_id TEXT\");\n } catch {}\n\n try {\n db.exec(\"ALTER TABLE api_topics ADD COLUMN kind TEXT NOT NULL DEFAULT 'channel'\");\n } catch {}\n\n try {\n db.exec(\"ALTER TABLE api_topics ADD COLUMN ai_mode TEXT\");\n } catch {}\n\n db.exec(`\n CREATE TABLE IF NOT EXISTS api_schema_migrations (\n key TEXT PRIMARY KEY,\n applied_at TEXT NOT NULL\n )\n`);\n\n const ALWAYS_RESPOND_MIGRATION = \"api_topics_ai_invited_default_always_respond_20260623\";\n const alwaysRespondMigration = db\n .query(\"SELECT key FROM api_schema_migrations WHERE key = ?\")\n .get(ALWAYS_RESPOND_MIGRATION);\n if (!alwaysRespondMigration) {\n db.transaction(() => {\n db.query(\"UPDATE api_topics SET ai_mention = 0 WHERE agent IS NOT NULL\").run();\n db.query(\"INSERT INTO api_schema_migrations (key, applied_at) VALUES (?, ?)\").run(\n ALWAYS_RESPOND_MIGRATION,\n new Date().toISOString(),\n );\n })();\n }\n\n const GENERAL_AGENT_KIND_MIGRATION = \"api_topics_general_agent_kind_20260704\";\n const generalAgentKindMigration = db\n .query(\"SELECT key FROM api_schema_migrations WHERE key = ?\")\n .get(GENERAL_AGENT_KIND_MIGRATION);\n if (!generalAgentKindMigration) {\n db.transaction(() => {\n db.query(\"UPDATE api_topics SET kind = 'agent', ai_mention = 0 WHERE id = ?\").run(\n GENERAL_TOPIC_ID,\n );\n db.query(\"INSERT INTO api_schema_migrations (key, applied_at) VALUES (?, ?)\").run(\n GENERAL_AGENT_KIND_MIGRATION,\n new Date().toISOString(),\n );\n })();\n }\n\n const AI_MODE_MIGRATION = \"api_topics_ai_mode_20260704\";\n const aiModeMigration = db\n .query(\"SELECT key FROM api_schema_migrations WHERE key = ?\")\n .get(AI_MODE_MIGRATION);\n if (!aiModeMigration) {\n db.transaction(() => {\n db.query(\n `UPDATE api_topics\n SET\n kind = CASE\n WHEN id = ? THEN 'agent'\n WHEN kind = 'channel' AND agent IS NOT NULL AND ai_mention = 0 THEN 'agent'\n ELSE kind\n END,\n ai_mode = CASE\n WHEN id = ? THEN 'always'\n WHEN agent IS NULL THEN 'off'\n WHEN kind = 'agent' THEN 'always'\n WHEN kind = 'channel' AND ai_mention != 0 THEN 'mention'\n WHEN kind = 'channel' AND ai_mention = 0 THEN 'always'\n WHEN ai_mention != 0 THEN 'mention'\n ELSE 'always'\n END`,\n ).run(GENERAL_TOPIC_ID, GENERAL_TOPIC_ID);\n db.query(\"INSERT INTO api_schema_migrations (key, applied_at) VALUES (?, ?)\").run(\n AI_MODE_MIGRATION,\n new Date().toISOString(),\n );\n })();\n }\n\n const GENERAL_MANAGER_KIND_MIGRATION = \"api_topics_general_manager_kind_20260704\";\n const generalManagerKindMigration = db\n .query(\"SELECT key FROM api_schema_migrations WHERE key = ?\")\n .get(GENERAL_MANAGER_KIND_MIGRATION);\n if (!generalManagerKindMigration) {\n db.transaction(() => {\n db.query(\n \"UPDATE api_topics SET kind = 'manager', ai_mention = 0, ai_mode = 'always' WHERE id = ?\",\n ).run(GENERAL_TOPIC_ID);\n db.query(\"INSERT INTO api_schema_migrations (key, applied_at) VALUES (?, ?)\").run(\n GENERAL_MANAGER_KIND_MIGRATION,\n new Date().toISOString(),\n );\n })();\n }\n }\n\n function createCanonicalTopicsTable(name: string): void {\n db.exec(`\n CREATE TABLE IF NOT EXISTS ${name} (\n id TEXT PRIMARY KEY,\n title TEXT NOT NULL,\n kind TEXT NOT NULL CHECK (kind IN ('channel','agent','manager')),\n description TEXT,\n agent TEXT CHECK (agent IS NULL OR agent IN ('maestro','claude','codex')),\n base_model TEXT,\n base_effort TEXT CHECK (base_effort IS NULL OR base_effort IN ('low','medium','high','xhigh','max')),\n response_policy TEXT NOT NULL CHECK (response_policy IN ('off','mention','always')),\n created_at TEXT NOT NULL,\n last_message_at TEXT,\n parent_topic_id TEXT,\n memory_topic_id TEXT,\n memory_key TEXT,\n is_fork INTEGER NOT NULL DEFAULT 0 CHECK (is_fork IN (0,1)),\n is_subagent INTEGER NOT NULL DEFAULT 0 CHECK (is_subagent IN (0,1)),\n visibility TEXT NOT NULL DEFAULT 'visible' CHECK (visibility IN ('visible','hidden')),\n surface TEXT NOT NULL DEFAULT 'terminal' CHECK (surface IN ('terminal','telegram','otium')),\n surface_scope TEXT,\n browser_profile TEXT NOT NULL DEFAULT 'default',\n browser_profile_owner TEXT,\n browser_connect_port INTEGER,\n session_id TEXT,\n CHECK (\n (kind = 'channel' AND response_policy = 'off' AND agent IS NULL) OR\n (kind = 'channel' AND response_policy = 'mention' AND agent IS NOT NULL) OR\n (kind IN ('agent','manager') AND response_policy = 'always' AND agent IS NOT NULL)\n )\n )\n `);\n }\n\n function createTopicMembersTable(): void {\n db.exec(`\n CREATE TABLE IF NOT EXISTS topic_members (\n topic_id TEXT NOT NULL REFERENCES api_topics(id) ON DELETE CASCADE,\n user_id TEXT NOT NULL,\n role TEXT NOT NULL CHECK (role IN ('owner','member')),\n PRIMARY KEY (topic_id, user_id)\n )\n `);\n db.exec(\"CREATE INDEX IF NOT EXISTS idx_topic_members_user ON topic_members(user_id)\");\n }\n\n if (needsCanonicalTopicRebuild) {\n const legacyRows = db.query(\"SELECT * FROM api_topics\").all() as Array<Record<string, unknown>>;\n const existingMemberRows = tableColumns(\"topic_members\").has(\"topic_id\")\n ? (db.query(\"SELECT topic_id, user_id, role FROM topic_members\").all() as Array<{\n topic_id: string;\n user_id: string;\n role: string;\n }>)\n : [];\n const configColumns = tableColumns(\"api_topic_config\");\n const legacyAgentOverrides = configColumns.has(\"agent\")\n ? new Map(\n (\n db\n .query(\"SELECT topic_id, agent FROM api_topic_config WHERE agent IS NOT NULL\")\n .all() as Array<{ topic_id: string; agent: AgentKind }>\n ).map((row) => [row.topic_id, row.agent]),\n )\n : new Map<string, AgentKind>();\n const previousForeignKeys = db\n .query<{ foreign_keys: number }, []>(\"PRAGMA foreign_keys\")\n .get()?.foreign_keys;\n db.exec(\"PRAGMA foreign_keys = OFF\");\n try {\n db.transaction(() => {\n createCanonicalTopicsTable(\"api_topics_next\");\n for (const row of legacyRows) {\n const selectedAgent = (legacyAgentOverrides.get(String(row.id)) ??\n row.agent ??\n row.runtime_agent ??\n row.default_agent ??\n undefined) as AgentKind | undefined;\n const normalized = normalizeTopicState({\n id: String(row.id),\n kind: normalizeTopicKind(row.kind),\n agent: selectedAgent,\n aiMode: normalizeAiMode(row.response_policy ?? row.ai_mode),\n aiMention: Number(row.ai_mention ?? 0) !== 0,\n });\n const legacyBaseModel = row.base_model ?? row.default_model;\n const legacyBaseEffort = row.base_effort ?? row.default_effort;\n db.query(\n `INSERT INTO api_topics_next\n (id,title,kind,description,agent,base_model,base_effort,response_policy,\n created_at,last_message_at,parent_topic_id,memory_topic_id,memory_key,is_fork,is_subagent,visibility,surface,surface_scope,session_id)\n VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,\n ).run(\n String(row.id),\n String(row.title),\n normalized.kind,\n typeof row.description === \"string\" ? row.description : null,\n normalized.agent ?? null,\n typeof legacyBaseModel === \"string\" ? legacyBaseModel : null,\n typeof legacyBaseEffort === \"string\" ? legacyBaseEffort : null,\n normalized.aiMode,\n String(row.created_at),\n typeof row.last_message_at === \"string\" ? row.last_message_at : null,\n typeof row.parent_topic_id === \"string\" ? row.parent_topic_id : null,\n typeof row.memory_topic_id === \"string\" ? row.memory_topic_id : null,\n typeof row.memory_key === \"string\" ? row.memory_key : null,\n Number(row.is_fork ?? 0) !== 0 ? 1 : 0,\n Number(row.is_subagent ?? 0) !== 0 ? 1 : 0,\n row.visibility === \"hidden\" ? \"hidden\" : \"visible\",\n row.surface === undefined ? defaultTopicSurface() : normalizeTopicSurface(row.surface),\n normalizeSurfaceScope(row.surface_scope),\n typeof row.session_id === \"string\" ? row.session_id : null,\n );\n }\n db.exec(\"DROP TABLE IF EXISTS topic_members\");\n db.exec(\"DROP TABLE api_topics\");\n db.exec(\"ALTER TABLE api_topics_next RENAME TO api_topics\");\n createTopicMembersTable();\n if (existingMemberRows.length > 0) {\n for (const member of existingMemberRows) {\n db.query(\n \"INSERT OR REPLACE INTO topic_members (topic_id,user_id,role) VALUES (?,?,?)\",\n ).run(member.topic_id, member.user_id, member.role === \"owner\" ? \"owner\" : \"member\");\n }\n } else {\n for (const row of legacyRows) {\n let participants: ParticipantDto[] = [];\n try {\n const parsed = JSON.parse(String(row.participants ?? \"[]\"));\n if (Array.isArray(parsed)) participants = parsed as ParticipantDto[];\n } catch {\n participants = [];\n }\n for (const participant of participants) {\n if (!participant?.userId) continue;\n db.query(\n \"INSERT OR REPLACE INTO topic_members (topic_id,user_id,role) VALUES (?,?,?)\",\n ).run(\n String(row.id),\n participant.userId,\n participant.role === \"owner\" ? \"owner\" : \"member\",\n );\n }\n }\n }\n })();\n } finally {\n db.exec(`PRAGMA foreign_keys = ${previousForeignKeys ? \"ON\" : \"OFF\"}`);\n }\n } else {\n createCanonicalTopicsTable(\"api_topics\");\n createTopicMembersTable();\n }\n\n db.exec(`\n CREATE TABLE IF NOT EXISTS subagent_tell_grants (\n subagent_topic_id TEXT NOT NULL REFERENCES api_topics(id) ON DELETE CASCADE,\n target_topic_id TEXT NOT NULL REFERENCES api_topics(id) ON DELETE CASCADE,\n granted_by_topic_id TEXT NOT NULL REFERENCES api_topics(id) ON DELETE CASCADE,\n created_at TEXT NOT NULL,\n PRIMARY KEY (subagent_topic_id, target_topic_id)\n )\n `);\n db.exec(`\n DELETE FROM subagent_tell_grants\n WHERE subagent_topic_id NOT IN (SELECT id FROM api_topics)\n OR target_topic_id NOT IN (SELECT id FROM api_topics)\n OR granted_by_topic_id NOT IN (SELECT id FROM api_topics)\n `);\n db.exec(\"DELETE FROM topic_members WHERE topic_id NOT IN (SELECT id FROM api_topics)\");\n\n // Canonical databases created before explicit adapter visibility need a\n // lightweight additive migration; fresh/rebuilt databases already have it.\n if (!tableColumns(\"api_topics\").has(\"visibility\")) {\n db.exec(\"ALTER TABLE api_topics ADD COLUMN visibility TEXT NOT NULL DEFAULT 'visible'\");\n }\n if (!tableColumns(\"api_topics\").has(\"surface\")) {\n db.exec(\"ALTER TABLE api_topics ADD COLUMN surface TEXT NOT NULL DEFAULT 'terminal'\");\n }\n if (!tableColumns(\"api_topics\").has(\"surface_scope\")) {\n db.exec(\"ALTER TABLE api_topics ADD COLUMN surface_scope TEXT\");\n }\n // `access_mode` was replaced by `surface`: a topic is reachable from Otium\n // because it lives there, not because a flag was flipped (S-4). Dropping the\n // column removes the second, now-contradictory source of truth.\n if (tableColumns(\"api_topics\").has(\"access_mode\")) {\n try {\n db.exec(\"ALTER TABLE api_topics DROP COLUMN access_mode\");\n } catch (err) {\n logger.warn({ err }, \"api_topics: could not drop the retired access_mode column\");\n }\n }\n if (!tableColumns(\"api_topics\").has(\"browser_profile\")) {\n db.exec(\"ALTER TABLE api_topics ADD COLUMN browser_profile TEXT NOT NULL DEFAULT 'default'\");\n }\n if (!tableColumns(\"api_topics\").has(\"browser_profile_owner\")) {\n db.exec(\"ALTER TABLE api_topics ADD COLUMN browser_profile_owner TEXT\");\n }\n if (!tableColumns(\"api_topics\").has(\"browser_connect_port\")) {\n db.exec(\"ALTER TABLE api_topics ADD COLUMN browser_connect_port INTEGER\");\n }\n if (!tableColumns(\"api_topics\").has(\"subagent_report_mode\")) {\n db.exec(\"ALTER TABLE api_topics ADD COLUMN subagent_report_mode TEXT NOT NULL DEFAULT 'auto'\");\n }\n if (!tableColumns(\"api_topics\").has(\"derived_by_user_id\")) {\n db.exec(\"ALTER TABLE api_topics ADD COLUMN derived_by_user_id TEXT\");\n }\n if (!tableColumns(\"api_topics\").has(\"memory_topic_id\")) {\n db.exec(\"ALTER TABLE api_topics ADD COLUMN memory_topic_id TEXT\");\n }\n if (!tableColumns(\"api_topics\").has(\"memory_key\")) {\n db.exec(\"ALTER TABLE api_topics ADD COLUMN memory_key TEXT\");\n }\n db.exec(`\n UPDATE api_topics\n SET browser_profile_owner = (\n SELECT m.user_id FROM topic_members m\n WHERE m.topic_id = api_topics.id AND m.role = 'owner'\n ORDER BY m.rowid\n LIMIT 1\n )\n WHERE browser_profile_owner IS NULL\n`);\n backfillTopicSurfaces();\n ensureSurfaceScopeStampTables();\n db.exec(\n \"CREATE INDEX IF NOT EXISTS idx_api_topics_last_message ON api_topics(last_message_at DESC)\",\n );\n db.exec(\"CREATE INDEX IF NOT EXISTS idx_api_topics_surface ON api_topics(surface)\");\n db.exec(\n \"CREATE INDEX IF NOT EXISTS idx_api_topics_surface_scope ON api_topics(surface, surface_scope)\",\n );\n}\n\nconst SURFACE_SCOPE_STAMP_MIGRATION = \"api_topics_surface_scope_stamp_20260809\";\n\n/**\n * Minimum spacing between two unforced retries of an incomplete M-9 stamp.\n * The retry is driven by timers / scope refreshes, never by request traffic,\n * and this bound keeps even a tight caller from turning it into a hot path.\n */\nexport const SURFACE_SCOPE_STAMP_RETRY_INTERVAL_MS = 30_000;\n\n/**\n * Refusals that leave a room pending: the room is still an unscoped otium room\n * and the stamp may succeed later (maintenance ends, an operator renames the\n * conflicting room or resolves a duplicate manager room, the row settles).\n * Every other refusal (`not_found`, `not_otium`, `scope_not_null`) means there\n * is nothing left to stamp.\n */\nconst SURFACE_SCOPE_STAMP_RETRYABLE = new Set([\n \"maintenance_in_progress\",\n \"title_conflict\",\n \"duplicate_manager\",\n \"row_changed\",\n \"invalid_scope\",\n]);\n\nfunction ensureSurfaceScopeStampTables(): void {\n db.exec(`\n CREATE TABLE IF NOT EXISTS api_schema_migrations (\n key TEXT PRIMARY KEY,\n applied_at TEXT NOT NULL\n )\n`);\n // Rooms the M-9 stamp could not file yet (revision 5). `scope` is pinned at\n // the first attempt: a retry never re-reads the current workspace, so a\n // second workspace joined later cannot swallow the first one's rooms.\n db.exec(`\n CREATE TABLE IF NOT EXISTS api_surface_scope_stamp_pending (\n topic_id TEXT PRIMARY KEY,\n scope TEXT NOT NULL,\n reason TEXT NOT NULL,\n detail TEXT,\n attempts INTEGER NOT NULL DEFAULT 1,\n first_seen_at TEXT NOT NULL,\n last_attempt_at TEXT NOT NULL\n )\n`);\n}\n\nexport interface SurfaceScopeStampStatus {\n /** The completion marker is written: every pre-existing room was filed. */\n complete: boolean;\n /** Rooms the stamp skipped and will retry (maintenance, title conflict ...). */\n pending: number;\n /** Workspace the pending rooms will be filed under (pinned at first attempt). */\n scope: string | null;\n pendingTopics: Array<{\n topicId: string;\n reason: string;\n detail: string | null;\n attempts: number;\n }>;\n}\n\n/**\n * Operator view of the M-9 stamp (diagnostics; `unscopedPending` on\n * `GET /surface-scope`). Read-only: the tables exist from schema init.\n */\nexport function surfaceScopeStampStatus(): SurfaceScopeStampStatus {\n const complete = Boolean(\n db\n .query(\"SELECT key FROM api_schema_migrations WHERE key = ?\")\n .get(SURFACE_SCOPE_STAMP_MIGRATION),\n );\n const rows = db\n .query<\n { topic_id: string; scope: string; reason: string; detail: string | null; attempts: number },\n []\n >(\n \"SELECT topic_id, scope, reason, detail, attempts FROM api_surface_scope_stamp_pending ORDER BY topic_id\",\n )\n .all();\n return {\n complete,\n pending: rows.length,\n scope: rows[0]?.scope ?? null,\n pendingTopics: rows.map((row) => ({\n topicId: row.topic_id,\n reason: row.reason,\n detail: row.detail,\n attempts: Number(row.attempts),\n })),\n };\n}\n\n/**\n * M-9 — file every pre-existing Otium room under the workspace attached now.\n *\n * Deliberately *not* a schema-init step. The scope is only knowable after the\n * first successful Central contact (M-3), which happens long after the store\n * opens; a boot-time migration would see no scope, record itself as applied and\n * leave every room unstamped forever. The Otium runtime calls this instead, once,\n * as soon as it has resolved its workspace.\n *\n * Completes at most once per store: rooms created after this point are stamped\n * at creation, and a second workspace joined later must not swallow the first\n * one's rooms. Unlike the surface migration this can never rename anything —\n * the scope enters the uniqueness key in the same release, so nothing can start\n * colliding because of it.\n *\n * Revision 5: the completion marker is written only when NO room was skipped.\n * A room refused for a retryable reason (live maintenance, title conflict) is\n * recorded in `api_surface_scope_stamp_pending` with the first attempt's scope,\n * and later calls retry exactly those rooms under that pinned scope — never a\n * fresh sweep, never the caller's (possibly different) scope. Rooms already\n * stamped are no longer unscoped and drop out, so every pass is idempotent. The\n * whole pass is one `BEGIN IMMEDIATE`, so concurrent boots serialize: the\n * second sees the first one's marker or pending set and re-checks it.\n */\nexport function stampUnscopedOtiumTopics(scope: string): number {\n const normalized = normalizeSurfaceScope(scope);\n if (!normalized) return 0;\n ensureSurfaceScopeStampTables();\n // Cheap unlocked pre-check: a completed store never takes the write lock.\n if (\n db\n .query(\"SELECT key FROM api_schema_migrations WHERE key = ?\")\n .get(SURFACE_SCOPE_STAMP_MIGRATION)\n ) {\n return 0;\n }\n\n let stamped = 0;\n const stillPending: Array<{ topicId: string; reason: string; detail?: string }> = [];\n let effectiveScope = normalized;\n let ran = false;\n db.transaction(() => {\n // Re-check under the write lock: a concurrent boot may have finished.\n if (\n db\n .query(\"SELECT key FROM api_schema_migrations WHERE key = ?\")\n .get(SURFACE_SCOPE_STAMP_MIGRATION)\n ) {\n return;\n }\n ran = true;\n const pendingRows = db\n .query<{ topic_id: string; scope: string }, []>(\n \"SELECT topic_id, scope FROM api_surface_scope_stamp_pending ORDER BY topic_id\",\n )\n .all();\n const retry = pendingRows.length > 0;\n if (retry) effectiveScope = pendingRows[0]?.scope ?? normalized;\n // Through the audited scope repair: an otium room's scope is otherwise\n // immutable (topic-link review fix 6); the move is recorded and create\n // claims stay on their original principal.\n const result = repairUnscopedOtiumTopicScopes(\n effectiveScope,\n \"m9-stamp\",\n \"file pre-existing Otium rooms under the resolved workspace\",\n retry ? { topicIds: pendingRows.map((row) => row.topic_id) } : {},\n );\n stamped = result.stamped;\n for (const skip of result.skipped) {\n if (skip.ok || !SURFACE_SCOPE_STAMP_RETRYABLE.has(skip.reason)) continue;\n stillPending.push({ topicId: skip.topicId, reason: skip.reason, detail: skip.detail });\n }\n const now = new Date().toISOString();\n const keep = new Set(stillPending.map((row) => row.topicId));\n for (const row of pendingRows) {\n if (!keep.has(row.topic_id)) {\n db.query(\"DELETE FROM api_surface_scope_stamp_pending WHERE topic_id = ?\").run(\n row.topic_id,\n );\n }\n }\n for (const row of stillPending) {\n db.query(\n `INSERT INTO api_surface_scope_stamp_pending\n (topic_id, scope, reason, detail, attempts, first_seen_at, last_attempt_at)\n VALUES (?, ?, ?, ?, 1, ?, ?)\n ON CONFLICT(topic_id) DO UPDATE SET\n reason = excluded.reason,\n detail = excluded.detail,\n attempts = api_surface_scope_stamp_pending.attempts + 1,\n last_attempt_at = excluded.last_attempt_at`,\n ).run(row.topicId, effectiveScope, row.reason, row.detail ?? null, now, now);\n }\n if (stillPending.length === 0) {\n db.query(\"INSERT INTO api_schema_migrations (key, applied_at) VALUES (?, ?)\").run(\n SURFACE_SCOPE_STAMP_MIGRATION,\n now,\n );\n }\n }).immediate();\n if (!ran) return 0;\n if (effectiveScope !== normalized) {\n logger.info(\n { scope: normalized, pinnedScope: effectiveScope },\n \"api_topics: surface scope stamp retry keeps the workspace of its first attempt\",\n );\n }\n if (stamped > 0) {\n logger.info({ scope: effectiveScope, stamped }, \"api_topics: surface scope stamped\");\n }\n if (stillPending.length > 0) {\n // Operator-visible every attempt: a permanent title conflict never\n // completes the migration and needs a rename (or admin repair).\n logger.warn(\n {\n scope: effectiveScope,\n pending: stillPending.length,\n topicIds: stillPending.map((row) => row.topicId),\n skipped: stillPending,\n },\n \"api_topics: surface scope stamp incomplete; rooms stay pending and will be retried\",\n );\n } else {\n logger.info({ scope: effectiveScope }, \"api_topics: surface scope stamp complete\");\n }\n return stamped;\n}\n\nlet lastSurfaceScopeStampRetryAt = 0;\n\n/**\n * Retry an incomplete M-9 stamp under its pinned scope. No-op (no write lock)\n * when the stamp never started or already completed. Unforced calls run at most\n * once per {@link SURFACE_SCOPE_STAMP_RETRY_INTERVAL_MS} per process; `force`\n * is for discrete events (a pending room's maintenance released, a scope\n * refresh). Never throws: a busy database just waits for the next trigger.\n */\nexport function retryPendingSurfaceScopeStamp(\n options: { force?: boolean; now?: number } = {},\n): number {\n const now = options.now ?? Date.now();\n if (\n !options.force &&\n now - lastSurfaceScopeStampRetryAt < SURFACE_SCOPE_STAMP_RETRY_INTERVAL_MS\n ) {\n return 0;\n }\n lastSurfaceScopeStampRetryAt = now;\n try {\n ensureSurfaceScopeStampTables();\n const pinned = db\n .query<{ scope: string }, []>(\"SELECT scope FROM api_surface_scope_stamp_pending LIMIT 1\")\n .get();\n if (!pinned) return 0;\n return stampUnscopedOtiumTopics(pinned.scope);\n } catch (err) {\n logger.warn({ err }, \"api_topics: surface scope stamp retry failed (will retry)\");\n return 0;\n }\n}\n\n/** Whether `topicId` is waiting for the M-9 stamp (cheap point lookup). */\nexport function isSurfaceScopeStampPending(topicId: string): boolean {\n return Boolean(\n db.query(\"SELECT 1 FROM api_surface_scope_stamp_pending WHERE topic_id = ?\").get(topicId),\n );\n}\n\n// A pending room's maintenance fence was released: retry now instead of\n// waiting for the next timer tick. Deferred so the stamp never runs inside the\n// releasing caller's transaction.\nonRuntimeTopicMaintenanceReleased((topicId) => {\n const timer = setTimeout(() => {\n try {\n if (isSurfaceScopeStampPending(topicId)) retryPendingSurfaceScopeStamp({ force: true });\n } catch (err) {\n logger.warn({ err, topicId }, \"api_topics: surface scope stamp retry on release failed\");\n }\n }, 0);\n timer.unref?.();\n});\n\nconst SURFACE_BACKFILL_MIGRATION = \"api_topics_surface_backfill_20260808\";\n\n/**\n * One-time classification of pre-surface topics.\n *\n * Every row predates the column, so there is no per-row evidence in this store\n * to distinguish surfaces — the host declares it (`NEGOTIUM_DEFAULT_SURFACE`).\n * The telegram adapter owns the second pass: its chat↔topic mapping lives in a\n * different database file, so only it can reclassify the rooms it created.\n *\n * Names are unique per surface from now on, so collapsing three namespaces into\n * one can produce duplicates. Rather than failing the boot, the oldest room\n * keeps the name and the rest are suffixed — a rename is recoverable, a node\n * that refuses to start is not.\n */\nfunction backfillTopicSurfaces(): void {\n db.exec(`\n CREATE TABLE IF NOT EXISTS api_schema_migrations (\n key TEXT PRIMARY KEY,\n applied_at TEXT NOT NULL\n )\n`);\n const applied = db\n .query(\"SELECT key FROM api_schema_migrations WHERE key = ?\")\n .get(SURFACE_BACKFILL_MIGRATION);\n if (applied) return;\n\n const surface = defaultTopicSurface();\n db.transaction(() => {\n db.query(\"UPDATE api_topics SET surface = ?\").run(surface);\n renameSurfaceTitleCollisions();\n db.query(\"INSERT INTO api_schema_migrations (key, applied_at) VALUES (?, ?)\").run(\n SURFACE_BACKFILL_MIGRATION,\n new Date().toISOString(),\n );\n })();\n logger.info({ surface }, \"api_topics: surface backfilled\");\n}\n\n/**\n * Suffix duplicate `(surface, kind, title)` rows so the new uniqueness rule holds.\n *\n * Manager rooms are excluded: they are one per user, so on a multi-user host\n * every member has a personal room with the same title and none of them is a\n * duplicate. Renaming those relabels real rooms belonging to other people.\n */\nfunction renameSurfaceTitleCollisions(): void {\n const rows = db\n .query<{ id: string; title: string; kind: string; surface: string }, []>(\n \"SELECT id, title, kind, surface FROM api_topics WHERE kind != 'manager' ORDER BY created_at ASC, rowid ASC\",\n )\n .all();\n const keyOf = (surface: string, kind: string, title: string) =>\n [surface, kind, normalizedTitle(title)].join(\"\\u0000\");\n // Every original title is reserved up front. Allocating only against the\n // titles seen so far would let an earlier duplicate claim \"Foo (2)\" while a\n // real room already named \"Foo (2)\" sits later in the scan — that room would\n // then be pushed to \"Foo (2) (2)\" for no reason.\n const reserved = new Set(rows.map((row) => keyOf(row.surface, row.kind, row.title)));\n const used = new Set<string>();\n const update = db.query(\"UPDATE api_topics SET title = ? WHERE id = ?\");\n for (const row of rows) {\n const key = (title: string) => keyOf(row.surface, row.kind, title);\n if (!used.has(key(row.title))) {\n used.add(key(row.title));\n continue;\n }\n let suffix = 2;\n let candidate = `${row.title} (${suffix})`;\n while (reserved.has(key(candidate)) || used.has(key(candidate))) {\n suffix += 1;\n candidate = `${row.title} (${suffix})`;\n }\n used.add(key(candidate));\n update.run(candidate, row.id);\n logger.warn(\n { topicId: row.id, surface: row.surface, from: row.title, to: candidate },\n \"api_topics: renamed a duplicate title for surface-scoped uniqueness\",\n );\n }\n}\n\nregisterStorageSchemaInitializer(initializeApiTopicsSchema, 20);\n\nexport interface TopicRow {\n id: string;\n title: string;\n kind: string | null;\n description: string | null;\n agent: string | null;\n base_model: string | null;\n base_effort: string | null;\n response_policy: string;\n created_at: string;\n last_message_at: string | null;\n parent_topic_id: string | null;\n memory_topic_id: string | null;\n memory_key: string | null;\n is_fork: number;\n is_subagent: number;\n subagent_report_mode: string | null;\n derived_by_user_id: string | null;\n visibility: string | null;\n surface: string | null;\n surface_scope: string | null;\n browser_profile_owner: string | null;\n browser_connect_port: number | null;\n session_id: string | null;\n}\n\nexport interface TopicSessionLogContext {\n reason?: string;\n queryId?: string;\n agent?: AgentKind;\n}\n\nfunction shortSessionId(sessionId: string | null | undefined): string | null {\n return sessionId ? sessionId.slice(0, 8) : null;\n}\n\nfunction getTopicParticipants(topicId: string): ParticipantDto[] {\n return db\n .query<{ user_id: string; role: \"owner\" | \"member\" }, string>(\n \"SELECT user_id, role FROM topic_members WHERE topic_id = ? ORDER BY rowid\",\n )\n .all(topicId)\n .map((row) => ({ userId: row.user_id, role: row.role }));\n}\n\nfunction getAllTopicParticipants(): Map<string, ParticipantDto[]> {\n const grouped = new Map<string, ParticipantDto[]>();\n const rows = db\n .query<{ topic_id: string; user_id: string; role: \"owner\" | \"member\" }, []>(\n \"SELECT topic_id, user_id, role FROM topic_members ORDER BY rowid\",\n )\n .all();\n for (const row of rows) {\n const participants = grouped.get(row.topic_id) ?? [];\n participants.push({ userId: row.user_id, role: row.role });\n grouped.set(row.topic_id, participants);\n }\n return grouped;\n}\n\nfunction getAllSubagentTellTargets(): Map<string, string[]> {\n const rows = db\n .query(\n \"SELECT subagent_topic_id, target_topic_id FROM subagent_tell_grants ORDER BY created_at\",\n )\n .all() as Array<{ subagent_topic_id: string; target_topic_id: string }>;\n const grouped = new Map<string, string[]>();\n for (const row of rows) {\n const targets = grouped.get(row.subagent_topic_id) ?? [];\n targets.push(row.target_topic_id);\n grouped.set(row.subagent_topic_id, targets);\n }\n return grouped;\n}\n\nfunction rowToDto(\n r: TopicRow,\n participants = getTopicParticipants(r.id),\n tellTargets?: Map<string, string[]>,\n): TopicDto {\n const normalized = normalizeTopicState({\n id: r.id,\n kind: normalizeTopicKind(r.kind),\n agent: (r.agent as AgentKind | null) ?? undefined,\n aiMode: normalizeAiMode(r.response_policy),\n });\n return {\n id: r.id,\n title: r.title,\n kind: normalized.kind,\n description: r.description ?? undefined,\n agent: normalized.agent,\n defaultModel: r.base_model ?? \"deepseek-pro\",\n defaultEffort: (r.base_effort as EffortLevel) ?? undefined,\n aiMode: normalized.aiMode,\n aiMention: aiMentionFromMode(normalized.aiMode),\n participants,\n createdAt: r.created_at,\n lastMessageAt: r.last_message_at ?? new Date().toISOString(),\n parentTopicId: r.parent_topic_id ?? undefined,\n memoryTopicId: r.memory_topic_id ?? undefined,\n memoryKey: r.memory_key ?? undefined,\n isFork: r.is_fork !== 0,\n ...(r.derived_by_user_id ? { derivedByUserId: r.derived_by_user_id } : {}),\n ...(r.is_subagent !== 0 ? { isSubagent: true } : {}),\n ...(r.is_subagent !== 0\n ? {\n subagentTellTargetIds: tellTargets\n ? (tellTargets.get(r.id) ?? [])\n : listSubagentTellTargetIds(r.id),\n }\n : {}),\n ...(r.is_subagent !== 0\n ? {\n subagentReportMode: (r.subagent_report_mode === \"tell\" ||\n r.subagent_report_mode === \"status-only\"\n ? r.subagent_report_mode\n : \"auto\") as SubagentReportMode,\n }\n : {}),\n visibility: normalizeTopicVisibility(r.visibility),\n surface: normalizeTopicSurface(r.surface),\n surfaceScope: normalizeSurfaceScope(r.surface_scope),\n ...(r.browser_connect_port != null ? { browserConnectPort: r.browser_connect_port } : {}),\n };\n}\n\nexport function normalizeTopicVisibility(value: unknown): TopicVisibility {\n return value === \"hidden\" ? \"hidden\" : \"visible\";\n}\n\n/** Discovery boundary shared by user-facing adapters. */\nexport function isTopicVisible(topic: Pick<TopicDto, \"visibility\">): boolean {\n return topic.visibility !== \"hidden\";\n}\n\nexport function normalizeTopicKind(value: unknown): TopicKind | null {\n return value === \"channel\" || value === \"agent\" || value === \"manager\" ? value : null;\n}\n\nexport function normalizeAiMode(value: unknown): AiMode | null {\n return value === \"off\" || value === \"mention\" || value === \"always\" ? value : null;\n}\n\nexport function aiMentionFromMode(mode: AiMode): boolean {\n return mode === \"mention\";\n}\n\nexport function inferTopicKind(input: {\n agent?: string | null;\n aiMention?: boolean | null;\n}): TopicKind {\n return input.agent && input.aiMention !== true ? \"agent\" : \"channel\";\n}\n\nexport function inferAiMode(input: {\n kind?: TopicKind | null;\n agent?: string | null;\n aiMode?: AiMode | null;\n aiMention?: boolean | null;\n}): AiMode {\n if (input.kind === \"manager\") return \"always\";\n if (input.kind === \"agent\") return \"always\";\n if (input.kind === \"channel\") {\n if (!input.agent) return \"off\";\n if (input.aiMode === \"mention\") return \"mention\";\n if (input.aiMention === true) return \"mention\";\n return \"mention\";\n }\n if (!input.agent) return \"off\";\n if (input.aiMode) return input.aiMode;\n return input.aiMention === true ? \"mention\" : \"always\";\n}\n\nexport function normalizeTopicState(input: {\n id?: string;\n kind?: TopicKind | null;\n agent?: AgentKind | null;\n aiMode?: AiMode | null;\n aiMention?: boolean | null;\n}): { kind: TopicKind; aiMode: AiMode; agent?: AgentKind } {\n if (input.kind === \"manager\" || input.id === GENERAL_TOPIC_ID) {\n return {\n kind: \"manager\",\n aiMode: \"always\",\n agent: input.agent ?? resolveFallbackAgent(),\n };\n }\n\n const requestedKind = input.kind;\n const kind =\n requestedKind ??\n (input.aiMode === \"always\"\n ? \"agent\"\n : input.aiMode === \"mention\" || input.aiMode === \"off\"\n ? \"channel\"\n : input.agent && input.aiMention !== true\n ? \"agent\"\n : \"channel\");\n\n if (kind === \"agent\") {\n return {\n kind: \"agent\",\n aiMode: \"always\",\n agent: input.agent ?? resolveFallbackAgent(),\n };\n }\n\n const agent = input.aiMode === \"off\" ? undefined : (input.agent ?? undefined);\n return {\n kind: \"channel\",\n aiMode: agent ? \"mention\" : \"off\",\n agent,\n };\n}\n\nfunction normalizedTitle(title: string): string {\n return title.trim().toLowerCase();\n}\n\n/**\n * The workspace a written row belongs to.\n *\n * `surfaceScope` partitions one surface into independent namespaces. Otium\n * uses a workspace scope and Telegram uses a forum-group scope. Terminal is\n * normally unscoped. An explicit value always wins; only Otium has a\n * process-level default because its workspace attachment is host state.\n */\nfunction surfaceScopeForWrite(t: TopicDto): string | null {\n if (t.surfaceScope !== undefined) return normalizeSurfaceScope(t.surfaceScope);\n return normalizeTopicSurface(t.surface ?? defaultTopicSurface()) === \"otium\"\n ? defaultSurfaceScope()\n : null;\n}\n\nexport function upsertTopic(t: TopicDto): void {\n const normalized = normalizeTopicState({\n id: t.id,\n kind: normalizeTopicKind(t.kind),\n agent: t.agent ?? undefined,\n aiMode: normalizeAiMode(t.aiMode),\n aiMention: t.aiMention,\n });\n db.transaction(() => {\n db.query(\n `INSERT INTO api_topics\n (id,title,kind,description,agent,base_model,base_effort,response_policy,\n created_at,last_message_at,parent_topic_id,memory_topic_id,memory_key,is_fork,is_subagent,visibility,surface,\n surface_scope,subagent_report_mode,derived_by_user_id)\n VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)\n ON CONFLICT(id) DO UPDATE SET\n title = excluded.title,\n kind = excluded.kind,\n description = excluded.description,\n agent = excluded.agent,\n base_model = excluded.base_model,\n base_effort = excluded.base_effort,\n response_policy = excluded.response_policy,\n created_at = excluded.created_at,\n last_message_at = excluded.last_message_at,\n parent_topic_id = excluded.parent_topic_id,\n memory_topic_id = excluded.memory_topic_id,\n memory_key = excluded.memory_key,\n is_fork = excluded.is_fork,\n is_subagent = excluded.is_subagent,\n visibility = excluded.visibility,\n surface = excluded.surface,\n -- A room's workspace is fixed at creation (M-1). COALESCE, not\n -- assignment: an update may fill in a scope that was unknown when the\n -- room was created, but may never move a room to another workspace.\n -- An otium room is stricter (topic-link review fix 6): its scope never\n -- changes through an upsert, not even NULL -> scope; only the audited\n -- repair (adminRepairOtiumTopicScope / the M-9 stamp) may assign it.\n surface_scope = CASE\n WHEN excluded.surface = 'otium' OR api_topics.surface = 'otium'\n THEN api_topics.surface_scope\n ELSE COALESCE(api_topics.surface_scope, excluded.surface_scope)\n END,\n subagent_report_mode = excluded.subagent_report_mode,\n -- Who asked for the derive is a fact about creation; a later update\n -- that omits it must not erase it.\n derived_by_user_id = COALESCE(excluded.derived_by_user_id, api_topics.derived_by_user_id)`,\n ).run(\n t.id,\n t.title,\n normalized.kind,\n t.description ?? null,\n normalized.agent ?? null,\n t.defaultModel ?? null,\n t.defaultEffort ?? null,\n normalized.aiMode,\n t.createdAt,\n t.lastMessageAt ?? null,\n t.parentTopicId ?? null,\n t.memoryTopicId ?? null,\n t.memoryKey ?? null,\n t.isFork ? 1 : 0,\n t.isSubagent ? 1 : 0,\n normalizeTopicVisibility(t.visibility),\n // A DTO without a surface means \"wherever this host puts rooms\", not\n // \"terminal\": embedding hosts (Otium) build topic literals by hand and\n // never name one, so defaulting to the literal would file every hub room\n // on the wrong surface.\n normalizeTopicSurface(t.surface ?? defaultTopicSurface()),\n surfaceScopeForWrite(t),\n t.subagentReportMode ?? \"auto\",\n t.derivedByUserId ?? null,\n );\n db.query(\"DELETE FROM topic_members WHERE topic_id = ?\").run(t.id);\n for (const participant of t.participants) {\n db.query(\"INSERT INTO topic_members (topic_id,user_id,role) VALUES (?,?,?)\").run(\n t.id,\n participant.userId,\n participant.role,\n );\n }\n const initialBrowserProfileOwner = t.participants.find(\n (participant) => participant.role === \"owner\",\n )?.userId;\n if (initialBrowserProfileOwner) {\n db.query(\n `UPDATE api_topics\n SET browser_profile_owner = COALESCE(browser_profile_owner, ?)\n WHERE id = ?`,\n ).run(initialBrowserProfileOwner, t.id);\n }\n })();\n}\n\n/**\n * List topics, optionally restricted to one surface.\n *\n * The filter lives here rather than in each adapter so a forgotten call site\n * cannot leak a telegram room into the terminal picker; adapters pass their own\n * surface and get a closed world back.\n */\nexport function listTopics(\n opts: { surface?: TopicSurface; surfaceScope?: string | null } = {},\n): TopicDto[] {\n // `surfaceScope: null` is a real filter (\"the unscoped rooms\"), so presence —\n // not truthiness — decides whether the scope narrows the query at all.\n const scoped = Object.hasOwn(opts, \"surfaceScope\");\n const rows = (\n opts.surface\n ? db\n .query(\n `SELECT * FROM api_topics WHERE surface = ?${scoped ? \" AND surface_scope IS ?\" : \"\"} ORDER BY last_message_at DESC`,\n )\n .all(\n ...(scoped\n ? [normalizeTopicSurface(opts.surface), normalizeSurfaceScope(opts.surfaceScope)]\n : [normalizeTopicSurface(opts.surface)]),\n )\n : db.query(\"SELECT * FROM api_topics ORDER BY last_message_at DESC\").all()\n ) as TopicRow[];\n const participants = getAllTopicParticipants();\n // Batch-load tell grants once: per-row queries would make every listTopics()\n // call O(N) extra statements as subagent counts grow.\n const tellTargets = rows.some((row) => row.is_subagent !== 0)\n ? getAllSubagentTellTargets()\n : undefined;\n return rows.map((row) => rowToDto(row, participants.get(row.id) ?? [], tellTargets));\n}\n\nexport function getTopic(id: string): TopicDto | null {\n const r = db.query(\"SELECT * FROM api_topics WHERE id = ?\").get(id) as TopicRow | undefined;\n return r ? rowToDto(r) : null;\n}\n\n/** Return the private manager room owned by a user, excluding the retired shared General row. */\n/**\n * The user's own manager room, optionally on one surface.\n *\n * A manager room is one per user **per surface**: Terminal and Telegram each\n * give the same person their own personal room, and returning one surface's\n * room to the other adapter lets that adapter bind to — and reclassify — a room\n * belonging to a different surface. Callers that represent an adapter pass\n * theirs; unscoped lookups stay for maintenance paths that work by user alone.\n */\nexport function getManagerTopicForUser(\n userId: string,\n surface?: TopicSurface,\n opts: { surfaceScope?: string | null } = {},\n): TopicDto | null {\n const scoped = Object.hasOwn(opts, \"surfaceScope\");\n const sql = `SELECT t.* FROM api_topics t\n JOIN topic_members m ON m.topic_id = t.id\n WHERE t.kind = 'manager'\n AND t.id != ?\n AND m.user_id = ?\n AND m.role = 'owner'\n ${surface ? \"AND t.surface = ?\" : \"\"}\n ${scoped ? \"AND t.surface_scope IS ?\" : \"\"}\n ORDER BY t.created_at ASC\n LIMIT 1`;\n const params: Array<string | null> = [GENERAL_TOPIC_ID, userId];\n if (surface) params.push(surface);\n if (scoped) params.push(normalizeSurfaceScope(opts.surfaceScope));\n const row = db.query<TopicRow, Array<string | null>>(sql).get(...params);\n return row ? rowToDto(row) : null;\n}\n\n/**\n * Resolve the topic whose wiki memory should be used for this topic.\n *\n * Derived rooms keep `parentTopicId` as an immediate UI link. Memory normally\n * follows the chain to its original root, while `memoryTopicId` can redirect a\n * subagent to another accessible topic's accumulated knowledge.\n */\nexport function getTopicMemoryOrigin(id: string): TopicDto | null {\n let current = getTopic(id);\n if (!current) return null;\n\n const seen = new Set<string>([current.id]);\n while (true) {\n const nextId = current.memoryTopicId ?? current.parentTopicId;\n if (!nextId || seen.has(nextId)) break;\n const next = getTopic(nextId);\n if (!next) {\n // An explicitly selected memory topic that no longer resolves must not\n // silently fall back to the parent chain — that would leak the parent\n // room's memory to a subagent that asked for something else. Stop at the\n // current topic instead so the broken source is visible.\n if (current.memoryTopicId) {\n console.warn(\n `[topics] memory topic ${current.memoryTopicId} for ${current.id} is unresolvable; using the topic's own memory`,\n );\n }\n break;\n }\n current = next;\n seen.add(current.id);\n }\n\n return current;\n}\n\n/** Look up a topic by its user-visible title (case-insensitive exact match). */\nexport function getTopicByName(title: string): TopicDto | null {\n const r = db.query(\"SELECT * FROM api_topics WHERE LOWER(title) = LOWER(?)\").get(title) as\n | TopicRow\n | undefined;\n return r ? rowToDto(r) : null;\n}\n\nexport function getTopicByNameAndKind(title: string, kind: TopicKind): TopicDto | null {\n const r = db\n .query(\"SELECT * FROM api_topics WHERE LOWER(title) = LOWER(?) AND kind = ?\")\n .get(title, kind) as TopicRow | undefined;\n return r ? rowToDto(r) : null;\n}\n\n/**\n * Titles are unique **per surface namespace**, not per node: the same title may\n * exist on terminal, in multiple Telegram groups, and in each attached Otium\n * workspace. Independent namespaces never see each other, so a name taken in\n * one says nothing about another.\n */\nexport function findTopicTitleConflict(\n title: string,\n kind: TopicKind,\n opts: { excludeTopicId?: string; surface?: TopicSurface; surfaceScope?: string | null } = {},\n): TopicDto | null {\n const wanted = normalizedTitle(title);\n const surface = normalizeTopicSurface(opts.surface ?? defaultTopicSurface());\n const surfaceScope = Object.hasOwn(opts, \"surfaceScope\")\n ? normalizeSurfaceScope(opts.surfaceScope)\n : surface === \"otium\"\n ? defaultSurfaceScope()\n : null;\n const generalTitleRequested = wanted === normalizedTitle(GENERAL_TOPIC_ID);\n if (generalTitleRequested && opts.excludeTopicId !== GENERAL_TOPIC_ID) {\n const general = db.query(\"SELECT * FROM api_topics WHERE id = ?\").get(GENERAL_TOPIC_ID) as\n | TopicRow\n | undefined;\n if (general) return rowToDto(general);\n }\n\n // Manager rooms are one-per-user and system-created, so several of them\n // legitimately share a title (every member's personal \"General\"). Comparing\n // them against each other is not a conflict, it is the design — on a\n // multi-user host it renamed real rooms out from under their owners.\n if (kind === \"manager\") return null;\n\n const params: Array<string | null> = [wanted, surface, surfaceScope, kind, GENERAL_TOPIC_ID];\n let sql =\n \"SELECT * FROM api_topics WHERE LOWER(TRIM(title)) = ? AND surface = ? AND surface_scope IS ? AND (kind = ? OR id = ?)\";\n if (opts.excludeTopicId) {\n sql += \" AND id != ?\";\n params.push(opts.excludeTopicId);\n }\n sql += \" LIMIT 1\";\n const row = db.query<TopicRow, string[]>(sql).get(...params);\n return row ? rowToDto(row) : null;\n}\n\n/**\n * Move topics onto a surface. Used by adapters that own a classification the\n * canonical store cannot derive on its own (the telegram chat↔topic mapping\n * lives in that adapter's database, not this one).\n */\nexport function setTopicSurfaces(topicIds: readonly string[], surface: TopicSurface): number {\n if (topicIds.length === 0) return 0;\n const normalized = normalizeTopicSurface(surface);\n let changed = 0;\n db.transaction(() => {\n const update = db.query(\"UPDATE api_topics SET surface = ? WHERE id = ? AND surface != ?\");\n for (const topicId of topicIds) {\n changed += Number(update.run(normalized, topicId, normalized).changes ?? 0);\n }\n })();\n return changed;\n}\n\n/**\n * File an existing topic into one surface namespace without changing its id.\n * Adapter-owned migrations use this when their local mapping store is the only\n * authority capable of deriving the namespace (for example Telegram chat id).\n */\nexport function setTopicSurfaceScope(\n topicId: string,\n surface: TopicSurface,\n surfaceScope: string | null,\n): boolean {\n const normalizedSurface = normalizeTopicSurface(surface);\n const normalizedScope = normalizeSurfaceScope(surfaceScope);\n const result = db\n .query(\n `UPDATE api_topics SET surface = ?, surface_scope = ?\n WHERE id = ? AND (surface IS NOT ? OR surface_scope IS NOT ?)`,\n )\n .run(normalizedSurface, normalizedScope, topicId, normalizedSurface, normalizedScope);\n return Number(result.changes ?? 0) > 0;\n}\n\n/**\n * How wide a title lookup is allowed to reach.\n *\n * `surface` is required rather than optional. It used to default to \"search\n * every surface\", which contradicted S-6's promise that a missed call site\n * \"cannot leak a topic across surfaces\" — the guarantee only held where a\n * caller remembered to opt in, and four did not: Telegram's `/load` and `/del`\n * (the latter could delete a terminal room), the runtime MCP id path, the cron\n * id path, and the session inbox. Every one of those was a silent leak with a\n * correct-looking call. Making the parameter explicit turns each future\n * omission into a compile error instead.\n *\n * `{ scope: \"all\" }` is the deliberate way to search every surface. It exists\n * for operator tooling — the CLI manages jobs across surfaces on purpose — and\n * reads as a decision at the call site rather than as an oversight.\n */\nexport type TopicNameLookupScope =\n | { surface: TopicSurface; surfaceScope?: string | null }\n | { scope: \"all\" };\n\n/**\n * Look up a topic by title, restricted to topics where `userId` participates.\n *\n * Answers only on a single match: a title is unique per surface (S-3), so an\n * `{ scope: \"all\" }` lookup of a name used on two surfaces resolves to null\n * rather than picking one.\n */\nexport function getTopicByNameForUser(\n title: string,\n userId: string,\n lookupScope: TopicNameLookupScope,\n): TopicDto | null {\n const opts: { surface?: TopicSurface; surfaceScope?: string | null } =\n \"scope\" in lookupScope ? {} : lookupScope;\n const trimmed = title.trim();\n const qualified = /^(agent|channel|manager):(.+)$/i.exec(trimmed);\n const requestedKind = qualified ? normalizeTopicKind(qualified[1]?.toLowerCase()) : null;\n const requestedTitle = qualified ? qualified[2]!.trim() : trimmed;\n const scoped = Object.hasOwn(opts, \"surfaceScope\");\n const rows = db\n .query(\n `SELECT t.* FROM api_topics t\n WHERE LOWER(t.title) = LOWER(?)\n AND t.id != ?\n AND t.visibility != 'hidden'\n AND (? IS NULL OR t.surface = ?)\n ${scoped ? \"AND t.surface_scope IS ?\" : \"\"}\n AND EXISTS (\n SELECT 1 FROM topic_members m WHERE m.topic_id = t.id AND m.user_id = ?\n )`,\n )\n .all(\n requestedTitle,\n GENERAL_TOPIC_ID,\n opts.surface ?? null,\n opts.surface ?? null,\n ...(scoped ? [normalizeSurfaceScope(opts.surfaceScope)] : []),\n userId,\n ) as TopicRow[];\n const matches = requestedKind ? rows.filter((row) => row.kind === requestedKind) : rows;\n return matches.length === 1 ? rowToDto(matches[0]!) : null;\n}\n\n/** Persist the agent session ID for a topic after a successful turn. */\nexport function setTopicSessionId(\n topicId: string,\n sessionId: string,\n context: TopicSessionLogContext = {},\n): void {\n const previous = getTopicSessionId(topicId);\n const result = db\n .query(\"UPDATE api_topics SET session_id = ? WHERE id = ?\")\n .run(sessionId, topicId);\n const changes = Number(result.changes ?? 0);\n const logContext = {\n topicId,\n previousSessionId: shortSessionId(previous),\n sessionId: shortSessionId(sessionId),\n reason: context.reason,\n queryId: context.queryId,\n agent: context.agent,\n };\n if (changes === 0) {\n logger.warn(logContext, \"api-topic session_id update missed topic\");\n } else if (previous !== sessionId) {\n logger.debug(logContext, \"api-topic session_id updated\");\n } else {\n logger.debug(logContext, \"api-topic session_id unchanged\");\n }\n}\n\n/** Clear the session ID (e.g. on topic reset). */\nexport function clearTopicSessionId(topicId: string, reason = \"unspecified\"): void {\n const previous = getTopicSessionId(topicId);\n const result = db.query(\"UPDATE api_topics SET session_id = NULL WHERE id = ?\").run(topicId);\n const changes = Number(result.changes ?? 0);\n const logContext = { topicId, previousSessionId: shortSessionId(previous), reason };\n if (changes === 0) {\n logger.warn(logContext, \"api-topic session_id clear missed topic\");\n } else if (previous) {\n logger.info(logContext, \"api-topic session_id cleared\");\n } else {\n logger.debug(logContext, \"api-topic session_id already clear\");\n }\n}\n\n/** Read the persisted session ID for a topic, or null if none. */\nexport function getTopicSessionId(topicId: string): string | null {\n const r = db\n .query<{ session_id: string | null }, string>(\"SELECT session_id FROM api_topics WHERE id = ?\")\n .get(topicId);\n return r?.session_id ?? null;\n}\n\n/**\n * Hard-delete a topic row. Irreversible — the caller is responsible for also\n * deleting the topic's messages (see `deleteMessagesForTopic`). Returns false\n * if the topic didn't exist.\n */\nexport function deleteTopic(id: string, options: { allowManager?: boolean } = {}): boolean {\n const r = db\n .query<{ id: string; kind: string }, string>(\"SELECT id, kind FROM api_topics WHERE id = ?\")\n .get(id);\n if (!r) return false;\n if (id === GENERAL_TOPIC_ID || (r.kind === \"manager\" && !options.allowManager)) return false;\n db.query(\n `DELETE FROM subagent_tell_grants\n WHERE subagent_topic_id = ? OR target_topic_id = ? OR granted_by_topic_id = ?`,\n ).run(id, id, id);\n db.query(\"DELETE FROM topic_members WHERE topic_id = ?\").run(id);\n db.query(\"DELETE FROM api_topics WHERE id = ?\").run(id);\n return true;\n}\n\nexport function listSubagentTellTargetIds(subagentTopicId: string): string[] {\n return db\n .query<{ target_topic_id: string }, string>(\n \"SELECT target_topic_id FROM subagent_tell_grants WHERE subagent_topic_id = ? ORDER BY created_at\",\n )\n .all(subagentTopicId)\n .map((row) => row.target_topic_id);\n}\n\nexport function grantSubagentTellTarget(\n subagentTopicId: string,\n targetTopicId: string,\n grantedByTopicId: string,\n): void {\n db.query(\n `INSERT INTO subagent_tell_grants\n (subagent_topic_id,target_topic_id,granted_by_topic_id,created_at)\n VALUES (?,?,?,?)\n ON CONFLICT(subagent_topic_id,target_topic_id) DO UPDATE SET\n granted_by_topic_id = excluded.granted_by_topic_id`,\n ).run(subagentTopicId, targetTopicId, grantedByTopicId, new Date().toISOString());\n}\n\nexport function revokeSubagentTellTarget(subagentTopicId: string, targetTopicId: string): boolean {\n return (\n db\n .query(\"DELETE FROM subagent_tell_grants WHERE subagent_topic_id = ? AND target_topic_id = ?\")\n .run(subagentTopicId, targetTopicId).changes > 0\n );\n}\n\n/**\n * Preserve a derived-topic chain when an intermediate parent is deleted.\n * Direct children move to the deleted topic's parent (or become roots) rather\n * than retaining a dangling parent id that would break memory-origin lookup.\n */\n/** Ids of the subagent worker rooms spawned directly from `parentTopicId`. */\nexport function listSubagentChildTopicIds(parentTopicId: string): string[] {\n return db\n .query<{ id: string }, string>(\n \"SELECT id FROM api_topics WHERE parent_topic_id = ? AND is_subagent = 1 ORDER BY created_at\",\n )\n .all(parentTopicId)\n .map((row) => row.id);\n}\n\nexport function reparentTopicChildren(\n deletedTopicId: string,\n replacementParentTopicId: string | null,\n): string[] {\n const rows = db\n .query<{ id: string }, string>(\"SELECT id FROM api_topics WHERE parent_topic_id = ?\")\n .all(deletedTopicId);\n if (rows.length === 0) return [];\n db.query(\"UPDATE api_topics SET parent_topic_id = ? WHERE parent_topic_id = ?\").run(\n replacementParentTopicId,\n deletedTopicId,\n );\n // Reparenting can move a topic out of the subtree whose manager granted its\n // tell edges; purge involved grants (fail closed) — an ancestor can re-grant.\n for (const row of rows) {\n db.query(\n \"DELETE FROM subagent_tell_grants WHERE subagent_topic_id = ? OR target_topic_id = ?\",\n ).run(row.id, row.id);\n }\n return rows.map((row) => row.id);\n}\n\nexport function addParticipantToDB(\n topicId: string,\n userId: string,\n role: \"member\" | \"owner\",\n): boolean {\n if (!db.query(\"SELECT 1 FROM api_topics WHERE id = ?\").get(topicId)) return false;\n db.query(\"INSERT OR IGNORE INTO topic_members (topic_id,user_id,role) VALUES (?,?,?)\").run(\n topicId,\n userId,\n role,\n );\n return true;\n}\n\nexport function removeParticipantFromDB(topicId: string, userId: string): boolean {\n if (!db.query(\"SELECT 1 FROM api_topics WHERE id = ?\").get(topicId)) return false;\n db.query(\"DELETE FROM topic_members WHERE topic_id = ? AND user_id = ?\").run(topicId, userId);\n return true;\n}\n",
|
|
36
|
-
"import { accessSync, constants as fsConstants } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { explicitAgentSwitchTargets } from \"#agents/explicit-agent-switch\";\n\nimport { 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 CANONICAL_MCP_PROXY_SERVER,\n DECISION_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 {\n buildPlaywrightMcpTransport,\n CODEX_BROWSER_CAPABILITY_ENV,\n} from \"#platform/playwright/mcp-transport\";\nimport { actorTopicScopeMaxAgeMs, encodeActorTopicScopeArg } from \"#runtime/actor-topic-scope\";\nimport { getRegisteredCronSession } from \"#runtime/cron-sessions\";\nimport { encodeRemoteSessionGrantArg } from \"#runtime/remote-session-grant\";\nimport type { HostMcpServerSpec } from \"#runtime-gateway\";\nimport { getTopic } from \"#storage/api-topics\";\nimport type {\n ActorTopicScope,\n AgentKind,\n AgentQueryOptions,\n PeerRuntimeBridgeContext,\n RemoteSessionGrant,\n} from \"#types\";\nimport type { TopicDto } from \"#types/api\";\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 ...(ctx.actorUserId ? { actorUserId: ctx.actorUserId } : {}),\n ...(ctx.actorTopicScope ? { actorTopicScope: ctx.actorTopicScope } : {}),\n // Only the session-comm surface addresses remote rooms; the other hosted\n // tokens (and the runtime token) never carry the grant, so it costs them\n // no URL budget.\n ...(surface === \"session-comm\" && ctx.remoteSession\n ? { remoteSession: ctx.remoteSession }\n : {}),\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 ...(ctx.threadRootId ? { threadRootId: ctx.threadRootId } : {}),\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 forum-name views read from this catalog plus the node-assigned\n * manifest overlay installed below. Adding a built-in MCP server remains 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 /** Product actor identity when it differs from the execution principal. */\n actorUserId?: string;\n /** Hub-asserted rooms the product actor may reach; forwarded into signed tokens. */\n actorTopicScope?: ActorTopicScope;\n /** Hub-issued per-turn remote session-comm grant; session-comm only. */\n remoteSession?: RemoteSessionGrant;\n /** Vault namespace when credentials belong to a different principal. */\n vaultUserId?: 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 /** Thread this turn answers inside; forwarded to the runtime MCP context. */\n threadRootId?: string;\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 { browserOwnerCapability, buildPlaywrightMcpTransport, CODEX_BROWSER_CAPABILITY_ENV };\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 longLivedHttpMcp(agent: AgentKind | undefined, port: number) {\n return agent === \"codex\"\n ? { url: `http://127.0.0.1:${port}/mcp` }\n : { type: \"sse\" as const, url: `http://127.0.0.1:${port}/sse` };\n}\n\n// cua-rs implements Streamable HTTP only; unlike browser-rs, it does not\n// expose the legacy SSE endpoint. The port is installed by the node-owned\n// process manager once its singleton is ready.\nlet cuaRsMcpPort: number | undefined;\n// cua-rs 0.8.0 requires `Authorization: Bearer` on /mcp, because loopback is not\n// an authorization boundary -- any local process, a web page included, could\n// otherwise drive the whole desktop. The node picks the token, hands it to the\n// child as CUA_HTTP_TOKEN, and publishes it here so turns can present it. Kept\n// beside the port because they are one fact: without both, the URL is useless.\nlet cuaRsMcpToken: string | undefined;\n\nexport function setCuaRsMcpPort(port: number | undefined, token?: string): void {\n if (port !== undefined && (!Number.isInteger(port) || port < 1 || port > 65_535)) {\n throw new Error(`invalid cua-rs MCP port: ${port}`);\n }\n cuaRsMcpPort = port;\n cuaRsMcpToken = port === undefined ? undefined : token;\n}\n\nfunction cuaRsHttpMcp(agent: AgentKind | undefined, port: number, token: string | undefined) {\n const url = `http://127.0.0.1:${port}/mcp`;\n // No token means an older cua-rs that does not ask for one. Sending the header\n // anyway would be harmless, but omitting it keeps the config honest about what\n // the running server actually requires.\n const headers = token ? { Authorization: `Bearer ${token}` } : undefined;\n // The shape is otherwise unchanged from before the token existed, including\n // `type` for codex: only the header field is added, and only when there is a\n // token to put in it. Codex spells that field `http_headers`.\n const base = { type: \"http\" as const, url };\n if (!headers) return base;\n return agent === \"codex\" ? { ...base, http_headers: headers } : { ...base, headers };\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 and Maestro use Streamable HTTP while Claude uses 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 buildPlaywrightMcpTransport(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 actorUserId,\n actorTopicScope,\n session,\n topicId,\n queryId,\n agent,\n cwd,\n model,\n currentUserPrompt,\n autoContinue,\n visualTools,\n fileDeliveryTools,\n threadRootId,\n peerBridge,\n }) {\n if (!topicId || !agent) return null;\n const switchTargets = explicitAgentSwitchTargets(currentUserPrompt);\n return buildRuntimeMcpSpec(agent, {\n // Runtime tools mutate node-owned state, so authorization stays bound\n // to the canonical execution principal. Keep the product-side human\n // actor separately for attribution instead of replacing the identity\n // that appears in this node's topic participant roster.\n userId,\n ...(actorUserId ? { actorUserId } : {}),\n ...(actorTopicScope ? { actorTopicScope } : {}),\n topicId,\n topicTitle: session,\n queryId,\n cwd: cwd ?? resolveTopicWorkspaceDir(topicId),\n agent,\n model,\n // Derived here, from the full prompt, so the signed token carries the\n // gate's answer (bounded) instead of the prompt (unbounded); see\n // `explicitAgentSwitchTargets`.\n ...(switchTargets.length ? { explicitAgentSwitchTargets: switchTargets } : {}),\n autoContinue,\n visualTools,\n fileDeliveryTools,\n ...(threadRootId ? { threadRootId } : {}),\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 decision: {\n ...commonRuntimeMcpPolicy(\"decision\"),\n build(ctx) {\n const { userId, session, topicId, queryId, agent, model, peerBridge } = ctx;\n if (peerBridge) {\n if (!topicId || !queryId) return null;\n const env = canonicalMcpBridgeEnv({\n surface: \"decision\",\n userId,\n topicId,\n queryId,\n peerBridge,\n });\n return env\n ? buildStdioMcpServer(agent, CANONICAL_MCP_PROXY_SERVER, [\"--surface=decision\"], env)\n : null;\n }\n const args = [\n `--user-id=${userId}`,\n `--topic=${session}`,\n `--agent=${agent ?? FALLBACK_AGENT}`,\n ];\n if (topicId) args.push(`--topic-id=${topicId}`);\n if (model) args.push(`--model=${model}`);\n return buildBuiltinMcpServer(\"decision\", ctx, () =>\n buildStdioMcpServer(agent, DECISION_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 actorUserId,\n actorTopicScope,\n remoteSession,\n session,\n topicId,\n subagentParentTopicId,\n agent,\n depth = 0,\n silent,\n threadRootId,\n peerBridge,\n } = ctx;\n const effectiveAgent = agent ?? FALLBACK_AGENT;\n const cronSessionId = topicId\n ? getRegisteredCronSession(topicId, effectiveAgent)?.sessionId\n : undefined;\n const args = [\n `--user-id=${userId}`,\n ...(actorUserId ? [`--actor-user-id=${actorUserId}`] : []),\n ...(actorTopicScope\n ? [\n `--actor-topic-scope=${encodeActorTopicScopeArg(actorTopicScope)}`,\n // The child does not inherit this process's env; hand it the\n // same freshness window the hosted tools apply.\n `--actor-topic-scope-max-age-ms=${actorTopicScopeMaxAgeMs()}`,\n ]\n : []),\n ...(remoteSession\n ? [`--remote-session-grant=${encodeRemoteSessionGrantArg(remoteSession)}`]\n : []),\n `--topic=${session}`,\n ...(topicId ? [`--topic-id=${topicId}`] : []),\n ...(subagentParentTopicId ? [`--subagent-parent-topic-id=${subagentParentTopicId}`] : []),\n `--depth=${depth}`,\n `--agent=${effectiveAgent}`,\n ...(cronSessionId ? [`--cron-session-id=${cronSessionId}`] : []),\n ...(silent ? [\"--reply-only=true\"] : []),\n // Turn-scoped, like `--peer-host-query-id`: this config is rebuilt for\n // every turn, so an `ask_session` raised inside a thread can record\n // where its answer belongs.\n ...(threadRootId ? [`--thread-root-id=${threadRootId}`] : []),\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 if (topicId) args.push(`--current-topic-id=${topicId}`);\n // Prefer the REST topic id so wiki_write 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, vaultUserId, 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=${vaultUserId ?? userId}`];\n if (agent !== \"codex\") args.push(\"--list-only=true\");\n return buildBuiltinMcpServer(\"vault\", { ...ctx, userId: vaultUserId ?? userId }, () =>\n buildStdioMcpServer(agent, VAULT_SERVER, args),\n );\n },\n },\n // macOS desktop control, delegated to maestrojeong/cua-rs rather than\n // reimplemented. The node owns one persistent Streamable HTTP process;\n // turns only receive its loopback URL and must never spawn a stdio copy.\n \"cua-rs\": {\n ...commonRuntimeMcpPolicy(\"cua-rs\"),\n build({ agent }) {\n return cuaRsMcpPort ? cuaRsHttpMcp(agent, cuaRsMcpPort, cuaRsMcpToken) : null;\n },\n },\n};\n\n/**\n * Locate the `cua-rs` binary, or `null` when it is not installed.\n *\n * Checked in order of specificity: an explicit env override for anyone running\n * a local build, then the installer's default target, then `/usr/local/bin`\n * for a `--bin-dir` install. PATH is deliberately not consulted -- the server\n * is spawned by a supervised host process whose PATH is not the user's shell\n * PATH, so a PATH lookup would succeed in a terminal and fail under pm2.\n */\nexport function resolveCuaRsBinary(platform: NodeJS.Platform = process.platform): string | null {\n if (platform !== \"darwin\") return null;\n const candidates = [\n envText(\"NEGOTIUM_CUA_RS_BIN\"),\n join(homedir(), \".local\", \"bin\", \"cua-rs\"),\n \"/usr/local/bin/cua-rs\",\n ].filter((p): p is string => Boolean(p));\n for (const candidate of candidates) {\n try {\n accessSync(candidate, fsConstants.X_OK);\n return candidate;\n } catch {\n // Not there, or not executable. Try the next one.\n }\n }\n return null;\n}\n\n// --- Derived catalog views ---\n\nexport type NodeMcpEntry =\n | { key: string; kind: \"http\"; port: number }\n | {\n key: string;\n kind: \"http-instance\";\n ensurePort: (instanceKey: string) => Promise<number>;\n }\n | { key: string; kind: \"stdio\"; command: string; args?: string[]; env?: Record<string, string> };\n\nlet nodeMcpEntries: NodeMcpEntry[] = [];\nconst resolvedNodeMcpPorts = new WeakMap<\n Extract<NodeMcpEntry, { kind: \"http-instance\" }>,\n Map<string, number>\n>();\n\n/** All forum-eligible MCP server names, in display order. */\nconst allForumMcpServerNames: string[] = [];\nexport const ALL_FORUM_MCP_SERVER_NAMES: readonly string[] = allForumMcpServerNames;\n\n/** Forum servers that cannot be removed via the enabled whitelist. */\nconst requiredForumMcpServers: string[] = [];\nexport const REQUIRED_FORUM_MCP_SERVERS: readonly string[] = requiredForumMcpServers;\n\n/** Forum servers that can be toggled via the enabled whitelist (not required). */\nconst optionalForumMcpServers: string[] = [];\nexport const OPTIONAL_FORUM_MCP_SERVERS: readonly string[] = optionalForumMcpServers;\n\nfunction refreshForumCatalogViews(): void {\n const { all, required, optional } = classifyForumMcpServers(MCP_CATALOG);\n const nodeNames = nodeMcpEntries.map((entry) => entry.key);\n const allWithNodeEntries = [...new Set([...all, ...nodeNames])];\n const optionalWithNodeEntries = [...new Set([...optional, ...nodeNames])];\n allForumMcpServerNames.splice(0, allForumMcpServerNames.length, ...allWithNodeEntries);\n requiredForumMcpServers.splice(0, requiredForumMcpServers.length, ...required);\n optionalForumMcpServers.splice(0, optionalForumMcpServers.length, ...optionalWithNodeEntries);\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 availableOptional = new Set(OPTIONAL_FORUM_MCP_SERVERS);\n const optionalActive = [...new Set(config.enabled)].filter((name) => availableOptional.has(name));\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\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 refreshForumCatalogViews();\n}\n\nexport function getNodeMcpServers(): readonly NodeMcpEntry[] {\n return nodeMcpEntries;\n}\n\n/** Prevent host grants from replacing node-owned MCP servers. */\nexport function isReservedRuntimeMcpServerName(name: string): boolean {\n return Object.hasOwn(MCP_CATALOG, name) || nodeMcpEntries.some((entry) => entry.key === name);\n}\n\n/** Host MCP servers that administer the workspace; only a manager room may receive them. */\nconst MANAGER_ONLY_HOST_MCP_NAMES = new Set([\"topic-admin\"]);\n\n/**\n * Why `topic` may not receive host MCP servers named `names`, or null when it\n * may. A manager room takes any of them. An ordinary room takes everything but\n * the manager administration surface, so a host can scope its own tools to a\n * room. A subagent room takes none.\n */\nexport function hostMcpGrantRefusal(\n topic: Pick<TopicDto, \"kind\" | \"isSubagent\">,\n names: readonly string[],\n): string | null {\n if (topic.kind === \"manager\") return null;\n if (topic.isSubagent) return \"hostMcpServers is not allowed for subagent topics\";\n const managerOnly = names.find((name) => MANAGER_ONLY_HOST_MCP_NAMES.has(name));\n return managerOnly ? `${managerOnly} is only allowed for manager topics` : null;\n}\n\nfunction withoutManagerOnlyHostMcpServers(\n hostMcpServers: Record<string, HostMcpServerSpec> | undefined,\n): Record<string, HostMcpServerSpec> | undefined {\n if (!hostMcpServers) return undefined;\n return Object.fromEntries(\n Object.entries(hostMcpServers).filter(([name]) => !MANAGER_ONLY_HOST_MCP_NAMES.has(name)),\n );\n}\n\nfunction mergeHostMcpServers(\n base: Record<string, unknown>,\n hostMcpServers: Record<string, HostMcpServerSpec> | undefined,\n): Record<string, unknown> {\n if (!hostMcpServers) return base;\n for (const name of Object.keys(hostMcpServers)) {\n if (Object.hasOwn(base, name) || isReservedRuntimeMcpServerName(name)) {\n throw new Error(`host MCP server name conflicts with node catalog: ${name}`);\n }\n }\n return { ...base, ...hostMcpServers };\n}\n\nfunction buildNodeMcpSpecs(\n agent: AgentKind | undefined,\n filter: (name: string) => boolean,\n ctx: Pick<RuntimeMcpBuildContext, \"topicId\" | \"userId\" | \"session\">,\n): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const entry of nodeMcpEntries) {\n if (!filter(entry.key)) continue;\n if (entry.kind === \"http\") {\n out[entry.key] = longLivedHttpMcp(agent, entry.port);\n continue;\n }\n if (entry.kind === \"http-instance\") {\n const port = resolvedNodeMcpPorts.get(entry)?.get(nodeMcpInstanceKey(ctx));\n if (port !== undefined) out[entry.key] = longLivedHttpMcp(agent, port);\n continue;\n }\n out[entry.key] = {\n command: entry.command,\n args: entry.args ?? [],\n ...(entry.env ? { env: entry.env } : {}),\n };\n }\n return out;\n}\n\nfunction nodeMcpInstanceKey(\n ctx: Pick<RuntimeMcpBuildContext, \"topicId\" | \"userId\" | \"session\">,\n): string {\n return ctx.topicId ?? `user:${ctx.userId}:session:${ctx.session}`;\n}\n\n/**\n * Lazily prepare per-topic HTTP manifest entries before a provider resolves\n * its otherwise-synchronous MCP config. One failed custom server is omitted\n * from that turn without taking down the rest of the runtime catalog.\n */\nexport async function prepareNodeMcpServersForQuery(opts: AgentQueryOptions): Promise<void> {\n if (\n opts.toolPolicy ||\n opts.sessionType === \"cron\" ||\n nodeMcpEntries.every((entry) => entry.kind !== \"http-instance\")\n ) {\n return;\n }\n\n const forum = ![\"dm\", \"ephemeral\", \"manager\"].includes(opts.sessionType ?? \"forum\");\n const enabled = opts.mcpEnabled ?? null;\n const instanceKey = nodeMcpInstanceKey({\n topicId: opts.topicId,\n userId: opts.userId || \"local\",\n session: opts.session || \"default\",\n });\n\n await Promise.all(\n nodeMcpEntries.map(async (entry) => {\n if (entry.kind !== \"http-instance\") return;\n if (forum && enabled !== null && !enabled.includes(entry.key)) return;\n let ports = resolvedNodeMcpPorts.get(entry);\n if (!ports) {\n ports = new Map();\n resolvedNodeMcpPorts.set(entry, ports);\n }\n try {\n const port = await entry.ensurePort(instanceKey);\n if (!Number.isInteger(port) || port < 1 || port > 65_535) {\n throw new Error(`invalid port ${port}`);\n }\n ports.set(instanceKey, port);\n } catch (err) {\n ports.delete(instanceKey);\n logger.warn(\n { err, key: entry.key, instanceKey },\n \"node mcp: failed to prepare instance-scoped server\",\n );\n }\n }),\n );\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, ctx));\n }\n return out;\n}\n\n/** DM session: catalog entries with `dm` scope, no whitelist. */\nexport function getDmMcpServers(opts: {\n userId: string;\n session?: string;\n topicId?: string;\n agent?: AgentKind;\n playwrightPort?: number;\n playwrightCapability?: string;\n}) {\n return buildScope(\"dm\", {\n userId: opts.userId,\n session: opts.session ?? \"dm\",\n topicId: opts.topicId,\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 actorUserId?: string;\n actorTopicScope?: ActorTopicScope;\n remoteSession?: RemoteSessionGrant;\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 actorUserId: opts.actorUserId,\n actorTopicScope: opts.actorTopicScope,\n remoteSession: opts.remoteSession,\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 actorUserId?: string;\n actorTopicScope?: ActorTopicScope;\n remoteSession?: RemoteSessionGrant;\n vaultUserId?: 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 threadRootId?: string;\n depth?: number;\n enabled?: string[] | null;\n extra?: Record<string, unknown>;\n silent?: boolean;\n peerBridge?: PeerRuntimeBridgeContext;\n}) {\n const {\n userId,\n actorUserId,\n actorTopicScope,\n remoteSession,\n vaultUserId,\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 threadRootId,\n peerBridge,\n } = opts;\n\n const filter = (name: string) => {\n if (silent && (name === \"task\" || name === \"decision\")) 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 actorUserId,\n actorTopicScope,\n remoteSession,\n vaultUserId,\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 threadRootId,\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 hideProviderIntrospectionForOtium(\n 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 opts.topicId,\n );\n }\n if (opts.sessionType === \"dm\" || opts.sessionType === \"ephemeral\") {\n return getDmMcpServers({\n userId: opts.userId || \"local\",\n session: opts.session,\n topicId: opts.topicId,\n agent: opts.agent,\n playwrightPort: opts.playwrightPort,\n playwrightCapability: opts.playwrightCapability,\n });\n }\n if (opts.sessionType === \"manager\") {\n return hideProviderIntrospectionForOtium(\n mergeHostMcpServers(\n getManagerMcpServers({\n userId: opts.userId || \"local\",\n actorUserId: opts.actorUserId,\n actorTopicScope: opts.actorTopicScope,\n remoteSession: opts.remoteSession,\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 opts.hostMcpServers,\n ),\n opts.topicId,\n );\n }\n return hideProviderIntrospectionForOtium(\n mergeHostMcpServers(\n getForumMcpServers({\n userId: opts.userId || \"local\",\n actorUserId: opts.actorUserId,\n actorTopicScope: opts.actorTopicScope,\n remoteSession: opts.remoteSession,\n vaultUserId: opts.vaultUserId,\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 threadRootId: opts.threadRootId,\n depth: opts.depth,\n enabled: opts.mcpEnabled,\n extra: opts.mcpExtra,\n silent: opts.silent,\n peerBridge: opts.peerBridge,\n }),\n withoutManagerOnlyHostMcpServers(opts.hostMcpServers),\n ),\n opts.topicId,\n );\n}\n\nfunction hideProviderIntrospectionForOtium(\n servers: Record<string, unknown>,\n topicId: string | undefined,\n): Record<string, unknown> {\n if (!topicId || getTopic(topicId)?.surface !== \"otium\") return servers;\n const filtered = { ...servers };\n delete filtered[\"agent-health\"];\n delete filtered[\"token-stats\"];\n return filtered;\n}\n",
|
|
36
|
+
"import { accessSync, constants as fsConstants } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { explicitAgentSwitchTargets } from \"#agents/explicit-agent-switch\";\n\nimport { 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 CANONICAL_MCP_PROXY_SERVER,\n DECISION_SERVER,\n envText,\n FALLBACK_AGENT,\n resolveTopicWorkspaceDir,\n SESSION_COMM_SERVER,\n SESSION_HISTORY_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 {\n buildPlaywrightMcpTransport,\n CODEX_BROWSER_CAPABILITY_ENV,\n} from \"#platform/playwright/mcp-transport\";\nimport { actorTopicScopeMaxAgeMs, encodeActorTopicScopeArg } from \"#runtime/actor-topic-scope\";\nimport { getRegisteredCronSession } from \"#runtime/cron-sessions\";\nimport { encodeRemoteSessionGrantArg } from \"#runtime/remote-session-grant\";\nimport type { HostMcpServerSpec } from \"#runtime-gateway\";\nimport { getTopic } from \"#storage/api-topics\";\nimport type {\n ActorTopicScope,\n AgentKind,\n AgentQueryOptions,\n PeerRuntimeBridgeContext,\n RemoteSessionGrant,\n} from \"#types\";\nimport type { TopicDto } from \"#types/api\";\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 ...(ctx.actorUserId ? { actorUserId: ctx.actorUserId } : {}),\n ...(ctx.actorTopicScope ? { actorTopicScope: ctx.actorTopicScope } : {}),\n // Only the session-comm surface addresses remote rooms; the other hosted\n // tokens (and the runtime token) never carry the grant, so it costs them\n // no URL budget.\n ...(surface === \"session-comm\" && ctx.remoteSession\n ? { remoteSession: ctx.remoteSession }\n : {}),\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 ...(ctx.threadRootId ? { threadRootId: ctx.threadRootId } : {}),\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 forum-name views read from this catalog plus the node-assigned\n * manifest overlay installed below. Adding a built-in MCP server remains 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 /** Product actor identity when it differs from the execution principal. */\n actorUserId?: string;\n /** Hub-asserted rooms the product actor may reach; forwarded into signed tokens. */\n actorTopicScope?: ActorTopicScope;\n /** Hub-issued per-turn remote session-comm grant; session-comm only. */\n remoteSession?: RemoteSessionGrant;\n /** Vault namespace when credentials belong to a different principal. */\n vaultUserId?: 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 /** Thread this turn answers inside; forwarded to the runtime MCP context. */\n threadRootId?: string;\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 { browserOwnerCapability, buildPlaywrightMcpTransport, CODEX_BROWSER_CAPABILITY_ENV };\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 longLivedHttpMcp(agent: AgentKind | undefined, port: number) {\n return agent === \"codex\"\n ? { url: `http://127.0.0.1:${port}/mcp` }\n : { type: \"sse\" as const, url: `http://127.0.0.1:${port}/sse` };\n}\n\n// cua-rs implements Streamable HTTP only; unlike browser-rs, it does not\n// expose the legacy SSE endpoint. The port is installed by the node-owned\n// process manager once its singleton is ready.\nlet cuaRsMcpPort: number | undefined;\n// cua-rs 0.8.0 requires `Authorization: Bearer` on /mcp, because loopback is not\n// an authorization boundary -- any local process, a web page included, could\n// otherwise drive the whole desktop. The node picks the token, hands it to the\n// child as CUA_HTTP_TOKEN, and publishes it here so turns can present it. Kept\n// beside the port because they are one fact: without both, the URL is useless.\nlet cuaRsMcpToken: string | undefined;\n\nexport function setCuaRsMcpPort(port: number | undefined, token?: string): void {\n if (port !== undefined && (!Number.isInteger(port) || port < 1 || port > 65_535)) {\n throw new Error(`invalid cua-rs MCP port: ${port}`);\n }\n cuaRsMcpPort = port;\n cuaRsMcpToken = port === undefined ? undefined : token;\n}\n\nfunction cuaRsHttpMcp(agent: AgentKind | undefined, port: number, token: string | undefined) {\n const url = `http://127.0.0.1:${port}/mcp`;\n // No token means an older cua-rs that does not ask for one. Sending the header\n // anyway would be harmless, but omitting it keeps the config honest about what\n // the running server actually requires.\n const headers = token ? { Authorization: `Bearer ${token}` } : undefined;\n // The shape is otherwise unchanged from before the token existed, including\n // `type` for codex: only the header field is added, and only when there is a\n // token to put in it. Codex spells that field `http_headers`.\n const base = { type: \"http\" as const, url };\n if (!headers) return base;\n return agent === \"codex\" ? { ...base, http_headers: headers } : { ...base, headers };\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 and Maestro use Streamable HTTP while Claude uses 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 buildPlaywrightMcpTransport(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 actorUserId,\n actorTopicScope,\n session,\n topicId,\n queryId,\n agent,\n cwd,\n model,\n currentUserPrompt,\n autoContinue,\n visualTools,\n fileDeliveryTools,\n threadRootId,\n peerBridge,\n }) {\n if (!topicId || !agent) return null;\n const switchTargets = explicitAgentSwitchTargets(currentUserPrompt);\n return buildRuntimeMcpSpec(agent, {\n // Runtime tools mutate node-owned state, so authorization stays bound\n // to the canonical execution principal. Keep the product-side human\n // actor separately for attribution instead of replacing the identity\n // that appears in this node's topic participant roster.\n userId,\n ...(actorUserId ? { actorUserId } : {}),\n ...(actorTopicScope ? { actorTopicScope } : {}),\n topicId,\n topicTitle: session,\n queryId,\n cwd: cwd ?? resolveTopicWorkspaceDir(topicId),\n agent,\n model,\n // Derived here, from the full prompt, so the signed token carries the\n // gate's answer (bounded) instead of the prompt (unbounded); see\n // `explicitAgentSwitchTargets`.\n ...(switchTargets.length ? { explicitAgentSwitchTargets: switchTargets } : {}),\n autoContinue,\n visualTools,\n fileDeliveryTools,\n ...(threadRootId ? { threadRootId } : {}),\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 decision: {\n ...commonRuntimeMcpPolicy(\"decision\"),\n build(ctx) {\n const { userId, session, topicId, queryId, agent, model, peerBridge } = ctx;\n if (peerBridge) {\n if (!topicId || !queryId) return null;\n const env = canonicalMcpBridgeEnv({\n surface: \"decision\",\n userId,\n topicId,\n queryId,\n peerBridge,\n });\n return env\n ? buildStdioMcpServer(agent, CANONICAL_MCP_PROXY_SERVER, [\"--surface=decision\"], env)\n : null;\n }\n const args = [\n `--user-id=${userId}`,\n `--topic=${session}`,\n `--agent=${agent ?? FALLBACK_AGENT}`,\n ];\n if (topicId) args.push(`--topic-id=${topicId}`);\n if (model) args.push(`--model=${model}`);\n return buildBuiltinMcpServer(\"decision\", ctx, () =>\n buildStdioMcpServer(agent, DECISION_SERVER, args),\n );\n },\n },\n \"session-history\": {\n ...commonRuntimeMcpPolicy(\"session-history\"),\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: \"session-history\",\n userId,\n topicId,\n queryId,\n peerBridge,\n });\n return env\n ? buildStdioMcpServer(\n agent,\n CANONICAL_MCP_PROXY_SERVER,\n [\"--surface=session-history\"],\n env,\n )\n : null;\n }\n const args = [`--user-id=${userId}`, `--topic=${session}`];\n if (topicId) args.push(`--topic-id=${topicId}`);\n return buildBuiltinMcpServer(\"session-history\", ctx, () =>\n buildStdioMcpServer(agent, SESSION_HISTORY_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 actorUserId,\n actorTopicScope,\n remoteSession,\n session,\n topicId,\n subagentParentTopicId,\n agent,\n depth = 0,\n silent,\n threadRootId,\n peerBridge,\n } = ctx;\n const effectiveAgent = agent ?? FALLBACK_AGENT;\n const cronSessionId = topicId\n ? getRegisteredCronSession(topicId, effectiveAgent)?.sessionId\n : undefined;\n const args = [\n `--user-id=${userId}`,\n ...(actorUserId ? [`--actor-user-id=${actorUserId}`] : []),\n ...(actorTopicScope\n ? [\n `--actor-topic-scope=${encodeActorTopicScopeArg(actorTopicScope)}`,\n // The child does not inherit this process's env; hand it the\n // same freshness window the hosted tools apply.\n `--actor-topic-scope-max-age-ms=${actorTopicScopeMaxAgeMs()}`,\n ]\n : []),\n ...(remoteSession\n ? [`--remote-session-grant=${encodeRemoteSessionGrantArg(remoteSession)}`]\n : []),\n `--topic=${session}`,\n ...(topicId ? [`--topic-id=${topicId}`] : []),\n ...(subagentParentTopicId ? [`--subagent-parent-topic-id=${subagentParentTopicId}`] : []),\n `--depth=${depth}`,\n `--agent=${effectiveAgent}`,\n ...(cronSessionId ? [`--cron-session-id=${cronSessionId}`] : []),\n ...(silent ? [\"--reply-only=true\"] : []),\n // Turn-scoped, like `--peer-host-query-id`: this config is rebuilt for\n // every turn, so an `ask_session` raised inside a thread can record\n // where its answer belongs.\n ...(threadRootId ? [`--thread-root-id=${threadRootId}`] : []),\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 if (topicId) args.push(`--current-topic-id=${topicId}`);\n // Prefer the REST topic id so wiki_write 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, vaultUserId, 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=${vaultUserId ?? userId}`];\n if (agent !== \"codex\") args.push(\"--list-only=true\");\n return buildBuiltinMcpServer(\"vault\", { ...ctx, userId: vaultUserId ?? userId }, () =>\n buildStdioMcpServer(agent, VAULT_SERVER, args),\n );\n },\n },\n // macOS desktop control, delegated to maestrojeong/cua-rs rather than\n // reimplemented. The node owns one persistent Streamable HTTP process;\n // turns only receive its loopback URL and must never spawn a stdio copy.\n \"cua-rs\": {\n ...commonRuntimeMcpPolicy(\"cua-rs\"),\n build({ agent }) {\n return cuaRsMcpPort ? cuaRsHttpMcp(agent, cuaRsMcpPort, cuaRsMcpToken) : null;\n },\n },\n};\n\n/**\n * Locate the `cua-rs` binary, or `null` when it is not installed.\n *\n * Checked in order of specificity: an explicit env override for anyone running\n * a local build, then the installer's default target, then `/usr/local/bin`\n * for a `--bin-dir` install. PATH is deliberately not consulted -- the server\n * is spawned by a supervised host process whose PATH is not the user's shell\n * PATH, so a PATH lookup would succeed in a terminal and fail under pm2.\n */\nexport function resolveCuaRsBinary(platform: NodeJS.Platform = process.platform): string | null {\n if (platform !== \"darwin\") return null;\n const candidates = [\n envText(\"NEGOTIUM_CUA_RS_BIN\"),\n join(homedir(), \".local\", \"bin\", \"cua-rs\"),\n \"/usr/local/bin/cua-rs\",\n ].filter((p): p is string => Boolean(p));\n for (const candidate of candidates) {\n try {\n accessSync(candidate, fsConstants.X_OK);\n return candidate;\n } catch {\n // Not there, or not executable. Try the next one.\n }\n }\n return null;\n}\n\n// --- Derived catalog views ---\n\nexport type NodeMcpEntry =\n | { key: string; kind: \"http\"; port: number }\n | {\n key: string;\n kind: \"http-instance\";\n ensurePort: (instanceKey: string) => Promise<number>;\n }\n | { key: string; kind: \"stdio\"; command: string; args?: string[]; env?: Record<string, string> };\n\nlet nodeMcpEntries: NodeMcpEntry[] = [];\nconst resolvedNodeMcpPorts = new WeakMap<\n Extract<NodeMcpEntry, { kind: \"http-instance\" }>,\n Map<string, number>\n>();\n\n/** All forum-eligible MCP server names, in display order. */\nconst allForumMcpServerNames: string[] = [];\nexport const ALL_FORUM_MCP_SERVER_NAMES: readonly string[] = allForumMcpServerNames;\n\n/** Forum servers that cannot be removed via the enabled whitelist. */\nconst requiredForumMcpServers: string[] = [];\nexport const REQUIRED_FORUM_MCP_SERVERS: readonly string[] = requiredForumMcpServers;\n\n/** Forum servers that can be toggled via the enabled whitelist (not required). */\nconst optionalForumMcpServers: string[] = [];\nexport const OPTIONAL_FORUM_MCP_SERVERS: readonly string[] = optionalForumMcpServers;\n\nfunction refreshForumCatalogViews(): void {\n const { all, required, optional } = classifyForumMcpServers(MCP_CATALOG);\n const nodeNames = nodeMcpEntries.map((entry) => entry.key);\n const allWithNodeEntries = [...new Set([...all, ...nodeNames])];\n const optionalWithNodeEntries = [...new Set([...optional, ...nodeNames])];\n allForumMcpServerNames.splice(0, allForumMcpServerNames.length, ...allWithNodeEntries);\n requiredForumMcpServers.splice(0, requiredForumMcpServers.length, ...required);\n optionalForumMcpServers.splice(0, optionalForumMcpServers.length, ...optionalWithNodeEntries);\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 availableOptional = new Set(OPTIONAL_FORUM_MCP_SERVERS);\n const optionalActive = [...new Set(config.enabled)].filter((name) => availableOptional.has(name));\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\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 refreshForumCatalogViews();\n}\n\nexport function getNodeMcpServers(): readonly NodeMcpEntry[] {\n return nodeMcpEntries;\n}\n\n/** Prevent host grants from replacing node-owned MCP servers. */\nexport function isReservedRuntimeMcpServerName(name: string): boolean {\n return Object.hasOwn(MCP_CATALOG, name) || nodeMcpEntries.some((entry) => entry.key === name);\n}\n\n/** Host MCP servers that administer the workspace; only a manager room may receive them. */\nconst MANAGER_ONLY_HOST_MCP_NAMES = new Set([\"topic-admin\"]);\n\n/**\n * Why `topic` may not receive host MCP servers named `names`, or null when it\n * may. A manager room takes any of them. An ordinary room takes everything but\n * the manager administration surface, so a host can scope its own tools to a\n * room. A subagent room takes none.\n */\nexport function hostMcpGrantRefusal(\n topic: Pick<TopicDto, \"kind\" | \"isSubagent\">,\n names: readonly string[],\n): string | null {\n if (topic.kind === \"manager\") return null;\n if (topic.isSubagent) return \"hostMcpServers is not allowed for subagent topics\";\n const managerOnly = names.find((name) => MANAGER_ONLY_HOST_MCP_NAMES.has(name));\n return managerOnly ? `${managerOnly} is only allowed for manager topics` : null;\n}\n\nfunction withoutManagerOnlyHostMcpServers(\n hostMcpServers: Record<string, HostMcpServerSpec> | undefined,\n): Record<string, HostMcpServerSpec> | undefined {\n if (!hostMcpServers) return undefined;\n return Object.fromEntries(\n Object.entries(hostMcpServers).filter(([name]) => !MANAGER_ONLY_HOST_MCP_NAMES.has(name)),\n );\n}\n\nfunction mergeHostMcpServers(\n base: Record<string, unknown>,\n hostMcpServers: Record<string, HostMcpServerSpec> | undefined,\n): Record<string, unknown> {\n if (!hostMcpServers) return base;\n for (const name of Object.keys(hostMcpServers)) {\n if (Object.hasOwn(base, name) || isReservedRuntimeMcpServerName(name)) {\n throw new Error(`host MCP server name conflicts with node catalog: ${name}`);\n }\n }\n return { ...base, ...hostMcpServers };\n}\n\nfunction buildNodeMcpSpecs(\n agent: AgentKind | undefined,\n filter: (name: string) => boolean,\n ctx: Pick<RuntimeMcpBuildContext, \"topicId\" | \"userId\" | \"session\">,\n): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const entry of nodeMcpEntries) {\n if (!filter(entry.key)) continue;\n if (entry.kind === \"http\") {\n out[entry.key] = longLivedHttpMcp(agent, entry.port);\n continue;\n }\n if (entry.kind === \"http-instance\") {\n const port = resolvedNodeMcpPorts.get(entry)?.get(nodeMcpInstanceKey(ctx));\n if (port !== undefined) out[entry.key] = longLivedHttpMcp(agent, port);\n continue;\n }\n out[entry.key] = {\n command: entry.command,\n args: entry.args ?? [],\n ...(entry.env ? { env: entry.env } : {}),\n };\n }\n return out;\n}\n\nfunction nodeMcpInstanceKey(\n ctx: Pick<RuntimeMcpBuildContext, \"topicId\" | \"userId\" | \"session\">,\n): string {\n return ctx.topicId ?? `user:${ctx.userId}:session:${ctx.session}`;\n}\n\n/**\n * Lazily prepare per-topic HTTP manifest entries before a provider resolves\n * its otherwise-synchronous MCP config. One failed custom server is omitted\n * from that turn without taking down the rest of the runtime catalog.\n */\nexport async function prepareNodeMcpServersForQuery(opts: AgentQueryOptions): Promise<void> {\n if (\n opts.toolPolicy ||\n opts.sessionType === \"cron\" ||\n nodeMcpEntries.every((entry) => entry.kind !== \"http-instance\")\n ) {\n return;\n }\n\n const forum = ![\"dm\", \"ephemeral\", \"manager\"].includes(opts.sessionType ?? \"forum\");\n const enabled = opts.mcpEnabled ?? null;\n const instanceKey = nodeMcpInstanceKey({\n topicId: opts.topicId,\n userId: opts.userId || \"local\",\n session: opts.session || \"default\",\n });\n\n await Promise.all(\n nodeMcpEntries.map(async (entry) => {\n if (entry.kind !== \"http-instance\") return;\n if (forum && enabled !== null && !enabled.includes(entry.key)) return;\n let ports = resolvedNodeMcpPorts.get(entry);\n if (!ports) {\n ports = new Map();\n resolvedNodeMcpPorts.set(entry, ports);\n }\n try {\n const port = await entry.ensurePort(instanceKey);\n if (!Number.isInteger(port) || port < 1 || port > 65_535) {\n throw new Error(`invalid port ${port}`);\n }\n ports.set(instanceKey, port);\n } catch (err) {\n ports.delete(instanceKey);\n logger.warn(\n { err, key: entry.key, instanceKey },\n \"node mcp: failed to prepare instance-scoped server\",\n );\n }\n }),\n );\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, ctx));\n }\n return out;\n}\n\n/** DM session: catalog entries with `dm` scope, no whitelist. */\nexport function getDmMcpServers(opts: {\n userId: string;\n session?: string;\n topicId?: string;\n agent?: AgentKind;\n playwrightPort?: number;\n playwrightCapability?: string;\n}) {\n return buildScope(\"dm\", {\n userId: opts.userId,\n session: opts.session ?? \"dm\",\n topicId: opts.topicId,\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 actorUserId?: string;\n actorTopicScope?: ActorTopicScope;\n remoteSession?: RemoteSessionGrant;\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 actorUserId: opts.actorUserId,\n actorTopicScope: opts.actorTopicScope,\n remoteSession: opts.remoteSession,\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 actorUserId?: string;\n actorTopicScope?: ActorTopicScope;\n remoteSession?: RemoteSessionGrant;\n vaultUserId?: 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 threadRootId?: string;\n depth?: number;\n enabled?: string[] | null;\n extra?: Record<string, unknown>;\n silent?: boolean;\n peerBridge?: PeerRuntimeBridgeContext;\n}) {\n const {\n userId,\n actorUserId,\n actorTopicScope,\n remoteSession,\n vaultUserId,\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 threadRootId,\n peerBridge,\n } = opts;\n\n const filter = (name: string) => {\n if (silent && (name === \"task\" || name === \"decision\")) 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 actorUserId,\n actorTopicScope,\n remoteSession,\n vaultUserId,\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 threadRootId,\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 hideProviderIntrospectionForOtium(\n 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 opts.topicId,\n );\n }\n if (opts.sessionType === \"dm\" || opts.sessionType === \"ephemeral\") {\n return getDmMcpServers({\n userId: opts.userId || \"local\",\n session: opts.session,\n topicId: opts.topicId,\n agent: opts.agent,\n playwrightPort: opts.playwrightPort,\n playwrightCapability: opts.playwrightCapability,\n });\n }\n if (opts.sessionType === \"manager\") {\n return hideProviderIntrospectionForOtium(\n mergeHostMcpServers(\n getManagerMcpServers({\n userId: opts.userId || \"local\",\n actorUserId: opts.actorUserId,\n actorTopicScope: opts.actorTopicScope,\n remoteSession: opts.remoteSession,\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 opts.hostMcpServers,\n ),\n opts.topicId,\n );\n }\n return hideProviderIntrospectionForOtium(\n mergeHostMcpServers(\n getForumMcpServers({\n userId: opts.userId || \"local\",\n actorUserId: opts.actorUserId,\n actorTopicScope: opts.actorTopicScope,\n remoteSession: opts.remoteSession,\n vaultUserId: opts.vaultUserId,\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 threadRootId: opts.threadRootId,\n depth: opts.depth,\n enabled: opts.mcpEnabled,\n extra: opts.mcpExtra,\n silent: opts.silent,\n peerBridge: opts.peerBridge,\n }),\n withoutManagerOnlyHostMcpServers(opts.hostMcpServers),\n ),\n opts.topicId,\n );\n}\n\nfunction hideProviderIntrospectionForOtium(\n servers: Record<string, unknown>,\n topicId: string | undefined,\n): Record<string, unknown> {\n if (!topicId || getTopic(topicId)?.surface !== \"otium\") return servers;\n const filtered = { ...servers };\n delete filtered[\"agent-health\"];\n delete filtered[\"token-stats\"];\n return filtered;\n}\n",
|
|
37
37
|
"import { chmodSync, mkdirSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { VAULT_MASTER_KEY } from \"#platform/config\";\nimport { closeDatabase, Database } from \"#storage/sqlite\";\nimport { resolveStorageDataDir } from \"#storage/storage-host\";\nimport { decryptVaultValue, encryptVaultValue, isEncryptedVaultValue } 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 /** Prior keys rows may still be encrypted under; migrated onto `masterKey`. */\n legacyMasterKeys?: readonly 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) {\n // `resolveStorageDataDir()`, not the import-time `DATA_DIR` constant: an\n // embedding host configures its data directory during bootstrap, and any\n // vault access that happens before `configureVaultStorage()` runs would\n // otherwise pin the vault to Negotium's own state directory for the life of\n // the process — silently, since both paths are valid and writable.\n vaultDb = openVaultDatabase(resolveStorageDataDir());\n }\n return vaultDb;\n}\n\n/** Re-encrypts rows only readable under `legacyKeys` onto `targetKey`, atomically. */\nfunction migrateLegacyMasterKeys(\n database: VaultDatabase,\n targetKey: string,\n legacyKeys: readonly string[],\n): void {\n if (legacyKeys.length === 0) return;\n const rows = database.prepare(\"SELECT user_id, key, value FROM vault\").all() as {\n user_id: string;\n key: string;\n value: string;\n }[];\n\n const rewrites: { userId: string; key: string; newValue: string }[] = [];\n for (const row of rows) {\n if (!isEncryptedVaultValue(row.value)) continue; // plaintext rows are handled by decryptRow()\n try {\n decryptVaultValue(row.user_id, row.key, row.value, targetKey);\n continue; // already readable under the target key\n } catch {\n // fall through to legacy recovery below\n }\n let recovered: string | undefined;\n for (const legacyKey of legacyKeys) {\n try {\n recovered = decryptVaultValue(row.user_id, row.key, row.value, legacyKey).value;\n break;\n } catch {\n // try the next legacy key\n }\n }\n if (recovered === undefined) {\n throw new Error(\n `vault migration: row \"${row.key}\" cannot be authenticated with the target master key or any legacy key`,\n );\n }\n rewrites.push({\n userId: row.user_id,\n key: row.key,\n newValue: encryptVaultValue(row.user_id, row.key, recovered, targetKey),\n });\n }\n if (rewrites.length === 0) return;\n\n database.exec(\"BEGIN IMMEDIATE\");\n try {\n const update = database.prepare(\"UPDATE vault SET value = ? WHERE user_id = ? AND key = ?\");\n for (const rewrite of rewrites) update.run(rewrite.newValue, rewrite.userId, rewrite.key);\n database.exec(\"COMMIT\");\n } catch (error) {\n database.exec(\"ROLLBACK\");\n throw error;\n }\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 =\n options.database ?? openVaultDatabase(options.dataDir ?? resolveStorageDataDir());\n const targetKey = options.masterKey ?? VAULT_MASTER_KEY;\n try {\n if (options.database) initializeVaultDatabase(configuredDb);\n if (options.legacyMasterKeys && options.legacyMasterKeys.length > 0) {\n migrateLegacyMasterKeys(configuredDb, targetKey, options.legacyMasterKeys);\n }\n } catch (error) {\n // A failed migration must not leak the connection this call opened: there\n // is no dispose to hand back, so nothing else can ever close it. Only a\n // database we opened ourselves is ours to close — an injected one is\n // borrowed.\n if (!options.database) {\n closeDatabase(configuredDb as VaultDatabase & { close(throwOnError?: boolean): void });\n }\n throw error;\n }\n vaultDb = configuredDb;\n vaultMasterKey = targetKey;\n let disposed = false;\n return () => {\n if (disposed) return;\n disposed = true;\n if (!options.database && \"close\" in configuredDb) {\n closeDatabase(configuredDb as VaultDatabase & { close(throwOnError?: boolean): void });\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",
|
|
38
38
|
"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",
|
|
39
39
|
"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",
|
|
@@ -41,7 +41,7 @@
|
|
|
41
41
|
"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",
|
|
42
42
|
"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"
|
|
43
43
|
],
|
|
44
|
-
"mappings": ";;;;AASA,sBAAS;AACT,oBAAS;;;ACVT;AACA;AACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AASA;AACA;AACA;AACA;;;ACKO,IAAM,mBAAyC,CAAC,WAAW,UAAU,OAAO;AAE5E,SAAS,WAAW,CAAC,OAAoC;AAAA,EAC9D,OAAO,OAAO,UAAU,YAAa,iBAAuC,SAAS,KAAK;AAAA;AAiBrF,IAAM,uBAAuB,CAAC,OAAO,UAAU,QAAQ,SAAS,KAAK;AACrE,IAAM,sBAAsB,CAAC,OAAO,UAAU,QAAQ,SAAS,KAAK;AACpE,IAAM,wBAAwB,CAAC,OAAO,UAAU,QAAQ,SAAS,KAAK;AAatE,IAAM,gBAAgB;AAAA,EAC3B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;;;ACvDO,SAAS,WAAW,CAAC,KAAyB,KAAiC;AAAA,EACpF,MAAM,QAAQ,IAAI,MAAM,KAAK;AAAA,EAC7B,OAAO,SAAS;AAAA;AAWX,SAAS,oBAAoB,CAAC,MAA0B,QAAQ,KAAgB;AAAA,EACrF,MAAM,QAAQ,YAAY,KAAK,gBAAgB,KAAK,YAAY,KAAK,eAAe;AAAA,EACpF,OAAO,YAAY,KAAK,IAAI,QAAQ;AAAA;AAG/B,SAAS,gBAAgB,CAAC,OAA2B,UAA0B;AAAA,EACpF,IAAI,CAAC;AAAA,IAAO,OAAO;AAAA,EACnB,MAAM,OAAO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