negotium 0.2.19 → 0.2.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/dist/agent-helpers.js +573 -593
  2. package/dist/agent-helpers.js.map +17 -17
  3. package/dist/background-bash.js +3 -2
  4. package/dist/background-bash.js.map +3 -3
  5. package/dist/browser-runtime.js +76 -36
  6. package/dist/browser-runtime.js.map +6 -6
  7. package/dist/canonical-mcp-bridge.js +1 -1
  8. package/dist/{chunk-fc58cqry.js → chunk-rhp26p2c.js} +171 -26
  9. package/dist/{chunk-fc58cqry.js.map → chunk-rhp26p2c.js.map} +6 -5
  10. package/dist/{chunk-r0xs3t81.js → chunk-s2gez3wg.js} +18 -3
  11. package/dist/{chunk-r0xs3t81.js.map → chunk-s2gez3wg.js.map} +2 -2
  12. package/dist/hosted-agent.js +185 -54
  13. package/dist/hosted-agent.js.map +7 -6
  14. package/dist/main.js +1209 -1114
  15. package/dist/main.js.map +25 -25
  16. package/dist/mcp-catalog.js.map +1 -1
  17. package/dist/mcp-factories.js +526 -540
  18. package/dist/mcp-factories.js.map +17 -17
  19. package/dist/outbox.js.map +1 -1
  20. package/dist/platform-runtime.js.map +1 -1
  21. package/dist/prompts.js +3 -2
  22. package/dist/prompts.js.map +3 -3
  23. package/dist/query-runtime.js +63 -26
  24. package/dist/query-runtime.js.map +4 -4
  25. package/dist/registry.js +4 -3
  26. package/dist/registry.js.map +3 -3
  27. package/dist/rollout.js +1 -1
  28. package/dist/runtime/src/agents/archiver.ts +3 -2
  29. package/dist/runtime/src/application/switch-topic-access-mode.ts +81 -8
  30. package/dist/runtime/src/bus.ts +19 -2
  31. package/dist/runtime/src/mcp/session-comm/runtime.ts +16 -0
  32. package/dist/runtime/src/platform/config.ts +13 -1
  33. package/dist/runtime/src/runtime/ask-callbacks.ts +19 -11
  34. package/dist/runtime/src/runtime/background-sessions.ts +9 -7
  35. package/dist/runtime/src/runtime/visual-store.ts +31 -23
  36. package/dist/runtime/src/storage/api-topics.ts +26 -0
  37. package/dist/runtime/src/storage/browser-profiles.ts +16 -8
  38. package/dist/runtime/src/storage/runtime-events.ts +30 -20
  39. package/dist/runtime/src/storage/runtime-gateway-submissions.ts +24 -16
  40. package/dist/runtime/src/storage/runtime-turn-requests.ts +9 -1
  41. package/dist/runtime/src/storage/self-schedules.ts +32 -24
  42. package/dist/runtime/src/storage/storage-host.ts +105 -43
  43. package/dist/runtime/src/storage/vault.ts +12 -3
  44. package/dist/runtime/src/version.ts +1 -1
  45. package/dist/runtime-helpers.js +63 -26
  46. package/dist/runtime-helpers.js.map +4 -4
  47. package/dist/sqlite.js +17 -1
  48. package/dist/sqlite.js.map +2 -2
  49. package/dist/storage.js +92 -46
  50. package/dist/storage.js.map +4 -4
  51. package/dist/types/packages/core/src/storage/api-topics.d.ts +15 -0
  52. package/dist/types/packages/core/src/storage/storage-host.d.ts +10 -0
  53. package/dist/types/packages/core/src/version.d.ts +1 -1
  54. package/dist/vault.js +156 -10
  55. package/dist/vault.js.map +6 -5
  56. package/package.json +1 -1
@@ -6,12 +6,12 @@
6
6
  "import { existsSync, unlinkSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { forkCodexSession } from \"#agents/codex-app-server\";\nimport type { AgentRegistry, AgentRegistryOperations } from \"#agents/contracts\";\nimport { hostedCodexHomePath } from \"#agents/execution-host\";\nimport { writeCodexRollout } from \"#agents/rollout/codex\";\nimport { logger } from \"#platform/logger\";\nimport { CODEX_EFFORT_VALUES, type EffortLevel } from \"#types\";\n\nconst VALID_EFFORTS = new Set<EffortLevel>(CODEX_EFFORT_VALUES);\n\n// Codex CLI's own empirical default is gpt-5.6-sol (`codex exec` 2026-07-10 →\n// \"model: gpt-5.6-sol\"), but we deliberately default to gpt-5.6-luna — the\n// cheapest/fastest GPT-5.6 tier — for a general always-on assistant where most\n// queries are light. Heavier work escalates to terra/sol via set_model. This\n// value is passed explicitly to the SDK (see event-processor resolveDefaultModel),\n// so the footer and the actual model stay in sync.\nexport const codexRegistry: AgentRegistry = {\n kind: \"codex\",\n defaultModel: \"gpt-5.6-luna\",\n // defaultEffort intentionally omitted — Codex SDK treats absence as\n // \"reasoning off\". Setting \"high\"/etc. would silently flip on reasoning.\n\n expandModelAlias(s) {\n return s;\n },\n\n validateModel(s) {\n // Codex doesn't publish a closed model list and OpenAI ships new IDs\n // (gpt-5.6-sol, gpt-5.6-terra, gpt-5.6-luna, o3, ...) frequently. Best-effort: accept any\n // non-empty string. Bad IDs surface at SDK call time with a clear error.\n return typeof s === \"string\" && s.length > 0;\n },\n\n validEfforts: CODEX_EFFORT_VALUES,\n validateEffort(s) {\n // GPT-5.6 accepts low/medium/high/xhigh/max; 'minimal'\n // was removed because the Codex API rejects it when default tools\n // (image_gen, web_search) are active.\n return VALID_EFFORTS.has(s);\n },\n\n footerLabel(model, effort) {\n // Codex omits effort to mean \"reasoning off\". Show `(off)` explicitly so\n // the user can distinguish from claude (which always has a default).\n return `${model} · ${effort ?? \"(off)\"}`;\n },\n};\n\nexport const codexRegistryOperations: AgentRegistryOperations = {\n writeRollout(opts) {\n // Codex SDK exposes the resume key as `threadId`; AgentRegistry unifies\n // the name to `sessionId` so callers don't branch on agent.\n // `reuseSessionId` (if any) is forwarded as `threadId` so claude→codex→claude\n // round-trips also keep one continuous codex thread instead of orphaning a\n // fresh uuidv7 on every switch.\n const { threadId, rolloutPath } = writeCodexRollout({\n cwd: opts.cwd,\n entries: opts.entries,\n model: opts.model ?? codexRegistry.defaultModel,\n ...(opts.effort ? { effort: opts.effort } : {}),\n ...(opts.reuseSessionId ? { threadId: opts.reuseSessionId } : {}),\n });\n return { sessionId: threadId, rolloutPath };\n },\n\n // The TypeScript SDK does not expose forking yet, but the bundled Codex App\n // Server does. Native thread/fork preserves the provider's stored prefix,\n // including tool structure, which gives prompt caching the best chance to\n // reuse the parent context. Callers retain unified-log synthesis as fallback.\n async forkSession({ parentSessionId }) {\n return await forkCodexSession(parentSessionId);\n },\n\n // Codex stores rollouts at `~/.codex/sessions/<YYYY>/<MM>/<DD>/rollout-<ts>-<threadId>.jsonl`.\n // The date prefix is unknown at cleanup time (it's the *original* write\n // timestamp, not \"now\"), so we glob across the whole sessions tree by\n // threadId suffix. With at most a few thousand files in active use this\n // is well under a millisecond on a warm filesystem.\n async cleanupRollouts({ sessionIds }) {\n if (sessionIds.length === 0) return;\n const sessionsDir = join(hostedCodexHomePath(), \"sessions\");\n // No sessions directory means there are no provider rollouts left to remove.\n if (!existsSync(sessionsDir)) return;\n const failures: unknown[] = [];\n // One Glob per threadId so a single corrupt entry can't poison the rest.\n // Bun.Glob's `scan` yields paths relative to its base dir.\n for (const tid of sessionIds) {\n try {\n const glob = new Bun.Glob(`**/rollout-*-${tid}.jsonl`);\n for await (const rel of glob.scan({ cwd: sessionsDir, onlyFiles: true })) {\n const path = join(sessionsDir, rel);\n try {\n unlinkSync(path);\n } catch (e) {\n if ((e as NodeJS.ErrnoException)?.code !== \"ENOENT\") {\n logger.warn({ err: e, path }, \"codex cleanupRollouts: unlink failed\");\n failures.push(e);\n }\n }\n }\n } catch (e) {\n logger.warn({ err: e, threadId: tid }, \"codex cleanupRollouts: scan failed\");\n failures.push(e);\n }\n }\n if (failures.length > 0) {\n throw new AggregateError(failures, \"codex cleanupRollouts failed\");\n }\n },\n};\n",
7
7
  "import { type ChildProcessWithoutNullStreams, spawn } from \"node:child_process\";\nimport { codexCliScriptPath } from \"#agents/codex-native-multi-agent\";\nimport { hostedCodexHomePath } from \"#agents/execution-host\";\nimport { latestCodexRolloutPath } from \"#agents/rollout/codex\";\nimport { NEGOTIUM_VERSION } from \"#version\";\n\ninterface CodexAppServerForkResult {\n forkId: string;\n rolloutPath: string;\n}\n\ninterface CodexAppServerForkHost {\n spawnServer(): ChildProcessWithoutNullStreams;\n findRolloutPath(threadId: string): string | undefined;\n timeoutMs: number;\n}\n\ntype JsonRpcResponse = {\n id?: number;\n result?: { thread?: { id?: unknown } };\n error?: { message?: unknown };\n};\n\nexport function createCodexAppServerForker(host: CodexAppServerForkHost) {\n return async (parentThreadId: string): Promise<CodexAppServerForkResult> => {\n const child = host.spawnServer();\n\n return await new Promise<CodexAppServerForkResult>((resolve, reject) => {\n let settled = false;\n let stdoutBuffer = \"\";\n let stderr = \"\";\n const timer = setTimeout(\n () => finish(new Error(\"Codex thread fork timed out\")),\n host.timeoutMs,\n );\n\n const finish = (error?: Error, result?: CodexAppServerForkResult) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n try {\n child.stdin.end();\n child.kill();\n } catch {\n // The app server may already have exited after stdin closed.\n }\n if (error) reject(error);\n else if (result) resolve(result);\n else reject(new Error(\"Codex thread fork returned no result\"));\n };\n\n const send = (message: Record<string, unknown>) => {\n child.stdin.write(`${JSON.stringify(message)}\\n`);\n };\n\n child.stderr.on(\"data\", (chunk) => {\n if (stderr.length < 8_192) stderr += String(chunk);\n });\n child.on(\"error\", (error) => finish(error));\n child.on(\"exit\", (code, signal) => {\n if (settled) return;\n const detail = signal ? `signal ${signal}` : `code ${code ?? 1}`;\n finish(\n new Error(\n `Codex app server exited with ${detail}${stderr.trim() ? `: ${stderr.trim()}` : \"\"}`,\n ),\n );\n });\n child.stdout.on(\"data\", (chunk) => {\n stdoutBuffer += String(chunk);\n for (;;) {\n const newline = stdoutBuffer.indexOf(\"\\n\");\n if (newline < 0) break;\n const line = stdoutBuffer.slice(0, newline);\n stdoutBuffer = stdoutBuffer.slice(newline + 1);\n let message: JsonRpcResponse;\n try {\n message = JSON.parse(line) as JsonRpcResponse;\n } catch {\n continue;\n }\n\n if (message.id === 1) {\n if (message.error) {\n finish(new Error(String(message.error.message || \"Codex initialization failed\")));\n return;\n }\n send({ method: \"initialized\" });\n send({ id: 2, method: \"thread/fork\", params: { threadId: parentThreadId } });\n continue;\n }\n if (message.id !== 2) continue;\n if (message.error) {\n finish(new Error(String(message.error.message || \"Codex thread fork failed\")));\n return;\n }\n const forkId = message.result?.thread?.id;\n if (typeof forkId !== \"string\" || !forkId) {\n finish(new Error(\"Codex thread fork returned no thread id\"));\n return;\n }\n const rolloutPath = host.findRolloutPath(forkId);\n if (!rolloutPath) {\n finish(new Error(`Codex thread fork rollout was not found for ${forkId}`));\n return;\n }\n finish(undefined, { forkId, rolloutPath });\n return;\n }\n });\n\n send({\n id: 1,\n method: \"initialize\",\n params: {\n clientInfo: { name: \"negotium\", version: NEGOTIUM_VERSION },\n },\n });\n });\n };\n}\n\nconst forkCodexThread = createCodexAppServerForker({\n spawnServer() {\n return spawn(process.execPath, [codexCliScriptPath(), \"app-server\", \"--stdio\"], {\n env: { ...process.env, CODEX_HOME: hostedCodexHomePath() },\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n });\n },\n findRolloutPath: latestCodexRolloutPath,\n timeoutMs: 15_000,\n});\n\nexport async function forkCodexSession(parentThreadId: string): Promise<CodexAppServerForkResult> {\n return await forkCodexThread(parentThreadId);\n}\n",
8
8
  "import { spawn } from \"node:child_process\";\nimport { randomUUID } from \"node:crypto\";\nimport {\n chmodSync,\n copyFileSync,\n existsSync,\n mkdtempSync,\n readFileSync,\n renameSync,\n rmSync,\n unlinkSync,\n writeFileSync,\n} from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { tmpdir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport { NEGOTIUM_VERSION } from \"#version\";\n\ntype CodexModel = Record<string, unknown>;\ntype CodexModelCache = {\n client_version?: unknown;\n models?: unknown;\n};\n\nconst moduleRequire = createRequire(import.meta.url);\nconst codexSdkPackagePath = moduleRequire.resolve(\"@openai/codex-sdk/package.json\");\nconst codexSdkRequire = createRequire(codexSdkPackagePath);\nconst bundledCodexPackagePath = codexSdkRequire.resolve(\"@openai/codex/package.json\");\n\nfunction readPackageVersion(packageJsonPath: string): string {\n const parsed = JSON.parse(readFileSync(packageJsonPath, \"utf8\")) as { version?: unknown };\n if (typeof parsed.version !== \"string\" || !parsed.version.trim()) {\n throw new Error(`Codex package has no valid version: ${packageJsonPath}`);\n }\n return parsed.version;\n}\n\nexport const BUNDLED_CODEX_VERSION = readPackageVersion(bundledCodexPackagePath);\nconst SAFE_BUNDLED_CODEX_VERSION = BUNDLED_CODEX_VERSION.replace(/[^a-zA-Z0-9._-]/g, \"_\");\nconst NEGOTIUM_MODEL_CACHE = `negotium-models-cache-${SAFE_BUNDLED_CODEX_VERSION}.json`;\nconst NEGOTIUM_MODEL_CATALOG = `negotium-model-catalog-${SAFE_BUNDLED_CODEX_VERSION}.json`;\n\nexport function codexCliScriptPath(): string {\n return join(dirname(bundledCodexPackagePath), \"bin\", \"codex.js\");\n}\n\nfunction parseCodexModelCache(contents: string, sourcePath: string): CodexModelCache {\n let parsed: CodexModelCache;\n try {\n parsed = JSON.parse(contents) as CodexModelCache;\n } catch (error) {\n throw new Error(`Codex model cache is invalid JSON: ${sourcePath}`, { cause: error });\n }\n if (!Array.isArray(parsed.models) || parsed.models.length === 0) {\n throw new Error(`Codex model cache has no models: ${sourcePath}`);\n }\n return parsed;\n}\n\nfunction readCodexModelCache(cachePath: string): {\n contents: string;\n parsed: CodexModelCache;\n} {\n const contents = readFileSync(cachePath, \"utf8\");\n return { contents, parsed: parseCodexModelCache(contents, cachePath) };\n}\n\nfunction readCompatibleCodexModelCache(cachePath: string): {\n contents: string;\n parsed: CodexModelCache;\n} {\n const cache = readCodexModelCache(cachePath);\n if (cache.parsed.client_version !== BUNDLED_CODEX_VERSION) {\n const found =\n typeof cache.parsed.client_version === \"string\"\n ? cache.parsed.client_version\n : \"missing or invalid\";\n throw new Error(\n `Codex model cache version ${found} does not match Negotium's bundled Codex ${BUNDLED_CODEX_VERSION}: ${cachePath}`,\n );\n }\n return cache;\n}\n\nfunction writePrivateFileAtomic(path: string, contents: string): void {\n if (existsSync(path) && readFileSync(path, \"utf8\") === contents) return;\n\n const tempPath = `${path}.${process.pid}.${randomUUID()}.tmp`;\n try {\n writeFileSync(tempPath, contents, { encoding: \"utf8\", mode: 0o600 });\n renameSync(tempPath, path);\n chmodSync(path, 0o600);\n } finally {\n try {\n unlinkSync(tempPath);\n } catch {\n // renameSync normally consumed the temporary file.\n }\n }\n}\n\nexport function bundledCodexModelCachePath(authFilePath: string): string {\n return join(dirname(authFilePath), NEGOTIUM_MODEL_CACHE);\n}\n\nasync function bootstrapCodexModelCache(codexHome: string, cachePath: string): Promise<void> {\n const child = spawn(process.execPath, [codexCliScriptPath(), \"app-server\", \"--stdio\"], {\n env: { ...process.env, CODEX_HOME: codexHome },\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n });\n\n await new Promise<void>((resolve, reject) => {\n let settled = false;\n let stdoutBuffer = \"\";\n let stderr = \"\";\n const timer = setTimeout(\n () => finish(new Error(\"timed out while refreshing the Codex model catalog\")),\n 15_000,\n );\n\n const finish = (error?: Error) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n try {\n child.stdin.end();\n child.kill();\n } catch {\n // The app server may already have exited after stdin closed.\n }\n if (error) reject(error);\n else if (!existsSync(cachePath)) reject(new Error(\"Codex did not create its model cache\"));\n else resolve();\n };\n\n const send = (message: Record<string, unknown>) => {\n child.stdin.write(`${JSON.stringify(message)}\\n`);\n };\n\n child.stderr.on(\"data\", (chunk) => {\n if (stderr.length < 4_096) stderr += String(chunk);\n });\n child.on(\"error\", (error) => finish(error));\n child.on(\"exit\", (code, signal) => {\n if (!settled) {\n finish(\n new Error(\n `Codex model catalog refresh exited with ${signal ? `signal ${signal}` : `code ${code ?? 1}`}${stderr.trim() ? `: ${stderr.trim()}` : \"\"}`,\n ),\n );\n }\n });\n child.stdout.on(\"data\", (chunk) => {\n stdoutBuffer += String(chunk);\n for (;;) {\n const newline = stdoutBuffer.indexOf(\"\\n\");\n if (newline < 0) break;\n const line = stdoutBuffer.slice(0, newline);\n stdoutBuffer = stdoutBuffer.slice(newline + 1);\n let message: { id?: number; error?: { message?: string } };\n try {\n message = JSON.parse(line) as typeof message;\n } catch {\n continue;\n }\n if (message.id === 1) {\n if (message.error) {\n finish(new Error(message.error.message || \"Codex initialization failed\"));\n return;\n }\n send({ method: \"initialized\" });\n send({ id: 2, method: \"model/list\", params: { includeHidden: true } });\n } else if (message.id === 2) {\n if (message.error) {\n finish(new Error(message.error.message || \"Codex model listing failed\"));\n } else {\n finish();\n }\n return;\n }\n }\n });\n\n send({\n id: 1,\n method: \"initialize\",\n params: {\n clientInfo: { name: \"negotium\", version: NEGOTIUM_VERSION },\n capabilities: { experimentalApi: true },\n },\n });\n });\n}\n\nasync function bootstrapIsolatedCodexModelCache(\n authFilePath: string,\n bootstrap: (codexHome: string, cachePath: string) => Promise<void>,\n): Promise<string> {\n const sourceHome = dirname(authFilePath);\n const isolatedHome = mkdtempSync(join(tmpdir(), \"negotium-codex-models-\"));\n const isolatedCachePath = join(isolatedHome, \"models_cache.json\");\n\n try {\n const isolatedAuthPath = join(isolatedHome, \"auth.json\");\n copyFileSync(authFilePath, isolatedAuthPath);\n chmodSync(isolatedAuthPath, 0o600);\n\n // Preserve custom provider configuration while keeping the bundled CLI's\n // cache write completely outside the user's shared CODEX_HOME.\n const sourceConfigPath = join(sourceHome, \"config.toml\");\n if (existsSync(sourceConfigPath)) {\n const isolatedConfigPath = join(isolatedHome, \"config.toml\");\n copyFileSync(sourceConfigPath, isolatedConfigPath);\n chmodSync(isolatedConfigPath, 0o600);\n }\n\n await bootstrap(isolatedHome, isolatedCachePath);\n return readCompatibleCodexModelCache(isolatedCachePath).contents;\n } finally {\n rmSync(isolatedHome, { recursive: true, force: true });\n }\n}\n\nexport async function ensureCodexModelCache(\n authFilePath: string,\n bootstrap: (codexHome: string, cachePath: string) => Promise<void> = bootstrapCodexModelCache,\n): Promise<string> {\n const codexHome = dirname(authFilePath);\n const configuredCachePath = process.env.NEGOTIUM_CODEX_MODELS_CACHE_FILE;\n if (configuredCachePath) {\n if (!existsSync(configuredCachePath)) {\n throw new Error(`Configured Codex model cache does not exist: ${configuredCachePath}`);\n }\n readCompatibleCodexModelCache(configuredCachePath);\n return configuredCachePath;\n }\n\n // The global Codex CLI owns models_cache.json and may update it to a schema\n // newer than the SDK bundled by Negotium. Snapshot a cache generated for our\n // exact bundled version so later global CLI updates cannot break turns.\n const bundledCachePath = bundledCodexModelCachePath(authFilePath);\n const sharedCachePath = join(codexHome, \"models_cache.json\");\n if (existsSync(sharedCachePath)) {\n try {\n const shared = readCompatibleCodexModelCache(sharedCachePath);\n // Keep model metadata fresh while the global CLI remains compatible.\n writePrivateFileAtomic(bundledCachePath, shared.contents);\n return bundledCachePath;\n } catch {\n // A compatible private snapshot is safer than failing because another\n // process briefly exposed an incomplete shared-cache write.\n }\n }\n\n if (existsSync(bundledCachePath)) {\n try {\n readCompatibleCodexModelCache(bundledCachePath);\n return bundledCachePath;\n } catch {\n // Re-bootstrap below instead of passing a corrupt or version-mismatched\n // private snapshot into this SDK version.\n }\n }\n\n const refreshedContents = await bootstrapIsolatedCodexModelCache(authFilePath, bootstrap);\n writePrivateFileAtomic(bundledCachePath, refreshedContents);\n return bundledCachePath;\n}\n\n/**\n * Codex can resolve model metadata before `features.multi_agent=false`, so a\n * model-advertised v1/v2 value may still register native collaboration tools.\n * Feed Codex an authoritative copy of its own catalog with only that field\n * disabled. Runtime MCP delegation remains available independently.\n */\nexport function writeCodexCatalogWithNativeMultiAgentDisabled(\n authFilePath: string,\n sourcePath: string,\n): string {\n const codexHome = dirname(authFilePath);\n const outputPath = join(codexHome, NEGOTIUM_MODEL_CATALOG);\n\n const parsed = readCodexModelCache(sourcePath).parsed;\n\n const models = (parsed.models as unknown[]).map((model, index): CodexModel => {\n if (!model || typeof model !== \"object\" || Array.isArray(model)) {\n throw new Error(`Codex model cache entry ${index} is invalid: ${sourcePath}`);\n }\n return { ...(model as CodexModel), multi_agent_version: \"disabled\" };\n });\n const contents = `${JSON.stringify({ models }, null, 2)}\\n`;\n writePrivateFileAtomic(outputPath, contents);\n return outputPath;\n}\n",
9
- "export const NEGOTIUM_VERSION = \"0.2.19\";\n",
9
+ "export const NEGOTIUM_VERSION = \"0.2.21\";\n",
10
10
  "import { randomUUID } from \"node:crypto\";\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join, resolve } from \"node:path\";\nimport type { AgentRegistry, AgentRegistryOperations } from \"#agents/contracts\";\nimport { assertUuidLike, ensureCwdExists, extractChatPairs } from \"#agents/rollout/shared\";\nimport { logger } from \"#platform/logger\";\nimport { MAESTRO_EFFORT_VALUES } from \"#types\";\n\nconst ALIAS_MAP: Record<string, string> = {\n \"deepseek-pro\": \"deepseek-v4-pro\",\n // \"deepseek-flash\" was disabled in 0.1.25 because DeepSeek had retired its\n // old flash model. \"DeepSeek-V4-Flash-0731\" (released 2026-07-31) is an\n // unrelated, currently-live model reusing a similar name — verified with a\n // live API call before re-enabling this alias.\n \"deepseek-flash\": \"deepseek-v4-flash\",\n kimi: \"kimi-k3\",\n \"kimi-pro\": \"kimi-k3\",\n \"kimi-code\": \"kimi-k2.7-code\",\n};\nconst VALID_MODELS = new Set([...Object.keys(ALIAS_MAP), ...Object.values(ALIAS_MAP)]);\nconst VALID_EFFORTS = new Set(MAESTRO_EFFORT_VALUES);\n\nexport const maestroRegistry: AgentRegistry = {\n kind: \"maestro\",\n defaultModel: \"deepseek-pro\",\n defaultEffort: \"medium\",\n expandModelAlias(model) {\n return ALIAS_MAP[model] ?? model;\n },\n validateModel(model) {\n return VALID_MODELS.has(model);\n },\n validEfforts: MAESTRO_EFFORT_VALUES,\n validateEffort(effort) {\n return VALID_EFFORTS.has(effort);\n },\n footerLabel(model, effort) {\n return effort ? `${model} · ${effort}` : model;\n },\n};\n\nfunction maestroSessionsDir(): string {\n return join(\n process.env.MAESTRO_DATA_DIR\n ? resolve(process.env.MAESTRO_DATA_DIR)\n : join(homedir(), \".maestro\"),\n \"sessions\",\n );\n}\n\nfunction maestroSessionPath(sessionId: string): string {\n return join(maestroSessionsDir(), `${sessionId}.jsonl`);\n}\n\nfunction maestroActiveSessionPath(sessionId: string): string {\n return join(maestroSessionsDir(), `${sessionId}.active.jsonl`);\n}\n\nfunction existingCreatedAt(path: string): string | undefined {\n if (!existsSync(path)) return undefined;\n try {\n const firstLine = readFileSync(path, \"utf8\").split(\"\\n\", 1)[0];\n const parsed = JSON.parse(firstLine) as { _meta?: { createdAt?: unknown } };\n return typeof parsed._meta?.createdAt === \"string\" ? parsed._meta.createdAt : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Placeholder for a synthesized turn whose text is blank.\n *\n * Moonshot (Kimi) hard-rejects the *whole* request when any history message has\n * empty content — `Kimi API 400: the message at position N with role 'user'\n * must not be empty` (verified against the live API, kimi-k3). DeepSeek's\n * validator is laxer today but the same shape is not worth relying on.\n *\n * maestro-agent-sdk 0.2.1 drops empty assistant slots, but only in the\n * *content-block* form (`content: []`); the pair encoder below writes plain\n * strings, and `content: \"\"` still reaches the wire and 400s. Blank sides are\n * reachable here from real conversations — an attachment-only user submission\n * records a `user_message` with `content: \"\"`, and `renderUserPromptBatch`\n * passes it through verbatim — so the synthesized session must not contain one.\n *\n * We substitute rather than drop: dropping a pair would silently delete a turn\n * from the historical narrative the next agent reads, while a one-line marker\n * keeps the turn boundary and tells the model why the slot is thin.\n */\nconst BLANK_TURN_PLACEHOLDER = \"(no text content in this turn)\";\n\nfunction nonEmptyTurnText(text: string): string {\n return text.trim().length > 0 ? text : BLANK_TURN_PLACEHOLDER;\n}\n\nfunction writeRollout(options: Parameters<AgentRegistryOperations[\"writeRollout\"]>[0]) {\n const sessionId = options.reuseSessionId ?? randomUUID();\n assertUuidLike(\"sessionId\", sessionId);\n ensureCwdExists(options.cwd);\n const path = maestroSessionPath(sessionId);\n mkdirSync(maestroSessionsDir(), { recursive: true });\n const messages = extractChatPairs(options.entries).flatMap((pair) => [\n { role: \"user\", content: nonEmptyTurnText(pair.userText) },\n { role: \"assistant\", content: nonEmptyTurnText(pair.assistantText) },\n ]);\n const lines = [\n {\n _meta: {\n version: 1,\n cwd: options.cwd,\n createdAt: existingCreatedAt(path) ?? new Date().toISOString(),\n // Deliberately a literal, not the SDK's `MAESTRO_SDK_VERSION`: this\n // module must not statically import maestro-agent-sdk (asserted by\n // tests/core/daemon-import-boundaries.test.ts — the SDK stays off the\n // daemon startup path). The value names the session *format* version\n // this encoder targets, which is what a reader of the header needs.\n sdkVersion: \"0.2.0\",\n },\n },\n ...messages,\n ];\n writeFileSync(path, `${lines.map((line) => JSON.stringify(line)).join(\"\\n\")}\\n`, {\n mode: 0o600,\n });\n return { sessionId, rolloutPath: path };\n}\n\nexport const maestroRegistryOperations: AgentRegistryOperations = {\n writeRollout(options) {\n return writeRollout(options);\n },\n async forkSession(options) {\n // Fork the full raw history while preserving the compacted working view.\n // A compacted parent that cannot copy its active projection is not a usable\n // cache-preserving fork, so let the caller fall back to bounded synthesis.\n const { deleteMaestroSession, forkSessionAt, loadRawMaestroSession } = await import(\n \"maestro-agent-sdk\"\n );\n const parentMessages = loadRawMaestroSession(options.parentSessionId);\n if (!parentMessages) {\n throw new Error(`Maestro parent session not found: ${options.parentSessionId}`);\n }\n const parentHasActiveProjection = existsSync(maestroActiveSessionPath(options.parentSessionId));\n const fork = forkSessionAt({\n parentSessionId: options.parentSessionId,\n messageIndex: parentMessages.length,\n cwd: options.cwd,\n userId: String(options.userId),\n });\n if (parentHasActiveProjection && !fork.activeProjectionForked) {\n deleteMaestroSession(fork.sessionId);\n throw new Error(`Maestro active projection could not be forked: ${options.parentSessionId}`);\n }\n const activePath = maestroActiveSessionPath(fork.sessionId);\n return {\n forkId: fork.sessionId,\n rolloutPath: fork.rolloutPath,\n ...(existsSync(activePath) ? { cleanupPaths: [activePath] } : {}),\n };\n },\n async cleanupRollouts(options) {\n // Keep the SDK off the daemon startup path, but use its canonical cleanup\n // once a Maestro session is actually being removed. It also clears memory,\n // task, todo, and in-process file-state sidecars.\n const { deleteMaestroSession } = await import(\"maestro-agent-sdk\");\n const failures: unknown[] = [];\n for (const sessionId of options.sessionIds) {\n try {\n deleteMaestroSession(sessionId);\n const remaining = [\n maestroSessionPath(sessionId),\n maestroActiveSessionPath(sessionId),\n ].filter(existsSync);\n if (remaining.length > 0) {\n throw new Error(`Maestro session files remain after cleanup: ${remaining.join(\", \")}`);\n }\n } catch (error) {\n logger.warn({ err: error, sessionId }, \"maestro cleanupRollouts: cleanup failed\");\n failures.push(error);\n }\n }\n if (failures.length > 0) {\n throw new AggregateError(failures, \"Maestro rollout cleanup failed\");\n }\n },\n};\n",
11
11
  "import { claudeRegistry, claudeRegistryOperations } from \"#agents/claude-registry\";\nimport { codexRegistry, codexRegistryOperations } from \"#agents/codex-registry\";\nimport type { AgentRegistry, AgentRegistryOperations } from \"#agents/contracts\";\nimport { maestroRegistry, maestroRegistryOperations } from \"#agents/maestro-registry\";\nimport type { AgentKind } from \"#types\";\n\nexport type {\n AgentRegistry,\n AgentRegistryOperations,\n CleanupRolloutsOptions,\n ForkRegistryOptions,\n ForkRegistryResult,\n WriteRolloutOptions,\n WriteRolloutResult,\n} from \"#agents/contracts\";\n\nconst REGISTRIES: Record<AgentKind, AgentRegistry> = {\n claude: claudeRegistry,\n codex: codexRegistry,\n maestro: maestroRegistry,\n};\n\nexport function getRegistry(agent: AgentKind): AgentRegistry {\n return REGISTRIES[agent];\n}\n\nconst OPERATIONS: Record<AgentKind, AgentRegistryOperations> = {\n claude: claudeRegistryOperations,\n codex: codexRegistryOperations,\n maestro: maestroRegistryOperations,\n};\n\nexport function getRegistryOperations(agent: AgentKind): AgentRegistryOperations {\n return OPERATIONS[agent];\n}\n",
12
12
  "import {\n type AgentRegistry,\n type AgentRegistryOperations,\n type CleanupRolloutsOptions,\n type ForkRegistryOptions,\n type ForkRegistryResult,\n getRegistry as resolveCoreRegistry,\n getRegistryOperations as resolveCoreRegistryOperations,\n type WriteRolloutOptions,\n type WriteRolloutResult,\n} from \"@negotium/core/registry\";\n\nexport type {\n AgentRegistry,\n AgentRegistryOperations,\n CleanupRolloutsOptions,\n ForkRegistryOptions,\n ForkRegistryResult,\n WriteRolloutOptions,\n WriteRolloutResult,\n};\n\nexport const getRegistry: typeof resolveCoreRegistry = (agent) => resolveCoreRegistry(agent);\n\nexport const getRegistryOperations: typeof resolveCoreRegistryOperations = (agent) =>\n resolveCoreRegistryOperations(agent);\n"
13
13
  ],
14
- "mappings": ";;;;;;;;;;;;;;;;;;;;;AAAA;AACA;AACA;AAOA,IAAM,YAAoC;AAAA,EACxC,QAAQ;AAAA,EACR,MAAM;AAAA,EACN,OAAO;AACT;AAEA,IAAM,gBAAgB,IAAI,IAAI,OAAO,KAAK,SAAS,CAAC;AACpD,IAAM,gBAAgB,IAAI,IAAiB,oBAAoB;AAExD,IAAM,iBAAgC;AAAA,EAC3C,MAAM;AAAA,EACN,cAAc;AAAA,EACd,eAAe;AAAA,EAEf,gBAAgB,CAAC,GAAG;AAAA,IAClB,OAAO,UAAU,MAAM;AAAA;AAAA,EAGzB,aAAa,CAAC,GAAG;AAAA,IACf,OAAO,cAAc,IAAI,CAAC;AAAA;AAAA,EAG5B,cAAc;AAAA,EACd,cAAc,CAAC,GAAG;AAAA,IAChB,OAAO,cAAc,IAAI,CAAC;AAAA;AAAA,EAG5B,WAAW,CAAC,OAAO,QAAQ;AAAA,IACzB,OAAO,SAAS,GAAG,cAAU,WAAW;AAAA;AAE5C;AAEO,IAAM,2BAAoD;AAAA,EAC/D,YAAY,CAAC,MAAM;AAAA,IAIjB,QAAQ,WAAW,gBAAgB,mBAAmB;AAAA,MACpD,KAAK,KAAK;AAAA,MACV,SAAS,KAAK;AAAA,MACd,OAAO,eAAe,iBAAiB,KAAK,SAAS,eAAe,YAAY;AAAA,SAC5E,KAAK,iBAAiB,EAAE,WAAW,KAAK,eAAe,IAAI,CAAC;AAAA,IAClE,CAAC;AAAA,IACD,OAAO,EAAE,WAAW,YAAY;AAAA;AAAA,OAY5B,YAAW,GAAG,iBAAiB,KAAK,SAAS;AAAA,IACjD,QAAQ,gBAAgB,MAAa;AAAA,IAGrC,MAAM,SAAS,MAAM,YAAY,iBAAiB;AAAA,SAC5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8D,CAAC,UAC1E,sBAA8B,KAAK;",
15
+ "debugId": "EC2E7BC8C0D007D864756E2164756E21",
16
16
  "names": []
17
17
  }
package/dist/rollout.js CHANGED
@@ -14,7 +14,7 @@ import {
14
14
  repairPoisonedRollout,
15
15
  writeClaudeRollout,
16
16
  writeCodexRollout
17
- } from "./chunk-fc58cqry.js";
17
+ } from "./chunk-rhp26p2c.js";
18
18
 
19
19
  // src/rollout.ts
20
20
  import { fileURLToPath } from "url";
@@ -2,6 +2,7 @@ import { randomUUID } from "node:crypto";
2
2
  import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
3
3
  import { join } from "node:path";
4
4
  import { runAgent } from "#agents/index";
5
+ import { summarizeDisplayText } from "#agents/tool-format";
5
6
  import { WsHub } from "#bus";
6
7
  import { resolveOutputLanguage, WORKSPACE_DIR } from "#platform/config";
7
8
  import { logger } from "#platform/logger";
@@ -59,10 +60,10 @@ function formatArchiverTool(name: string, input: Record<string, unknown>): strin
59
60
  const params = Object.entries(input)
60
61
  .map(([key, value]) => {
61
62
  const rendered = typeof value === "string" ? value : JSON.stringify(value);
62
- return `${key}: ${sessionText(rendered ?? "")}`;
63
+ return `${key}: ${summarizeDisplayText(sessionText(rendered ?? ""))}`;
63
64
  })
64
65
  .join(", ");
65
- return `${name}${params ? `(${params})` : ""}`;
66
+ return summarizeDisplayText(`${name}${params ? `(${params})` : ""}`);
66
67
  }
67
68
 
68
69
  export interface RunArchiverTurnParams {
@@ -1,9 +1,9 @@
1
1
  import { WsHub } from "#bus";
2
- import { getTopic, upsertTopic } from "#storage/api-topics";
3
- import type { TopicAccessMode } from "#types/api";
2
+ import { getTopic, listTopics, setTopicAccessModes } from "#storage/api-topics";
3
+ import type { TopicAccessMode, TopicDto } from "#types/api";
4
4
 
5
5
  export type SwitchTopicAccessModeResult =
6
- | { ok: true; accessMode: TopicAccessMode; text: string }
6
+ | { ok: true; accessMode: TopicAccessMode; text: string; topicIds: string[] }
7
7
  | { ok: false; error: string };
8
8
 
9
9
  export interface SwitchTopicAccessModeParams {
@@ -12,6 +12,38 @@ export interface SwitchTopicAccessModeParams {
12
12
  accessMode: TopicAccessMode;
13
13
  }
14
14
 
15
+ /**
16
+ * Every subagent room reachable from `rootTopicId`, deepest-first order aside.
17
+ *
18
+ * Mirrors the traversal `deleteTopicCascade` already uses: only `isSubagent`
19
+ * children are owned by their parent, while fork/spawn rooms are independent
20
+ * and must keep their own privacy. `seen` guards against a parent cycle left
21
+ * behind by reparenting, which would otherwise loop forever.
22
+ */
23
+ function collectSubagentDescendants(rootTopicId: string): TopicDto[] {
24
+ const all = listTopics();
25
+ const childrenByParent = new Map<string, TopicDto[]>();
26
+ for (const topic of all) {
27
+ if (!topic.isSubagent || !topic.parentTopicId) continue;
28
+ const siblings = childrenByParent.get(topic.parentTopicId);
29
+ if (siblings) siblings.push(topic);
30
+ else childrenByParent.set(topic.parentTopicId, [topic]);
31
+ }
32
+ const descendants: TopicDto[] = [];
33
+ const seen = new Set<string>([rootTopicId]);
34
+ const queue = [rootTopicId];
35
+ while (queue.length > 0) {
36
+ const parentId = queue.shift() as string;
37
+ for (const child of childrenByParent.get(parentId) ?? []) {
38
+ if (seen.has(child.id)) continue;
39
+ seen.add(child.id);
40
+ descendants.push(child);
41
+ queue.push(child.id);
42
+ }
43
+ }
44
+ return descendants;
45
+ }
46
+
15
47
  /** Change whether a user-owned topic is local-only or shared with connected adapters. */
16
48
  export function switchTopicAccessMode(
17
49
  params: SwitchTopicAccessModeParams,
@@ -22,16 +54,57 @@ export function switchTopicAccessMode(
22
54
  (participant) => participant.userId === params.userId && participant.role === "owner",
23
55
  );
24
56
  if (!owner) return { ok: false, error: "Only topic owners can change privacy" };
57
+ // A subagent room is owned by the room that spawned it, so its privacy is not
58
+ // its own to change: allowing it would let a worker room escape the parent's
59
+ // setting, and the next parent switch would silently overwrite it anyway.
60
+ if (topic.isSubagent) {
61
+ return {
62
+ ok: false,
63
+ error: "Subagent rooms inherit privacy from their parent topic",
64
+ };
65
+ }
66
+
67
+ // Subagents hold the parent's conversation context, so leaving them behind on
68
+ // the old mode would either expose work the user just made private or strand
69
+ // half a delegation tree off the Hub. New rooms already inherit the parent's
70
+ // access mode at creation (`createDerivedTopic`); this keeps existing ones in
71
+ // step.
72
+ const descendants = collectSubagentDescendants(topic.id);
73
+ const changed = [topic, ...descendants].filter(
74
+ (candidate) => (candidate.accessMode ?? "private") !== params.accessMode,
75
+ );
76
+ if (changed.length === 0) {
77
+ return {
78
+ ok: true,
79
+ accessMode: params.accessMode,
80
+ text:
81
+ params.accessMode === "shared"
82
+ ? `"${topic.title}" is already public to the connected Otium Hub.`
83
+ : `"${topic.title}" is already private to this worker.`,
84
+ topicIds: [],
85
+ };
86
+ }
87
+
88
+ setTopicAccessModes(
89
+ changed.map((candidate) => candidate.id),
90
+ params.accessMode,
91
+ );
92
+ // Broadcast only after the write commits: an event emitted inside the
93
+ // transaction would announce a state a rollback could still take back.
94
+ for (const candidate of changed) WsHub.get().broadcastTopicUpdated(candidate.id);
25
95
 
26
- topic.accessMode = params.accessMode;
27
- upsertTopic(topic);
28
- WsHub.get().broadcastTopicUpdated(topic.id);
96
+ const subagentCount = changed.filter((candidate) => candidate.id !== topic.id).length;
97
+ const suffix =
98
+ subagentCount > 0
99
+ ? ` (${subagentCount} subagent room${subagentCount === 1 ? "" : "s"} updated)`
100
+ : "";
29
101
  return {
30
102
  ok: true,
31
103
  accessMode: params.accessMode,
104
+ topicIds: changed.map((candidate) => candidate.id),
32
105
  text:
33
- params.accessMode === "shared"
106
+ (params.accessMode === "shared"
34
107
  ? `"${topic.title}" is public to the connected Otium Hub.`
35
- : `"${topic.title}" is private to this worker.`,
108
+ : `"${topic.title}" is private to this worker.`) + suffix,
36
109
  };
37
110
  }
@@ -319,9 +319,26 @@ export class SqliteRuntimeBus implements RuntimeBus {
319
319
  }
320
320
  }
321
321
 
322
- let current: RuntimeBus = new SqliteRuntimeBus();
322
+ /**
323
+ * Constructed on first use, not at import.
324
+ *
325
+ * `SqliteRuntimeBus`'s constructor reads the latest event sequence, so building
326
+ * the process bus at module scope resolved the storage connection the moment
327
+ * this module was imported. For an embedding host that happens before
328
+ * `configureStorageHost()` has run, and Negotium would open — then cache for the
329
+ * whole process — its own database in the default state directory, leaving every
330
+ * later caller on the wrong store with nothing reporting an error.
331
+ *
332
+ * The read stays in the constructor deliberately: the cursor must be the
333
+ * sequence as of construction so that events broadcast before the first
334
+ * subscriber are still delivered to it. Deferring the read itself would drop
335
+ * them. Deferring the *construction* keeps that semantics and still moves the
336
+ * first storage touch past host bootstrap.
337
+ */
338
+ let current: RuntimeBus | null = null;
323
339
 
324
340
  export function runtimeBus(): RuntimeBus {
341
+ if (!current) current = new SqliteRuntimeBus();
325
342
  return current;
326
343
  }
327
344
 
@@ -332,6 +349,6 @@ export function setRuntimeBus(bus: RuntimeBus): void {
332
349
  /** Drop-in compat for code ported from otium's `WsHub.get()` call sites. */
333
350
  export const WsHub = {
334
351
  get(): RuntimeBus {
335
- return current;
352
+ return runtimeBus();
336
353
  },
337
354
  };
@@ -23,6 +23,7 @@ import {
23
23
  } from "#platform/config";
24
24
  import { readJsonFile } from "#platform/jsonl";
25
25
  import { Database } from "#storage/sqlite";
26
+ import { configuredStorageDatabase, ensureStorageSchemas } from "#storage/storage-host";
26
27
  import type { AgentKind } from "#types";
27
28
  // NOTE: import from "#types" — NOT "@/agents". The agents barrel re-exports
28
29
  // `maestroProvider`, which transitively pulls in `maestro-agent-sdk`. That SDK
@@ -69,6 +70,21 @@ export function withDb<T>(
69
70
  fn: (db: InstanceType<typeof Database>) => T,
70
71
  opts?: { write?: boolean },
71
72
  ): T {
73
+ // An embedding host (Otium) supplies the canonical connection through
74
+ // `configureStorageHost`. Opening `SESSIONS_DB` by path instead would ignore
75
+ // that entirely: the constant is resolved at import time from Negotium's own
76
+ // state directory, so session-comm silently read and wrote a *different*
77
+ // database than the rest of the process — no error, no visible symptom, just
78
+ // two stores drifting apart. Borrow the host connection when one exists.
79
+ const hostDb = configuredStorageDatabase();
80
+ if (hostDb) {
81
+ // Negotium's tables are registered lazily, so a host connection that has not
82
+ // been touched through the shared accessor yet would be missing them.
83
+ ensureStorageSchemas(hostDb);
84
+ // Deliberately no pragmas and no close(): the connection is borrowed, and
85
+ // its journal mode and lifetime belong to the host that opened it.
86
+ return fn(hostDb);
87
+ }
72
88
  const db = new Database(SESSIONS_DB, opts?.write ? undefined : { readonly: true });
73
89
  try {
74
90
  db.exec(opts?.write ? "PRAGMA busy_timeout = 5000" : "PRAGMA busy_timeout = 3000");
@@ -114,11 +114,23 @@ function versionAtLeast(actualVersion: string, minimumVersion: string): boolean
114
114
  return true;
115
115
  }
116
116
 
117
+ /**
118
+ * Ceiling for the `--version` probe, not a latency expectation.
119
+ *
120
+ * The probe exists so a wedged binary cannot hang startup; a healthy one
121
+ * answers in milliseconds. At 2s it also failed whenever the machine was merely
122
+ * busy — process startup under a loaded test suite regularly exceeds that —
123
+ * which turned a correctness check into a load measurement and made
124
+ * `resolveBrowserRsBin` intermittently report a perfectly good binary as
125
+ * unusable. Generous enough that only a genuinely stuck process trips it.
126
+ */
127
+ const BROWSER_RS_VERSION_PROBE_TIMEOUT_MS = 15_000;
128
+
117
129
  function browserRsMeetsMinimumVersion(candidate: string): boolean {
118
130
  try {
119
131
  const output = execFileSync(candidate, ["--version"], {
120
132
  encoding: "utf8",
121
- timeout: 2_000,
133
+ timeout: BROWSER_RS_VERSION_PROBE_TIMEOUT_MS,
122
134
  stdio: ["ignore", "pipe", "ignore"],
123
135
  }).trim();
124
136
  const match = output.match(/^browser-rs (\d+)\.(\d+)\.(\d+)$/);
@@ -12,18 +12,26 @@
12
12
  import { deliverPeerReply, type RemoteReplyRoute } from "#mcp/session-comm/peer-forward";
13
13
  import { db } from "#storage/forum-db";
14
14
  import { PENDING_ASK_TTL_MS, type PendingAskUserId } from "#storage/session-asks";
15
+ import { registerStorageSchemaInitializer } from "#storage/storage-host";
15
16
 
16
- db.exec(`
17
- CREATE TABLE IF NOT EXISTS remote_ask_callbacks (
18
- target_query_id TEXT PRIMARY KEY,
19
- request_id TEXT NOT NULL,
20
- node_name TEXT NOT NULL,
21
- node_cell_id TEXT NOT NULL,
22
- topic_id TEXT NOT NULL,
23
- user_id TEXT NOT NULL,
24
- created_at INTEGER NOT NULL
25
- )
26
- `);
17
+ // Registered rather than executed at import time. A bare top-level `db.exec`
18
+ // resolves the storage connection the moment this module is imported, which for
19
+ // an embedding host is before `configureStorageHost()` has run — Negotium then
20
+ // opens its own database in the default state directory, caches it, and every
21
+ // later caller silently keeps using it instead of the host's.
22
+ registerStorageSchemaInitializer((database) => {
23
+ database.exec(`
24
+ CREATE TABLE IF NOT EXISTS remote_ask_callbacks (
25
+ target_query_id TEXT PRIMARY KEY,
26
+ request_id TEXT NOT NULL,
27
+ node_name TEXT NOT NULL,
28
+ node_cell_id TEXT NOT NULL,
29
+ topic_id TEXT NOT NULL,
30
+ user_id TEXT NOT NULL,
31
+ created_at INTEGER NOT NULL
32
+ )
33
+ `);
34
+ });
27
35
 
28
36
  interface PendingAskIdentity {
29
37
  userId: PendingAskUserId;
@@ -1,4 +1,5 @@
1
1
  import { listActiveMemoryArchiverSessions } from "#agents/archiver";
2
+ import { summarizeDisplayText } from "#agents/tool-format";
2
3
  import { getTopic } from "#storage/api-topics";
3
4
  import { listRecentRuntimeEventsForTopic } from "#storage/runtime-events";
4
5
  import { listRuntimeTurnLeases } from "#storage/runtime-leases";
@@ -127,7 +128,7 @@ function detailedToolStep(payload: Record<string, unknown>): string {
127
128
 
128
129
  if (shortName === "ask_session" || shortName === "tell_session") {
129
130
  const target = typeof input.to === "string" && input.to.trim() ? input.to.trim() : "session";
130
- const msg = typeof input.message === "string" ? text(input.message) : "";
131
+ const msg = typeof input.message === "string" ? summarizeDisplayText(text(input.message)) : "";
131
132
  const action = shortName === "ask_session" ? "Ask" : "Tell";
132
133
  return `${action} ${target}${msg ? ` — ${msg}` : ""}`;
133
134
  }
@@ -150,20 +151,21 @@ function detailedToolStep(payload: Record<string, unknown>): string {
150
151
  return `${action} file`;
151
152
  }
152
153
  if (shortName === "grep" || shortName === "glob") {
153
- const pattern = typeof input.pattern === "string" ? input.pattern : "";
154
+ const pattern =
155
+ typeof input.pattern === "string" ? summarizeDisplayText(text(input.pattern)) : "";
154
156
  const action = shortName === "grep" ? "Grep" : "Glob";
155
- if (pattern) return `${action} '${text(pattern)}'${path ? ` in ${path}` : ""}`;
157
+ if (pattern) return `${action} '${pattern}'${path ? ` in ${path}` : ""}`;
156
158
  if (path) return `${action} ${path}`;
157
159
  }
158
160
  if (shortName === "bash") {
159
- const cmd = typeof input.command === "string" ? text(input.command) : "";
161
+ const cmd = typeof input.command === "string" ? summarizeDisplayText(text(input.command)) : "";
160
162
  return cmd ? `Bash: ${cmd}` : "Bash";
161
163
  }
162
164
  if (shortName === "webfetch" || shortName === "url_fetch") {
163
- const url = typeof input.url === "string" ? text(input.url) : "";
165
+ const url = typeof input.url === "string" ? summarizeDisplayText(text(input.url)) : "";
164
166
  return url ? `Fetch ${url}` : "WebFetch";
165
167
  }
166
- return label;
168
+ return summarizeDisplayText(label);
167
169
  }
168
170
 
169
171
  export function backgroundSessionProgress(
@@ -190,7 +192,7 @@ export function backgroundSessionProgress(
190
192
  else if (kind === "tool_output") {
191
193
  const toolName = toolNames.get(text(payload.toolUseId)) ?? "Tool";
192
194
  step = payload.isError
193
- ? `${toolName} failed: ${text(payload.content) || "unknown error"}`
195
+ ? `${toolName} failed: ${summarizeDisplayText(text(payload.content)) || "unknown error"}`
194
196
  : `${toolName} result · ${byteSize(payload.content)}`;
195
197
  } else if (kind === "ai_done") {
196
198
  const usage =
@@ -10,34 +10,42 @@
10
10
  */
11
11
  import { randomUUID } from "node:crypto";
12
12
  import { db } from "#storage/forum-db";
13
+ import { registerStorageSchemaInitializer } from "#storage/storage-host";
13
14
 
14
15
  const MAX_HISTORY = 10;
15
16
  const MAX_VISUAL_TITLE_CHARS = 180;
16
17
  export const VISUAL_MEDIA_URL_PLACEHOLDER = "__NEGOTIUM_VISUAL_MEDIA_URL__";
17
18
 
18
- db.exec(`
19
- CREATE TABLE IF NOT EXISTS api_topic_visuals (
20
- id INTEGER PRIMARY KEY AUTOINCREMENT,
21
- topic_id TEXT NOT NULL,
22
- html TEXT NOT NULL,
23
- title TEXT,
24
- created_at INTEGER NOT NULL,
25
- kind TEXT NOT NULL DEFAULT 'html',
26
- source TEXT,
27
- file_id TEXT,
28
- mime_type TEXT,
29
- media_token TEXT
30
- );
31
- CREATE INDEX IF NOT EXISTS idx_api_topic_visuals_topic
32
- ON api_topic_visuals(topic_id, created_at DESC);
33
-
34
- CREATE TABLE IF NOT EXISTS api_topic_visual_views (
35
- topic_id TEXT NOT NULL,
36
- user_id TEXT NOT NULL,
37
- visual_id INTEGER NOT NULL,
38
- PRIMARY KEY (topic_id, user_id)
39
- );
40
- `);
19
+ // Registered rather than executed at import time. A bare top-level `db.exec`
20
+ // resolves the storage connection the moment this module is imported, which for
21
+ // an embedding host is before `configureStorageHost()` has run — Negotium then
22
+ // opens its own database in the default state directory, caches it, and every
23
+ // later caller silently keeps using it instead of the host's.
24
+ registerStorageSchemaInitializer((database) => {
25
+ database.exec(`
26
+ CREATE TABLE IF NOT EXISTS api_topic_visuals (
27
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
28
+ topic_id TEXT NOT NULL,
29
+ html TEXT NOT NULL,
30
+ title TEXT,
31
+ created_at INTEGER NOT NULL,
32
+ kind TEXT NOT NULL DEFAULT 'html',
33
+ source TEXT,
34
+ file_id TEXT,
35
+ mime_type TEXT,
36
+ media_token TEXT
37
+ );
38
+ CREATE INDEX IF NOT EXISTS idx_api_topic_visuals_topic
39
+ ON api_topic_visuals(topic_id, created_at DESC);
40
+
41
+ CREATE TABLE IF NOT EXISTS api_topic_visual_views (
42
+ topic_id TEXT NOT NULL,
43
+ user_id TEXT NOT NULL,
44
+ visual_id INTEGER NOT NULL,
45
+ PRIMARY KEY (topic_id, user_id)
46
+ );
47
+ `);
48
+ });
41
49
 
42
50
  for (const statement of [
43
51
  "ALTER TABLE api_topic_visuals ADD COLUMN kind TEXT NOT NULL DEFAULT 'html'",
@@ -705,6 +705,32 @@ export function upsertTopic(t: TopicDto): void {
705
705
  })();
706
706
  }
707
707
 
708
+ /**
709
+ * Apply one access mode to a set of topics as a single all-or-nothing write.
710
+ *
711
+ * A partial write is not a cosmetic glitch here: a public parent left with
712
+ * private subagent children (or the reverse) is exactly the half-exposed state
713
+ * the access-mode cascade exists to prevent, so every row commits or none do.
714
+ *
715
+ * Deliberately a narrow UPDATE instead of a loop over {@link upsertTopic}.
716
+ * That helper opens its own transaction, and the node:sqlite shim in
717
+ * `sqlite.ts` emulates transactions with bare BEGIN/COMMIT rather than
718
+ * savepoints — nesting one inside an outer transaction would fail outright.
719
+ * It also rewrites participants and browser-profile ownership, none of which
720
+ * an access-mode change should touch.
721
+ */
722
+ export function setTopicAccessModes(
723
+ topicIds: readonly string[],
724
+ accessMode: TopicAccessMode,
725
+ ): void {
726
+ if (topicIds.length === 0) return;
727
+ const normalized = normalizeTopicAccessMode(accessMode);
728
+ db.transaction(() => {
729
+ const update = db.query("UPDATE api_topics SET access_mode = ? WHERE id = ?");
730
+ for (const topicId of topicIds) update.run(normalized, topicId);
731
+ })();
732
+ }
733
+
708
734
  export function listTopics(): TopicDto[] {
709
735
  const rows = db
710
736
  .query("SELECT * FROM api_topics ORDER BY last_message_at DESC")
@@ -1,4 +1,5 @@
1
1
  import { db } from "#storage/forum-db";
2
+ import { registerStorageSchemaInitializer } from "#storage/storage-host";
2
3
 
3
4
  export const DEFAULT_BROWSER_PROFILE = "default";
4
5
 
@@ -17,14 +18,21 @@ export function normalizeBrowserProfileName(name: string): string {
17
18
  return value;
18
19
  }
19
20
 
20
- db.exec(`
21
- CREATE TABLE IF NOT EXISTS browser_profiles (
22
- owner_id TEXT NOT NULL,
23
- name TEXT NOT NULL,
24
- created_at TEXT NOT NULL,
25
- PRIMARY KEY (owner_id, name)
26
- )
27
- `);
21
+ // Registered rather than executed at import time. A bare top-level `db.exec`
22
+ // resolves the storage connection the moment this module is imported, which for
23
+ // an embedding host is before `configureStorageHost()` has run — Negotium then
24
+ // opens its own database in the default state directory, caches it, and every
25
+ // later caller silently keeps using it instead of the host's.
26
+ registerStorageSchemaInitializer((database) => {
27
+ database.exec(`
28
+ CREATE TABLE IF NOT EXISTS browser_profiles (
29
+ owner_id TEXT NOT NULL,
30
+ name TEXT NOT NULL,
31
+ created_at TEXT NOT NULL,
32
+ PRIMARY KEY (owner_id, name)
33
+ )
34
+ `);
35
+ });
28
36
 
29
37
  export function getBrowserProfileOwner(topicId: string, fallbackUserId: string): string {
30
38
  return (