negotium 0.2.4 → 0.2.5

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 (62) hide show
  1. package/dist/agent-helpers.js +241 -127
  2. package/dist/agent-helpers.js.map +19 -19
  3. package/dist/background-bash.js +1 -3
  4. package/dist/background-bash.js.map +4 -4
  5. package/dist/browser-runtime.js +1 -3
  6. package/dist/browser-runtime.js.map +4 -4
  7. package/dist/{chunk-1s9ryz8g.js → chunk-qmbcbhyy.js} +20 -12
  8. package/dist/chunk-qmbcbhyy.js.map +35 -0
  9. package/dist/hosted-agent.js +13 -10
  10. package/dist/hosted-agent.js.map +10 -10
  11. package/dist/main.js +598 -438
  12. package/dist/main.js.map +30 -29
  13. package/dist/mcp-factories.js +238 -123
  14. package/dist/mcp-factories.js.map +18 -18
  15. package/dist/prompts.js +1 -3
  16. package/dist/prompts.js.map +4 -4
  17. package/dist/query-runtime.js +1 -3
  18. package/dist/query-runtime.js.map +5 -5
  19. package/dist/registry.js +3 -3
  20. package/dist/registry.js.map +2 -2
  21. package/dist/rollout.js +1 -1
  22. package/dist/runtime/src/agents/api-topic-agent-switch.ts +6 -12
  23. package/dist/runtime/src/agents/claude-provider.ts +2 -2
  24. package/dist/runtime/src/agents/codex-provider.ts +1 -0
  25. package/dist/runtime/src/agents/index.ts +19 -14
  26. package/dist/runtime/src/agents/maestro-provider.ts +1 -1
  27. package/dist/runtime/src/agents/rollout/codex.ts +25 -18
  28. package/dist/runtime/src/agents/self-config-core.ts +2 -4
  29. package/dist/runtime/src/agents/topic-agent-switch.ts +4 -10
  30. package/dist/runtime/src/application/submit-runtime-gateway-turn.ts +77 -19
  31. package/dist/runtime/src/application/switch-topic-model.ts +7 -10
  32. package/dist/runtime/src/index.ts +4 -0
  33. package/dist/runtime/src/mcp/wiki-server.ts +19 -12
  34. package/dist/runtime/src/platform/config.ts +0 -2
  35. package/dist/runtime/src/platform/log-rotation.ts +45 -0
  36. package/dist/runtime/src/platform/mcp-config.ts +9 -3
  37. package/dist/runtime/src/query/active-rooms.ts +7 -1
  38. package/dist/runtime/src/runtime/errors.ts +1 -0
  39. package/dist/runtime/src/runtime/turn-event-stream.ts +46 -1
  40. package/dist/runtime/src/runtime/turn-runner.ts +176 -100
  41. package/dist/runtime/src/runtime/user-turn-envelope.ts +19 -0
  42. package/dist/runtime/src/storage/runtime-gateway-submissions.ts +12 -3
  43. package/dist/runtime/src/storage/runtime-turn-requests.ts +68 -7
  44. package/dist/runtime/src/types.ts +2 -0
  45. package/dist/runtime/src/version.ts +1 -1
  46. package/dist/runtime-helpers.js +1 -3
  47. package/dist/runtime-helpers.js.map +4 -4
  48. package/dist/storage.js.map +1 -1
  49. package/dist/types/packages/core/src/agents/api-topic-agent-switch.d.ts +1 -1
  50. package/dist/types/packages/core/src/agents/self-config-core.d.ts +1 -1
  51. package/dist/types/packages/core/src/platform/config.d.ts +0 -1
  52. package/dist/types/packages/core/src/platform/mcp-config.d.ts +3 -0
  53. package/dist/types/packages/core/src/query/active-rooms.d.ts +7 -1
  54. package/dist/types/packages/core/src/runtime/turn-runner.d.ts +42 -1
  55. package/dist/types/packages/core/src/runtime/user-turn-envelope.d.ts +7 -0
  56. package/dist/types/packages/core/src/storage/runtime-turn-requests.d.ts +17 -0
  57. package/dist/types/packages/core/src/types.d.ts +2 -0
  58. package/dist/types/packages/core/src/version.d.ts +1 -1
  59. package/dist/vault.js +1 -3
  60. package/dist/vault.js.map +4 -4
  61. package/package.json +1 -1
  62. package/dist/chunk-1s9ryz8g.js.map +0 -35
@@ -19,7 +19,7 @@
19
19
  "/**\n * Global (workspace-wide) application settings — a single shared record, not\n * per-user and not per-topic.\n *\n * Currently holds the global AI name (default \"Otium\"): the AI is one named\n * entity for the whole workspace. Changing it is an admin-only action (see the\n * settings route). Loaded lazily from the currently configured storage host.\n */\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { resolveStorageDataDir } from \"#storage/storage-host\";\n\nexport const DEFAULT_AI_NAME = \"Otium\";\n\nlet aiName = DEFAULT_AI_NAME;\nlet loadedSettingsFile: string | null = null;\n\nfunction settingsFile(): string {\n return join(resolveStorageDataDir(), \"otium-settings.json\");\n}\n\nfunction ensureSettingsLoaded(): string {\n const path = settingsFile();\n if (loadedSettingsFile === path) return path;\n loadedSettingsFile = path;\n aiName = DEFAULT_AI_NAME;\n try {\n if (existsSync(path)) {\n const data = JSON.parse(readFileSync(path, \"utf8\")) as { aiName?: unknown };\n if (typeof data.aiName === \"string\" && data.aiName.trim()) {\n aiName = data.aiName.trim();\n }\n }\n } catch {\n // Corrupt/missing file → keep the default.\n }\n return path;\n}\n\nexport function getGlobalAiName(): string {\n ensureSettingsLoaded();\n return aiName || DEFAULT_AI_NAME;\n}\n\n/** Set the global AI name (empty → reset to default). Persists to disk. */\nexport function setGlobalAiName(name: string): string {\n const path = ensureSettingsLoaded();\n aiName = name.trim() || DEFAULT_AI_NAME;\n try {\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, JSON.stringify({ aiName }, null, 2));\n } catch {\n // Best-effort persistence; the in-memory value still updates.\n }\n return aiName;\n}\n",
20
20
  "import { db } from \"#storage/forum-db\";\nimport { registerStorageSchemaInitializer } from \"#storage/storage-host\";\nimport type { AskUserQuestionDto } from \"#types/api\";\n\nexport type AskUserGateState = \"pending\" | \"claimed\" | \"answered\" | \"cancelled\" | \"quarantined\";\n\nexport interface AskUserGateRecord {\n gateId: string;\n topicId: string;\n queryId?: string;\n idempotencyKey: string;\n bodyHash: string;\n messageId: string;\n ownerId: string;\n state: AskUserGateState;\n selectedLabel?: string;\n answeredBy?: string;\n}\n\ninterface AskUserGateRow {\n gate_id: string;\n topic_id: string;\n query_id: string | null;\n idempotency_key: string;\n body_hash: string;\n message_id: string;\n owner_id: string;\n state: AskUserGateState;\n selected_label: string | null;\n answered_by: string | null;\n}\n\nexport interface AskUserGateCardUpdate {\n topicId: string;\n messageId: string;\n askUserQuestion: AskUserQuestionDto;\n editedAt: string;\n}\n\nfunction initializeAskUserGateSchema(): void {\n db.exec(`\n CREATE TABLE IF NOT EXISTS ask_user_gates (\n gate_id TEXT PRIMARY KEY,\n topic_id TEXT NOT NULL REFERENCES api_topics(id) ON DELETE CASCADE,\n query_id TEXT,\n idempotency_key TEXT NOT NULL,\n body_hash TEXT NOT NULL,\n message_id TEXT NOT NULL UNIQUE,\n owner_id TEXT NOT NULL,\n state TEXT NOT NULL,\n selected_label TEXT,\n answered_by TEXT,\n claim_source TEXT,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL\n );\n CREATE INDEX IF NOT EXISTS idx_ask_user_gates_idempotency\n ON ask_user_gates(topic_id, idempotency_key, created_at);\n CREATE UNIQUE INDEX IF NOT EXISTS idx_ask_user_gates_active_key\n ON ask_user_gates(topic_id, idempotency_key)\n WHERE state IN ('pending', 'claimed');\n `);\n}\n\nregisterStorageSchemaInitializer(initializeAskUserGateSchema, 31);\n\nfunction fromRow(row: AskUserGateRow): AskUserGateRecord {\n return {\n gateId: row.gate_id,\n topicId: row.topic_id,\n queryId: row.query_id ?? undefined,\n idempotencyKey: row.idempotency_key,\n bodyHash: row.body_hash,\n messageId: row.message_id,\n ownerId: row.owner_id,\n state: row.state,\n selectedLabel: row.selected_label ?? undefined,\n answeredBy: row.answered_by ?? undefined,\n };\n}\n\nfunction latestGate(topicId: string, idempotencyKey: string): AskUserGateRecord | null {\n const row = db\n .query(\n `SELECT * FROM ask_user_gates\n WHERE topic_id = ? AND idempotency_key = ?\n ORDER BY rowid DESC LIMIT 1`,\n )\n .get(topicId, idempotencyKey) as AskUserGateRow | undefined;\n return row ? fromRow(row) : null;\n}\n\nfunction expireAskCard(\n topicId: string,\n messageId: string,\n editedAt: string,\n): AskUserGateCardUpdate | null {\n const row = db\n .query(\n `SELECT ask_user_question FROM api_messages\n WHERE topic_id = ? AND id = ? AND deleted = 0 AND kind = 'ask_user_question'`,\n )\n .get(topicId, messageId) as { ask_user_question: string | null } | undefined;\n if (!row?.ask_user_question) return null;\n const ask = JSON.parse(row.ask_user_question) as AskUserQuestionDto;\n if (ask.selectedLabel || ask.expired) return null;\n const expired = { ...ask, expired: true };\n db.query(\n `UPDATE api_messages SET ask_user_question = ?, edited_at = ?\n WHERE topic_id = ? AND id = ? AND deleted = 0 AND kind = 'ask_user_question'`,\n ).run(JSON.stringify(expired), editedAt, topicId, messageId);\n return { topicId, messageId, askUserQuestion: expired, editedAt };\n}\n\nexport type PrepareAskUserGateResult =\n | { outcome: \"created\"; gate: AskUserGateRecord }\n | { outcome: \"pending\"; gate: AskUserGateRecord }\n | { outcome: \"replay\"; gate: AskUserGateRecord }\n | { outcome: \"conflict\"; gate: AskUserGateRecord };\n\nexport function prepareAskUserGate(args: {\n gateId: string;\n topicId: string;\n queryId?: string;\n idempotencyKey: string;\n bodyHash: string;\n messageId: string;\n ownerId: string;\n now: string;\n}): PrepareAskUserGateResult {\n return db\n .transaction(() => {\n const latest = latestGate(args.topicId, args.idempotencyKey);\n if (latest?.bodyHash !== undefined && latest.bodyHash !== args.bodyHash) {\n return { outcome: \"conflict\", gate: latest } as const;\n }\n if (latest?.state === \"answered\") return { outcome: \"replay\", gate: latest } as const;\n if (\n latest &&\n (latest.state === \"pending\" || latest.state === \"claimed\") &&\n latest.ownerId === args.ownerId\n ) {\n return { outcome: \"pending\", gate: latest } as const;\n }\n if (latest && (latest.state === \"pending\" || latest.state === \"claimed\")) {\n return { outcome: \"pending\", gate: latest } as const;\n }\n\n db.query(\n `INSERT INTO ask_user_gates\n (gate_id, topic_id, query_id, idempotency_key, body_hash, message_id, owner_id, state, created_at, updated_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', ?, ?)`,\n ).run(\n args.gateId,\n args.topicId,\n args.queryId ?? null,\n args.idempotencyKey,\n args.bodyHash,\n args.messageId,\n args.ownerId,\n args.now,\n args.now,\n );\n return {\n outcome: \"created\",\n gate: {\n gateId: args.gateId,\n topicId: args.topicId,\n queryId: args.queryId,\n idempotencyKey: args.idempotencyKey,\n bodyHash: args.bodyHash,\n messageId: args.messageId,\n ownerId: args.ownerId,\n state: \"pending\",\n },\n } as const;\n })\n .immediate();\n}\n\nexport function quarantineAskUserGate(\n gateId: string,\n ownerId: string,\n now = new Date().toISOString(),\n): AskUserGateCardUpdate | null {\n return db\n .transaction(() => {\n const row = db.query(\"SELECT * FROM ask_user_gates WHERE gate_id = ?\").get(gateId) as\n | AskUserGateRow\n | undefined;\n if (!row || row.owner_id !== ownerId || ![\"pending\", \"claimed\"].includes(row.state)) {\n return null;\n }\n const result = db\n .query(\n `UPDATE ask_user_gates SET state = 'quarantined', updated_at = ?\n WHERE gate_id = ? AND owner_id = ? AND state IN ('pending', 'claimed')`,\n )\n .run(now, gateId, ownerId);\n if (Number(result.changes ?? 0) === 0) return null;\n return expireAskCard(row.topic_id, row.message_id, now);\n })\n .immediate();\n}\n\nexport function quarantineForeignAskUserGates(\n liveOwnerIds: ReadonlySet<string>,\n now = new Date().toISOString(),\n): AskUserGateCardUpdate[] {\n return db\n .transaction(() => {\n const rows = db\n .query(\n `SELECT * FROM ask_user_gates\n WHERE state IN ('pending', 'claimed')`,\n )\n .all() as AskUserGateRow[];\n const updates: AskUserGateCardUpdate[] = [];\n for (const row of rows) {\n if (liveOwnerIds.has(row.owner_id)) continue;\n if (row.state === \"claimed\" && row.selected_label && row.answered_by) {\n db.query(\n `UPDATE ask_user_gates SET state = 'answered', updated_at = ?\n WHERE gate_id = ? AND state = 'claimed'`,\n ).run(now, row.gate_id);\n continue;\n }\n const result = db\n .query(\n `UPDATE ask_user_gates SET state = 'quarantined', updated_at = ?\n WHERE gate_id = ? AND state IN ('pending', 'claimed')`,\n )\n .run(now, row.gate_id);\n if (Number(result.changes ?? 0) === 0) continue;\n const update = expireAskCard(row.topic_id, row.message_id, now);\n if (update) updates.push(update);\n }\n const legacyCards = db\n .query(\n `SELECT m.topic_id, m.id\n FROM api_messages m\n LEFT JOIN ask_user_gates g ON g.message_id = m.id\n WHERE m.kind = 'ask_user_question'\n AND m.deleted = 0\n AND g.gate_id IS NULL`,\n )\n .all() as { topic_id: string; id: string }[];\n for (const card of legacyCards) {\n const update = expireAskCard(card.topic_id, card.id, now);\n if (update) updates.push(update);\n }\n return updates;\n })\n .immediate();\n}\n\nexport type ClaimAskUserGateResult =\n | {\n outcome: \"claimed\";\n gate: AskUserGateRecord;\n askUserQuestion: AskUserQuestionDto;\n editedAt: string;\n }\n | { outcome: \"unavailable\" };\n\nexport function claimAskUserGateAndSelect(args: {\n topicId: string;\n messageId: string;\n label: string;\n userId: string;\n ownerId: string;\n source: string;\n now: string;\n}): ClaimAskUserGateResult {\n return db\n .transaction(() => {\n const row = db\n .query(\n `SELECT * FROM ask_user_gates\n WHERE topic_id = ? AND message_id = ?\n ORDER BY rowid DESC LIMIT 1`,\n )\n .get(args.topicId, args.messageId) as AskUserGateRow | undefined;\n if (!row || row.owner_id !== args.ownerId || row.state !== \"pending\") {\n return { outcome: \"unavailable\" } as const;\n }\n const message = db\n .query(\n `SELECT ask_user_question FROM api_messages\n WHERE topic_id = ? AND id = ? AND deleted = 0 AND kind = 'ask_user_question'`,\n )\n .get(args.topicId, args.messageId) as { ask_user_question: string | null } | undefined;\n if (!message?.ask_user_question) return { outcome: \"unavailable\" } as const;\n const ask = JSON.parse(message.ask_user_question) as AskUserQuestionDto;\n if (\n ask.expired ||\n ask.selectedLabel ||\n !ask.choices.some((choice) => choice.label === args.label)\n ) {\n return { outcome: \"unavailable\" } as const;\n }\n\n const claimed = db\n .query(\n `UPDATE ask_user_gates\n SET state = 'answered', selected_label = ?, answered_by = ?, claim_source = ?, updated_at = ?\n WHERE gate_id = ? AND owner_id = ? AND state = 'pending'`,\n )\n .run(args.label, args.userId, args.source, args.now, row.gate_id, args.ownerId);\n if (Number(claimed.changes ?? 0) === 0) return { outcome: \"unavailable\" } as const;\n\n const selected = { ...ask, selectedLabel: args.label };\n db.query(\n `UPDATE api_messages SET ask_user_question = ?, edited_at = ?\n WHERE topic_id = ? AND id = ? AND deleted = 0 AND kind = 'ask_user_question'`,\n ).run(JSON.stringify(selected), args.now, args.topicId, args.messageId);\n return {\n outcome: \"claimed\",\n gate: fromRow({\n ...row,\n state: \"answered\",\n selected_label: args.label,\n answered_by: args.userId,\n }),\n askUserQuestion: selected,\n editedAt: args.now,\n } as const;\n })\n .immediate();\n}\n\nexport function cancelAskUserGate(\n topicId: string,\n messageId: string,\n ownerId: string,\n now = new Date().toISOString(),\n): AskUserGateCardUpdate | null {\n return db\n .transaction(() => {\n const row = db\n .query(\n `SELECT * FROM ask_user_gates\n WHERE topic_id = ? AND message_id = ? ORDER BY rowid DESC LIMIT 1`,\n )\n .get(topicId, messageId) as AskUserGateRow | undefined;\n if (!row || row.owner_id !== ownerId || row.state !== \"pending\") return null;\n const result = db\n .query(\n `UPDATE ask_user_gates SET state = 'cancelled', updated_at = ?\n WHERE gate_id = ? AND owner_id = ? AND state = 'pending'`,\n )\n .run(now, row.gate_id, ownerId);\n if (Number(result.changes ?? 0) === 0) return null;\n return expireAskCard(topicId, messageId, now);\n })\n .immediate();\n}\n",
21
21
  "import {\n existsSync,\n mkdirSync,\n readFileSync,\n renameSync,\n unlinkSync,\n writeFileSync,\n} from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { appendJsonlLine } from \"#platform/jsonl\";\nimport { logger } from \"#platform/logger\";\nimport { sanitizeTopicName } from \"#security/sanitize\";\nimport { resolveStorageDataDir } from \"#storage/storage-host\";\nimport type { AgentKind, UnifiedEvent } from \"#types\";\n\n/**\n * Per-topic conversation log (UnifiedEvent stream) used as the\n * **provider-agnostic source of truth** for cross-agent portability.\n *\n * Storage layout:\n * {DATA_DIR}/conversations/{sanitizedTopicName}.jsonl\n * {DATA_DIR}/conversations/{sanitizedTopicName}.active.jsonl\n *\n * The first file is append-only and retains every yielded UnifiedEvent for\n * archive and teardown. The optional active file is a replaceable provider\n * projection: compaction writes its summary there and later turns append to\n * both streams. Agent switches and rollout repair read the active projection.\n *\n * The Claude/Codex SDK rollouts (~/.claude/projects/, ~/.codex/sessions/) are\n * intentionally treated as opaque side-effects of the SDKs. The raw stream\n * remains the forensic source of truth.\n */\nexport interface ConversationEntry {\n ts: string;\n /**\n * Agent that produced this event, frozen at write time. A topic that has\n * been switched (via `set_agent`) will have a mixed-agent log: earlier\n * entries keep the agent that originally generated them. Replay code\n * (rollout-codec `extractChatPairs`) intentionally ignores this field —\n * the cross-agent rollout's whole point is to feed past dialogue, no\n * matter who produced it, into the *new* SDK as if it were native.\n */\n agent: AgentKind;\n event: UnifiedEvent;\n}\n\n/** Public userId remains in the API, but standalone storage has one flat local namespace. */\nfunction conversationDir(_userId: number | string): string {\n return join(resolveStorageDataDir(), \"conversations\");\n}\n\nfunction topicFilename(topicName: string): string {\n const t = sanitizeTopicName(topicName, true);\n return `${t}.jsonl`;\n}\n\n/** Compute the absolute path for a given user/topic conversation log. */\nexport function getConversationPath(userId: number | string, topicName: string): string {\n return join(conversationDir(userId), topicFilename(topicName));\n}\n\n/** Replaceable provider context derived from the append-only raw conversation log. */\nexport function getActiveConversationPath(userId: number | string, topicName: string): string {\n const rawPath = getConversationPath(userId, topicName);\n return rawPath.endsWith(\".jsonl\")\n ? `${rawPath.slice(0, -\".jsonl\".length)}.active.jsonl`\n : `${rawPath}.active`;\n}\n\nexport function hasActiveConversation(userId: number | string, topicName: string): boolean {\n return existsSync(getActiveConversationPath(userId, topicName));\n}\n\n/**\n * Append a single UnifiedEvent for the given topic. Creates the parent\n * directory and the file as needed. Best-effort: I/O failures are logged but\n * never throw, since recording must not break the live stream to Telegram.\n *\n * **Concurrency note (review item M2, revised):** within the bot process the\n * single-threaded event loop already serializes writes — but this module is\n * NOT single-process: the self-config MCP server (a separate stdio process,\n * via `topic-agent-switch`) and provider bridge helpers append to the same\n * topic logs.\n * Cross-process interleaving on macOS is real for lines beyond PIPE_BUF\n * (512B), and a torn line is silently dropped by `readConversation` —\n * corrupting the canonical source for cross-agent rollout reconstruction.\n * Writes therefore go through `appendJsonlLine` (sidecar `.lock` via O_EXCL,\n * stale-lock reclaim, and a `JsonlLockTimeoutError` when the lock stays busy —\n * nothing is written unlocked, so a contended append fails instead of risking\n * an interleaved line that `readConversationPath` would later discard).\n *\n * The append stays SYNCHRONOUS on purpose: a previous attempt at a\n * Promise-chained per-topic queue made writes async (durability gap before a\n * synchronous `readConversation`) and broke `set_agent` in the bridge tests.\n */\nexport function appendConversationEvent(\n userId: number | string,\n topicName: string,\n agent: AgentKind,\n event: UnifiedEvent,\n): boolean {\n try {\n appendConversationEventStrict(userId, topicName, agent, event);\n return true;\n } catch (err) {\n logger.warn(\n { err, userId, topicName, eventType: event.type },\n \"appendConversationEvent: write failed\",\n );\n return false;\n }\n}\n\n/**\n * The raw manifest accepted an entry that the active projection rejected.\n *\n * Distinct from a plain write failure because the two logs are now out of sync\n * rather than merely un-updated: `raw` records the event, `active` — the log\n * replayed to the provider — does not.\n */\nexport class ConversationLogDivergedError extends Error {\n constructor(\n readonly rawPath: string,\n readonly activePath: string,\n override readonly cause: unknown,\n ) {\n super(\n `conversation logs diverged: the entry is in the raw manifest (${rawPath}) ` +\n `but the active projection (${activePath}) rejected it`,\n );\n this.name = \"ConversationLogDivergedError\";\n }\n}\n\n/**\n * Strict variant for state transitions where the conversation log is a manifest\n * rather than telemetry. Throws on I/O failure so callers can avoid committing\n * DB state that points at an unmanifested SDK session.\n */\nexport function appendConversationEventStrict(\n userId: number | string,\n topicName: string,\n agent: AgentKind,\n event: UnifiedEvent,\n): void {\n const path = getConversationPath(userId, topicName);\n const entry: ConversationEntry = {\n ts: new Date().toISOString(),\n agent,\n event,\n };\n const line = JSON.stringify(entry);\n mkdirSync(dirname(path), { recursive: true });\n appendJsonlLine(path, line);\n const activePath = getActiveConversationPath(userId, topicName);\n if (existsSync(activePath)) {\n try {\n appendJsonlLine(activePath, line);\n } catch (cause) {\n // The two appends are not atomic. Raw already has the entry, so failing\n // here leaves the logs permanently split: the provider replays `active`\n // and will never see this event, while the raw manifest says it happened.\n // We cannot un-append, so at least name the inconsistency instead of\n // surfacing a generic write error that hides which side is wrong.\n throw new ConversationLogDivergedError(path, activePath, cause);\n }\n }\n}\n\n/** Append lifecycle metadata to the raw manifest without changing active context. */\nexport function appendRawConversationEventStrict(\n userId: number | string,\n topicName: string,\n agent: AgentKind,\n event: UnifiedEvent,\n): void {\n const path = getConversationPath(userId, topicName);\n const entry: ConversationEntry = {\n ts: new Date().toISOString(),\n agent,\n event,\n };\n mkdirSync(dirname(path), { recursive: true });\n appendJsonlLine(path, JSON.stringify(entry));\n}\n\n/**\n * Read one JSONL conversation stream. Malformed lines are skipped so one\n * damaged event does not poison the remaining history.\n */\nfunction readConversationPath(path: string): ConversationEntry[] {\n const out: ConversationEntry[] = [];\n if (!existsSync(path)) return out;\n let raw: string;\n try {\n raw = readFileSync(path, \"utf8\");\n } catch (err) {\n logger.warn({ err, path }, \"readConversation: read failed\");\n return out;\n }\n for (const line of raw.split(\"\\n\")) {\n if (!line.trim()) continue;\n try {\n out.push(JSON.parse(line) as ConversationEntry);\n } catch (err) {\n logger.warn(\n { err, line: line.slice(0, 200) },\n \"readConversation: malformed JSONL line skipped\",\n );\n }\n }\n return out;\n}\n\n/**\n * Read the context the next provider turn should receive. Before the first\n * compaction this is the raw stream. Afterwards the replaceable active stream\n * contains the compacted summary plus every subsequently recorded event.\n *\n * NOTE(perf): reads the whole file each call. Topics in the kilobyte range\n * are fine; if a single topic ever grows into multi-megabyte territory,\n * consider a streaming reader (`readline`/`Bun.file().stream()`) and a\n * size-bounded tail.\n */\nexport function readConversation(userId: number | string, topicName: string): ConversationEntry[] {\n const activePath = getActiveConversationPath(userId, topicName);\n return readConversationPath(\n existsSync(activePath) ? activePath : getConversationPath(userId, topicName),\n );\n}\n\n/** Read the immutable full-fidelity stream used for archive and teardown. */\nexport function readRawConversation(\n userId: number | string,\n topicName: string,\n): ConversationEntry[] {\n return readConversationPath(getConversationPath(userId, topicName));\n}\n\n/** Atomically replace only the provider's active context projection. */\nexport function replaceConversationStrict(\n userId: number | string,\n topicName: string,\n entries: ConversationEntry[],\n): void {\n replaceConversationPathStrict(getActiveConversationPath(userId, topicName), entries);\n}\n\n/** Atomically seed or restore the append-only stream before it becomes live. */\nexport function replaceRawConversationStrict(\n userId: number | string,\n topicName: string,\n entries: ConversationEntry[],\n): void {\n replaceConversationPathStrict(getConversationPath(userId, topicName), entries);\n}\n\nfunction replaceConversationPathStrict(path: string, entries: ConversationEntry[]): void {\n const tempPath = `${path}.${process.pid}.${Date.now()}.tmp`;\n mkdirSync(dirname(path), { recursive: true });\n try {\n writeFileSync(\n tempPath,\n entries.length > 0 ? `${entries.map((entry) => JSON.stringify(entry)).join(\"\\n\")}\\n` : \"\",\n { flag: \"wx\" },\n );\n renameSync(tempPath, path);\n } catch (error) {\n try {\n unlinkSync(tempPath);\n } catch {}\n throw error;\n }\n}\n\n/**\n * Copy the unified conversation log of `srcTopic` into the file path that\n * `dstTopic` will read from. Used by `/fork` so a forked child topic inherits\n * the parent's full cross-agent history, not just the agent's native SDK\n * rollout. `/spawn` intentionally does not call this; it starts with no\n * conversation history. Without this copy, a fork followed immediately by\n * `/agent <other>` would feed the empty child log to `switchTopicAgent` and\n * the new agent would start from zero — see the bug report from 2026-05-24.\n *\n * Semantics:\n * - Copies the parent's raw stream and its active projection when present.\n * - Writes independent files so parent and child can diverge after the fork.\n * - Refuses to overwrite a non-empty destination (returns `{copied:false}`).\n * `/fork`'s only caller runs this immediately after topic creation when\n * the dst file is guaranteed empty, so a non-empty dst means a programmer\n * error somewhere upstream — fail loud rather than silently merging.\n * - On any I/O error: throws. The caller (`createChildTopic`) already has\n * a rollback path that wraps this call.\n */\nexport function cloneConversationLog(opts: {\n userId: number | string;\n srcTopic: string;\n dstTopic: string;\n}): { copied: boolean; entries: number } {\n const { userId, srcTopic, dstTopic } = opts;\n const dstPath = getConversationPath(userId, dstTopic);\n if (existsSync(dstPath) && readFileSync(dstPath, \"utf8\").trim().length > 0) {\n logger.warn(\n { userId, srcTopic, dstTopic, dstPath },\n \"cloneConversationLog: dst already non-empty — refusing to overwrite\",\n );\n return { copied: false, entries: 0 };\n }\n const entries = readRawConversation(userId, srcTopic);\n if (entries.length === 0) {\n return { copied: false, entries: 0 };\n }\n const body = `${entries.map((e) => JSON.stringify(e)).join(\"\\n\")}\\n`;\n mkdirSync(dirname(dstPath), { recursive: true });\n writeFileSync(dstPath, body);\n const srcActivePath = getActiveConversationPath(userId, srcTopic);\n if (existsSync(srcActivePath)) {\n const dstActivePath = getActiveConversationPath(userId, dstTopic);\n writeFileSync(dstActivePath, readFileSync(srcActivePath));\n }\n return { copied: true, entries: entries.length };\n}\n\n/**\n * Walk the unified log backwards and return the most recent SDK-emitted\n * session id for the given agent — or null if that agent has never run on\n * this topic.\n *\n * Used by `set_agent` to round-trip the SAME native rollout file across\n * agent switches: when the user does claude → codex → claude, we reuse\n * the original claude sessionId so the synthetic rollout lands at the\n * same path the SDK already manages, preserving prompt-cache continuity\n * and avoiding orphan `~/.claude/projects/<dir>/<id>.jsonl` files.\n *\n * Behavior:\n * - First-ever switch to an agent (no prior session events) → null,\n * caller falls back to a fresh randomUUID/uuidv7. Same as before.\n * - Roundtrip switch (prior session exists) → that sessionId.\n *\n * `session` events are emitted on every turn by claude-/codex-provider and\n * captured into the unified log by runAgent's append wrapper. The most\n * recent one for the target agent is by definition the current SDK-side\n * resume key for that agent.\n */\nexport function findLastSessionIdForAgent(\n entries: ConversationEntry[],\n agent: AgentKind,\n): string | null {\n for (let i = entries.length - 1; i >= 0; i--) {\n const entry = entries[i];\n if (entry.agent !== agent) continue;\n if (entry.event.type === \"session\") {\n return entry.event.sessionId;\n }\n }\n return null;\n}\n",
22
- "/**\n * Common context carried through the attachment/prompt-build pipeline.\n * Used by buildPromptFromMessage and related helpers.\n */\nexport interface SessionContext {\n userId: number;\n topicName?: string;\n userDir?: string;\n sessionType?: \"dm\" | \"forum\" | \"ephemeral\" | \"manager\" | \"cron\";\n}\n\nexport interface TokenUsage {\n /** Aggregate billable input across every model call made during this turn. */\n inputTokens: number;\n outputTokens: number;\n cacheCreationInputTokens?: number;\n cacheReadInputTokens?: number;\n /** Provider-reported query cost when available. */\n costUsd?: number;\n /** Tokens occupied by the latest model call, not aggregate turn spend. */\n contextTokens?: number;\n /** Provider-reported context window for the latest model call. */\n contextWindow?: number;\n}\n\n/** Agent identifier — one of the supported AI provider backends. */\nexport type AgentKind = \"maestro\" | \"claude\" | \"codex\";\n\nexport const SUPPORTED_AGENTS: readonly AgentKind[] = [\"maestro\", \"claude\", \"codex\"] as const;\n\nexport function isAgentKind(value: unknown): value is AgentKind {\n return typeof value === \"string\" && (SUPPORTED_AGENTS as readonly string[]).includes(value);\n}\n\n/**\n * Per-agent supported reasoning efforts. Single source of truth for both the\n * `EffortLevel` type and each registry's `validEfforts` runtime list — the\n * registries import these directly so adding a value in one place\n * propagates to validation, footer rendering, and zod enums.\n *\n * Claude SDK rejects 'minimal'; Codex SDK rejects 'max'. The two sets\n * intersect on low/medium/high/xhigh. Maestro (TS port) currently piggybacks\n * on the Anthropic provider, so its efforts mirror the Claude set; this can\n * narrow per-provider once Phase 5 lands.\n *\n * 'minimal' removed from codex: Codex API rejects it when default tools\n * (image_gen, web_search) are active, making agent sessions unusable.\n */\nexport const CLAUDE_EFFORT_VALUES = [\"low\", \"medium\", \"high\", \"xhigh\", \"max\"] as const;\nexport const CODEX_EFFORT_VALUES = [\"low\", \"medium\", \"high\", \"xhigh\", \"max\"] as const;\nexport const MAESTRO_EFFORT_VALUES = [\"low\", \"medium\", \"high\", \"xhigh\", \"max\"] as const;\n\nexport type EffortLevel =\n | (typeof CLAUDE_EFFORT_VALUES)[number]\n | (typeof CODEX_EFFORT_VALUES)[number]\n | (typeof MAESTRO_EFFORT_VALUES)[number];\n\n/**\n * Runtime iteration list (used by zod enums and any callers that need to\n * loop over every accepted value). Manually ordered for readability; the\n * `satisfies` check fails the build if an entry here isn't covered by the\n * per-agent unions above.\n */\nexport const EFFORT_VALUES = [\n \"low\",\n \"medium\",\n \"high\",\n \"xhigh\",\n \"max\",\n] as const satisfies readonly EffortLevel[];\n\n/**\n * Normalized events yielded by any agent provider (claudeProvider, codexProvider).\n * The handler/event-processor consumes these without caring which backend produced them.\n *\n * `user_message` is the lone \"into-the-log\" variant — no provider yields it.\n * The query handler writes it directly to the conversation log right before\n * `runAgent()` starts, so cross-agent rollout reconstruction can pair every\n * assistant turn with the user prompt that triggered it. Consumers that only\n * react to provider output (e.g. processAgentEvent) can safely ignore it.\n */\n/**\n * Wire-safe projection of one task, carried by the `tasks` UnifiedEvent.\n *\n * This is also the on-disk shape of Otium's shared task store, so claude,\n * codex, and maestro render the same live panel from the same source of truth.\n */\nexport interface TaskSnapshot {\n id: string;\n subject: string;\n status: \"pending\" | \"in_progress\" | \"completed\";\n /** Task ids this one is blocked by; omitted when empty. */\n blockedBy?: string[];\n /** Present-continuous label for spinners, when set. */\n activeForm?: string;\n /** Owner / agent name for multi-agent runs, when set. */\n owner?: string;\n}\n\nexport type UnifiedEvent =\n | {\n type: \"user_message\";\n content: string;\n synthetic?: \"compaction\";\n /** Total ordered user submissions represented by one preempting provider turn. */\n consecutiveBatchSize?: number;\n /** Zero-based position within the ordered preemption batch. */\n consecutiveBatchIndex?: number;\n }\n | { type: \"session\"; sessionId: string }\n | {\n type: \"tool_use\";\n name: string;\n input: Record<string, unknown>;\n /** Provider-assigned id so the client can match tool_use→tool_result pairs. */\n toolUseId?: string;\n }\n | { type: \"tool_progress\"; toolName: string; elapsed: number }\n | { type: \"tool_use_summary\"; summary: string }\n // Provider reasoning/thinking summary text (Codex `reasoning` items; Claude\n // extended-thinking). Surfaced so background runs (cron/archiver) show the\n // agent's thought process, not just tool calls.\n | { type: \"reasoning\"; content: string }\n // Full task-list snapshot (replace, not delta) from Otium's shared task\n // store. Provider-native task/todo stores are not authoritative.\n | { type: \"tasks\"; tasks: TaskSnapshot[] }\n | {\n type: \"tool_result\";\n toolUseId: string;\n content: string;\n /** True when the tool call failed; absent/false means success. */\n isError?: boolean;\n metadata?: {\n truncatedForModel: boolean;\n originalBytes: number;\n returnedBytes: number;\n omittedBytes?: number;\n outputPath?: string;\n };\n }\n | { type: \"text_delta\"; content: string }\n | { type: \"text\"; content: string }\n | { type: \"result\"; content: string; stopReason: string; usage?: TokenUsage }\n | { type: \"file\"; path: string; source: string; origin: \"tag\" | \"extension\" }\n | {\n type: \"error\";\n content: string;\n usage?: TokenUsage;\n code?: \"budget_exceeded\";\n }\n | { type: \"status\"; content: string };\n\nexport interface AgentInputAttachment {\n id: string;\n type: \"image\" | \"file\" | \"audio\";\n filename: string;\n mimeType: string;\n sizeBytes: number;\n path: string;\n}\n\n/** Worker-side runtime tools proxy user-facing state back to the canonical\n * hub topic identified here. */\nexport interface PeerRuntimeBridgeContext {\n hubCellId: string;\n hostTopicId: string;\n hostQueryId: string;\n canSpawnSubagents: boolean;\n}\n\nexport interface AgentQueryOptions {\n agent: AgentKind;\n prompt: string;\n attachments?: AgentInputAttachment[];\n sessionId?: string | null;\n cwd: string;\n systemPrompt: string;\n userId?: string;\n session?: string;\n playwrightPort?: number;\n playwrightCapability?: string;\n bgBashPort?: number;\n sessionType?: \"dm\" | \"forum\" | \"ephemeral\" | \"manager\" | \"cron\";\n /** API topic id (REST/WS world). Carries per-query topic context for MCP servers. */\n topicId?: string;\n /** Direct parent topic id when this query runs inside a subagent room. */\n subagentParentTopicId?: string;\n /** API query id for the currently running turn. Used by runtime MCP tools. */\n queryId?: string;\n /** Optional wiki-memory topic id. Derived topics use their root origin here\n * while other per-topic MCP servers keep `topicId` bound to the live room. */\n wikiTopicId?: string;\n /** Whether self-config MCP may enqueue an automatic continue turn after set_* changes. */\n autoContinue?: boolean;\n /** Expose Otium-only visual panel tools for this turn. Default-deny. */\n visualTools?: boolean;\n /** Expose adapter-backed file-delivery tools for this turn. Default-deny. */\n fileDeliveryTools?: boolean;\n abortController?: AbortController;\n model?: string;\n /** Provider-side hard budget when the selected SDK supports one. */\n maxBudgetUsd?: number;\n depth?: number;\n agents?: Record<\n string,\n {\n description: string;\n prompt: string;\n model?: string;\n tools?: string[];\n maxTurns?: number;\n effort?: EffortLevel | number;\n }\n >;\n effort?: EffortLevel;\n /**\n * Per-API-call `max_tokens` ceiling on the assistant's output. Wired\n * through to the underlying provider request body for every agent\n * (claude/codex/maestro). Omit to inherit each provider SDK's per-model\n * default — for maestro that's the v0.1.21+ `getNativeMaxOutputTokens`\n * catalog (deepseek-pro=64K, kimi-k3=64K, kimi-k2.7-code=32K).\n *\n * Pass an explicit number when a specific topic / surface needs a tighter\n * latency cap or a higher ceiling for long-form generation (legal\n * report writing, multi-K Write/Edit file bodies). Pre-0.1.21 maestro\n * builds silently clamped at 4096 and truncated outputs mid-string;\n * setting this field is now the supported way to lift that ceiling.\n */\n maxTokens?: number;\n /**\n * v0.1.22+: Claude-Code-style deferred tool catalog + `ToolSearch` built-in.\n *\n * Wired straight through to `maestro-agent-sdk`'s\n * `AgentQueryOptions.enableToolSearch`. When `true`, the maestro provider\n * registers every MCP tool as deferred — schemas stay off the wire until\n * the model promotes them via `ToolSearch(\"select:Name1,Name2\")` or\n * `ToolSearch(\"keyword\")`. Active set persists across resume.\n *\n * Otium's maestro provider supplies `true` when the caller leaves this\n * option unset, because most forum turns carry enough MCP surface for the\n * reminder-token savings to outweigh the first-use `ToolSearch` round-trip.\n * Callers can still pass `false` per call when a narrow surface or\n * latency-sensitive workflow is better served by eager MCP schemas.\n *\n * No-op for claude / codex agents — they have their own deferred-tool\n * machinery owned by their respective SDKs.\n */\n enableToolSearch?: boolean;\n /**\n * Bounded tool results with the full output kept on disk.\n *\n * Wired to `maestro-agent-sdk`'s `AgentQueryOptions.toolResultTruncation`.\n * The SDK caps a string tool result, writes the untruncated bytes to a file,\n * and splices an opaque `maestro://tool-output/<id>` reference into the text\n * that the `ReadToolOutput` tool can page back through.\n *\n * The maestro provider enables it by default. Left unset, every tool result\n * — a whole-file `Read`, a wide `Grep`, a `WebFetch` of a large page —\n * entered the context at full size, and the `\"ReadToolOutput\"` entry in the\n * provider's builtin list was dead, because the SDK only registers that tool\n * when truncation is on with `saveFullOutput`.\n *\n * Pass an explicit object to tune the budget, or `{ enabled: false }` for a\n * call whose tool results must arrive whole.\n *\n * No-op for claude / codex agents — their SDKs do their own truncation.\n */\n toolResultTruncation?: {\n enabled?: boolean;\n maxBytes?: number;\n headBytes?: number;\n tailBytes?: number;\n saveFullOutput?: boolean;\n outputDir?: string;\n retentionDays?: number;\n ignoreTools?: string[];\n };\n /**\n * Claude-Code-compatible exact tool denylist. Maestro v0.1.42+ hides these\n * tools from provider schemas / ToolSearch and blocks dispatch if a stale\n * call still arrives. Claude maps this to its SDK option. Codex does not\n * support this name-based list; its provider-native multi-agent tool family\n * is disabled separately through the Codex feature config.\n */\n disallowedTools?: readonly string[];\n /**\n * Hard provider tool policy for auxiliary model calls.\n *\n * `\"none\"` removes MCP and provider-native tools before the request is\n * dispatched. `\"compaction-log\"` keeps provider-native tools disabled and\n * exposes only the host-scoped immutable log reader. Use these for untrusted\n * transcript transforms; reacting to tool events after dispatch is not a\n * security boundary.\n */\n toolPolicy?: \"none\" | \"compaction-log\";\n mcpEnabled?: string[] | null;\n peerBridge?: PeerRuntimeBridgeContext;\n mcpExtra?: Record<string, unknown>;\n /**\n * true for silent fork runs generating ask_session replies — restricts session-comm\n * outbound tools (ask/tell/abort) so the forked session can only produce text\n */\n silent?: boolean;\n}\n\n/** State file written to data/users/{userId}/active-queries/{topicId}.json while a query is running. */\nexport interface QueryState {\n topicId?: string;\n topicName?: string;\n task?: string; // first 100 chars of prompt, newlines normalized\n since: string; // ISO timestamp\n}\n",
22
+ "/**\n * Common context carried through the attachment/prompt-build pipeline.\n * Used by buildPromptFromMessage and related helpers.\n */\nexport interface SessionContext {\n userId: number;\n topicName?: string;\n userDir?: string;\n sessionType?: \"dm\" | \"forum\" | \"ephemeral\" | \"manager\" | \"cron\";\n}\n\nexport interface TokenUsage {\n /** Aggregate billable input across every model call made during this turn. */\n inputTokens: number;\n outputTokens: number;\n cacheCreationInputTokens?: number;\n cacheReadInputTokens?: number;\n /** Provider-reported query cost when available. */\n costUsd?: number;\n /** Tokens occupied by the latest model call, not aggregate turn spend. */\n contextTokens?: number;\n /** Provider-reported context window for the latest model call. */\n contextWindow?: number;\n}\n\n/** Agent identifier — one of the supported AI provider backends. */\nexport type AgentKind = \"maestro\" | \"claude\" | \"codex\";\n\nexport const SUPPORTED_AGENTS: readonly AgentKind[] = [\"maestro\", \"claude\", \"codex\"] as const;\n\nexport function isAgentKind(value: unknown): value is AgentKind {\n return typeof value === \"string\" && (SUPPORTED_AGENTS as readonly string[]).includes(value);\n}\n\n/**\n * Per-agent supported reasoning efforts. Single source of truth for both the\n * `EffortLevel` type and each registry's `validEfforts` runtime list — the\n * registries import these directly so adding a value in one place\n * propagates to validation, footer rendering, and zod enums.\n *\n * Claude SDK rejects 'minimal'; Codex SDK rejects 'max'. The two sets\n * intersect on low/medium/high/xhigh. Maestro (TS port) currently piggybacks\n * on the Anthropic provider, so its efforts mirror the Claude set; this can\n * narrow per-provider once Phase 5 lands.\n *\n * 'minimal' removed from codex: Codex API rejects it when default tools\n * (image_gen, web_search) are active, making agent sessions unusable.\n */\nexport const CLAUDE_EFFORT_VALUES = [\"low\", \"medium\", \"high\", \"xhigh\", \"max\"] as const;\nexport const CODEX_EFFORT_VALUES = [\"low\", \"medium\", \"high\", \"xhigh\", \"max\"] as const;\nexport const MAESTRO_EFFORT_VALUES = [\"low\", \"medium\", \"high\", \"xhigh\", \"max\"] as const;\n\nexport type EffortLevel =\n | (typeof CLAUDE_EFFORT_VALUES)[number]\n | (typeof CODEX_EFFORT_VALUES)[number]\n | (typeof MAESTRO_EFFORT_VALUES)[number];\n\n/**\n * Runtime iteration list (used by zod enums and any callers that need to\n * loop over every accepted value). Manually ordered for readability; the\n * `satisfies` check fails the build if an entry here isn't covered by the\n * per-agent unions above.\n */\nexport const EFFORT_VALUES = [\n \"low\",\n \"medium\",\n \"high\",\n \"xhigh\",\n \"max\",\n] as const satisfies readonly EffortLevel[];\n\n/**\n * Normalized events yielded by any agent provider (claudeProvider, codexProvider).\n * The handler/event-processor consumes these without caring which backend produced them.\n *\n * `user_message` is the lone \"into-the-log\" variant — no provider yields it.\n * The query handler writes it directly to the conversation log right before\n * `runAgent()` starts, so cross-agent rollout reconstruction can pair every\n * assistant turn with the user prompt that triggered it. Consumers that only\n * react to provider output (e.g. processAgentEvent) can safely ignore it.\n */\n/**\n * Wire-safe projection of one task, carried by the `tasks` UnifiedEvent.\n *\n * This is also the on-disk shape of Otium's shared task store, so claude,\n * codex, and maestro render the same live panel from the same source of truth.\n */\nexport interface TaskSnapshot {\n id: string;\n subject: string;\n status: \"pending\" | \"in_progress\" | \"completed\";\n /** Task ids this one is blocked by; omitted when empty. */\n blockedBy?: string[];\n /** Present-continuous label for spinners, when set. */\n activeForm?: string;\n /** Owner / agent name for multi-agent runs, when set. */\n owner?: string;\n}\n\nexport type UnifiedEvent =\n | {\n type: \"user_message\";\n content: string;\n synthetic?: \"compaction\";\n /** Total ordered user submissions represented by one preempting provider turn. */\n consecutiveBatchSize?: number;\n /** Zero-based position within the ordered preemption batch. */\n consecutiveBatchIndex?: number;\n }\n | { type: \"session\"; sessionId: string }\n | {\n type: \"tool_use\";\n name: string;\n input: Record<string, unknown>;\n /** Provider-assigned id so the client can match tool_use→tool_result pairs. */\n toolUseId?: string;\n }\n | { type: \"tool_progress\"; toolName: string; elapsed: number }\n | { type: \"tool_use_summary\"; summary: string }\n // Provider reasoning/thinking summary text (Codex `reasoning` items; Claude\n // extended-thinking). Surfaced so background runs (cron/archiver) show the\n // agent's thought process, not just tool calls.\n | { type: \"reasoning\"; content: string }\n // Full task-list snapshot (replace, not delta) from Otium's shared task\n // store. Provider-native task/todo stores are not authoritative.\n | { type: \"tasks\"; tasks: TaskSnapshot[] }\n | {\n type: \"tool_result\";\n toolUseId: string;\n content: string;\n /** True when the tool call failed; absent/false means success. */\n isError?: boolean;\n metadata?: {\n truncatedForModel: boolean;\n originalBytes: number;\n returnedBytes: number;\n omittedBytes?: number;\n outputPath?: string;\n };\n }\n | { type: \"text_delta\"; content: string }\n | { type: \"text\"; content: string }\n | { type: \"result\"; content: string; stopReason: string; usage?: TokenUsage }\n | { type: \"file\"; path: string; source: string; origin: \"tag\" | \"extension\" }\n | {\n type: \"error\";\n content: string;\n usage?: TokenUsage;\n code?: \"budget_exceeded\";\n }\n | { type: \"status\"; content: string };\n\nexport interface AgentInputAttachment {\n id: string;\n type: \"image\" | \"file\" | \"audio\";\n filename: string;\n mimeType: string;\n sizeBytes: number;\n path: string;\n}\n\n/** Worker-side runtime tools proxy user-facing state back to the canonical\n * hub topic identified here. */\nexport interface PeerRuntimeBridgeContext {\n hubCellId: string;\n hostTopicId: string;\n hostQueryId: string;\n canSpawnSubagents: boolean;\n}\n\nexport interface AgentQueryOptions {\n agent: AgentKind;\n prompt: string;\n attachments?: AgentInputAttachment[];\n sessionId?: string | null;\n cwd: string;\n systemPrompt: string;\n userId?: string;\n /** 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 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",
23
23
  "/**\n * Stringify an unknown thrown value for logging or user-visible messages.\n * Default fallback is `String(e)`. Pass an explicit fallback (e.g. \"unknown\")\n * to override what non-Error throws turn into.\n */\nexport function errMsg(e: unknown, fallback?: string): string {\n if (e instanceof Error) return e.message;\n return fallback ?? String(e);\n}\n",
24
24
  "import { errMsg } from \"#platform/error\";\nimport { logger } from \"#platform/logger\";\nimport { db } from \"#storage/forum-db\";\nimport { closeStorageDatabase, registerStorageSchemaInitializer } from \"#storage/storage-host\";\nimport { type AgentKind, isAgentKind } from \"#types\";\n\nexport { db };\n\nexport interface ForumTopicInfo {\n messageThreadId: number;\n sessionId: string;\n createdAt: string;\n name: string;\n description?: string;\n forkOrigin?: string;\n agent: AgentKind;\n}\n\nexport interface UserForumConfig {\n communicateThreadId?: number;\n dmSessionId?: string;\n topics: { [topicName: string]: ForumTopicInfo };\n}\n\nexport type TopicRow = {\n user_id: string;\n name: string;\n message_thread_id: number;\n session_id: string | null;\n created_at: string;\n description: string | null;\n fork_origin: string | null;\n agent: string | null;\n};\n\nexport type UserRow = {\n id: string;\n dm_session_id: string | null;\n communicate_thread_id: number | null;\n};\n\nfunction initializeForumSchema(): void {\n db.exec(`\n CREATE TABLE IF NOT EXISTS users (\n id TEXT PRIMARY KEY,\n dm_session_id TEXT,\n communicate_thread_id INTEGER\n );\n\n CREATE TABLE IF NOT EXISTS topics (\n user_id TEXT NOT NULL REFERENCES users(id),\n name TEXT NOT NULL,\n message_thread_id INTEGER NOT NULL,\n session_id TEXT,\n created_at TEXT NOT NULL,\n description TEXT,\n fork_origin TEXT,\n agent TEXT NOT NULL DEFAULT 'claude',\n mcp_enabled TEXT,\n mcp_extra TEXT,\n last_shown_model TEXT,\n last_shown_effort TEXT,\n last_shown_agent TEXT,\n PRIMARY KEY (user_id, name),\n UNIQUE (user_id, message_thread_id)\n );\n\n CREATE INDEX IF NOT EXISTS idx_topics_lookup ON topics(user_id, message_thread_id);\n`);\n\n function tryMigrate(sql: string, expectedMsg?: string): void {\n try {\n db.exec(sql);\n } catch (e) {\n if (expectedMsg && errMsg(e).includes(expectedMsg)) return;\n logger.error({ err: e, sql }, \"DB migration failed\");\n throw e;\n }\n }\n\n type SqlValue = string | number | bigint | boolean | null | Uint8Array;\n\n function sqlValue(value: unknown): SqlValue {\n if (value === undefined || value === null) return null;\n if (\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"bigint\" ||\n typeof value === \"boolean\"\n ) {\n return value;\n }\n if (value instanceof Uint8Array) return value;\n return String(value);\n }\n\n function columnExists(table: string, column: string): boolean {\n return db\n .query<{ name: string }, []>(`PRAGMA table_info(${table})`)\n .all()\n .some((c) => c.name === column);\n }\n\n function tableSql(table: string): string | null {\n return (\n db\n .query<{ sql: string }, string>(\n \"SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?\",\n )\n .get(table)?.sql ?? null\n );\n }\n\n function dropColumnIfExists(table: string, column: string): void {\n if (columnExists(table, column)) {\n tryMigrate(`ALTER TABLE ${table} DROP COLUMN ${column}`);\n }\n }\n\n function topicTableNeedsRebuild(): boolean {\n const sql = tableSql(\"topics\");\n if (!sql) return false;\n const cols = db.query<{ name: string }, []>(\"PRAGMA table_info(topics)\").all();\n const names = new Set(cols.map((c) => c.name));\n return (\n names.has(\"forum_group_id\") ||\n names.has(\"system_prompt_extra\") ||\n names.has(\"model\") ||\n names.has(\"effort\") ||\n names.has(\"model_pinned\") ||\n names.has(\"effort_pinned\") ||\n names.has(\"memory_files\") ||\n names.has(\"memory_summary\") ||\n names.has(\"privacy_mode\") ||\n names.has(\"advisor_enabled\") ||\n names.has(\"agent_settings\") ||\n !/PRIMARY KEY \\(\\s*user_id\\s*,\\s*name\\s*\\)/i.test(sql)\n );\n }\n\n function normalizeStoredAgent(value: unknown): AgentKind {\n if (isAgentKind(value)) return value;\n if (value === \"hermes\" || value === \"alpha\") return \"maestro\";\n return \"claude\";\n }\n\n function rebuildTopicsTableIfNeeded(): void {\n if (!topicTableNeedsRebuild()) return;\n\n const cols = db.query<{ name: string }, []>(\"PRAGMA table_info(topics)\").all();\n const has = new Set(cols.map((c) => c.name));\n const pick = (row: Record<string, unknown>, column: string, fallback: unknown = null) =>\n has.has(column) ? (row[column] ?? fallback) : fallback;\n const descriptionFor = (row: Record<string, unknown>) =>\n pick(row, \"description\", pick(row, \"system_prompt_extra\", null));\n\n const rows = db\n .query<Record<string, unknown>, []>(\"SELECT rowid AS __rowid, * FROM topics\")\n .all()\n .sort((a, b) => {\n const aCreated = String(pick(a, \"created_at\", \"\"));\n const bCreated = String(pick(b, \"created_at\", \"\"));\n const byDate = bCreated.localeCompare(aCreated);\n if (byDate !== 0) return byDate;\n return Number(b.__rowid ?? 0) - Number(a.__rowid ?? 0);\n });\n\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 db.exec(\"DROP TABLE IF EXISTS topics_new\");\n db.exec(`\n CREATE TABLE topics_new (\n user_id TEXT NOT NULL REFERENCES users(id),\n name TEXT NOT NULL,\n message_thread_id INTEGER NOT NULL,\n session_id TEXT,\n created_at TEXT NOT NULL,\n description TEXT,\n fork_origin TEXT,\n agent TEXT NOT NULL DEFAULT 'claude',\n mcp_enabled TEXT,\n mcp_extra TEXT,\n last_shown_model TEXT,\n last_shown_effort TEXT,\n last_shown_agent TEXT,\n PRIMARY KEY (user_id, name),\n UNIQUE (user_id, message_thread_id)\n )\n `);\n\n const insert = db.query(`\n INSERT OR IGNORE INTO topics_new\n (user_id, name, message_thread_id, session_id, created_at, description,\n fork_origin, agent, mcp_enabled, mcp_extra, last_shown_model,\n last_shown_effort, last_shown_agent)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n `);\n let inserted = 0;\n const fallbackCreatedAt = new Date().toISOString();\n for (const row of rows) {\n const result = insert.run(\n String(pick(row, \"user_id\", \"\")),\n String(pick(row, \"name\", \"\")),\n Number(pick(row, \"message_thread_id\", 0)),\n sqlValue(pick(row, \"session_id\", null)),\n String(pick(row, \"created_at\", fallbackCreatedAt)),\n sqlValue(descriptionFor(row)),\n sqlValue(pick(row, \"fork_origin\", null)),\n normalizeStoredAgent(pick(row, \"agent\", \"claude\")),\n sqlValue(pick(row, \"mcp_enabled\", null)),\n sqlValue(pick(row, \"mcp_extra\", null)),\n sqlValue(pick(row, \"last_shown_model\", null)),\n sqlValue(pick(row, \"last_shown_effort\", null)),\n sqlValue(pick(row, \"last_shown_agent\", null)),\n );\n if (Number(result.changes ?? 0) > 0) inserted += 1;\n }\n\n db.exec(\"DROP TABLE topics\");\n db.exec(\"ALTER TABLE topics_new RENAME TO topics\");\n db.exec(\n \"CREATE INDEX IF NOT EXISTS idx_topics_lookup ON topics(user_id, message_thread_id)\",\n );\n logger.info(\n { migrated: inserted, skippedConflicts: rows.length - inserted },\n \"topics schema migrated to current user-scoped schema\",\n );\n })();\n } finally {\n db.exec(`PRAGMA foreign_keys = ${previousForeignKeys ? \"ON\" : \"OFF\"}`);\n }\n }\n\n rebuildTopicsTableIfNeeded();\n\n tryMigrate(\"ALTER TABLE topics ADD COLUMN fork_origin TEXT\", \"duplicate column\");\n tryMigrate(\n \"ALTER TABLE topics ADD COLUMN agent TEXT NOT NULL DEFAULT 'claude'\",\n \"duplicate column\",\n );\n tryMigrate(\"ALTER TABLE topics ADD COLUMN mcp_enabled TEXT\", \"duplicate column\");\n tryMigrate(\"ALTER TABLE topics ADD COLUMN mcp_extra TEXT\", \"duplicate column\");\n tryMigrate(\"ALTER TABLE topics ADD COLUMN last_shown_model TEXT\", \"duplicate column\");\n tryMigrate(\"ALTER TABLE topics ADD COLUMN last_shown_effort TEXT\", \"duplicate column\");\n tryMigrate(\"ALTER TABLE topics ADD COLUMN last_shown_agent TEXT\", \"duplicate column\");\n\n for (const column of [\"privacy_mode\", \"advisor_enabled\", \"agent_settings\"]) {\n dropColumnIfExists(\"topics\", column);\n }\n dropColumnIfExists(\"users\", \"manager_session_id\");\n\n tryMigrate(\"DROP INDEX idx_topics_lookup\", \"no such index\");\n tryMigrate(\"CREATE INDEX IF NOT EXISTS idx_topics_lookup ON topics(user_id, message_thread_id)\");\n\n function assertColumn(table: string, column: string): void {\n if (!columnExists(table, column)) {\n throw new Error(`Schema migration failed: ${table}.${column} is missing`);\n }\n }\n\n for (const column of [\"id\", \"dm_session_id\", \"communicate_thread_id\"]) {\n assertColumn(\"users\", column);\n }\n for (const column of [\n \"user_id\",\n \"name\",\n \"message_thread_id\",\n \"session_id\",\n \"created_at\",\n \"description\",\n \"fork_origin\",\n \"agent\",\n \"mcp_enabled\",\n \"mcp_extra\",\n \"last_shown_model\",\n \"last_shown_effort\",\n \"last_shown_agent\",\n ]) {\n assertColumn(\"topics\", column);\n }\n}\n\nregisterStorageSchemaInitializer(initializeForumSchema, 10);\n\nexport function rowToTopic(row: TopicRow): ForumTopicInfo {\n if (!isAgentKind(row.agent)) throw new Error(`Invalid agent in DB: ${row.agent}`);\n const agent: AgentKind = row.agent;\n return {\n messageThreadId: row.message_thread_id,\n sessionId: row.session_id ?? \"\",\n createdAt: row.created_at,\n name: row.name,\n agent,\n ...(row.description && { description: row.description }),\n ...(row.fork_origin && { forkOrigin: row.fork_origin }),\n };\n}\n\nexport function flushSessionCache() {\n closeStorageDatabase();\n}\n\nexport { logger };\n",
25
25
  "import { type AgentKind, isAgentKind } from \"#types\";\nimport { db } from \"./schema\";\n\nexport function getTopicAgent(userId: number, topicName: string): AgentKind {\n const row = db\n .query<{ agent: string | null }, [string, string]>(\n \"SELECT agent FROM topics WHERE user_id = ? AND name = ?\",\n )\n .get(String(userId), topicName);\n const value = row?.agent;\n if (!isAgentKind(value)) throw new Error(`Invalid agent in DB: ${value}`);\n return value;\n}\n\nexport function setTopicAgent(userId: number, topicName: string, agent: AgentKind): boolean {\n const result = db\n .query(\"UPDATE topics SET agent = ? WHERE user_id = ? AND name = ?\")\n .run(agent, String(userId), topicName);\n return result.changes > 0;\n}\n",
@@ -3,7 +3,7 @@ import type { AgentKind, EffortLevel } from "../types";
3
3
  export type ApiTopicSwitchOutcome = {
4
4
  kind: "fresh";
5
5
  agent: AgentKind;
6
- reason: "no-history" | "bridge-failed";
6
+ reason: "no-history";
7
7
  } | {
8
8
  kind: "bridged";
9
9
  agent: AgentKind;
@@ -67,7 +67,7 @@ export type SelfConfigAgentSwitchResult = {
67
67
  outcome: {
68
68
  kind: "fresh";
69
69
  agent: AgentKind;
70
- reason: "no-history" | "bridge-failed";
70
+ reason: "no-history";
71
71
  } | {
72
72
  kind: "bridged";
73
73
  agent: AgentKind;
@@ -10,7 +10,6 @@ export declare const BROWSER_DIR: string;
10
10
  export declare const BROWSER_PROFILES_DIR: string;
11
11
  export declare const BINARIES_DIR: string;
12
12
  export declare const SECRETS_DIR: string;
13
- export declare const CONTEXTS_DIR: string;
14
13
  export declare const DM_WORKSPACE_DIR: string;
15
14
  export declare const SESSION_WORKSPACE_DIR: string;
16
15
  export declare const CLAUDE_EXECUTABLE: string | undefined;
@@ -64,6 +64,8 @@ export declare function consumePlaywrightUnavailable(userId: string, topic: stri
64
64
  */
65
65
  export interface RuntimeMcpBuildContext {
66
66
  userId: string;
67
+ /** Vault namespace when credentials belong to a different principal. */
68
+ vaultUserId?: string;
67
69
  /** "dm" for DM scope, topic/session name for forum/fork. */
68
70
  session: string;
69
71
  /** REST/WS topic id when known. Prefer for authorization/scope checks. */
@@ -183,6 +185,7 @@ export declare function getManagerMcpServers(opts: {
183
185
  */
184
186
  export declare function getForumMcpServers(opts: {
185
187
  userId: string;
188
+ vaultUserId?: string;
186
189
  session: string;
187
190
  topicId?: string;
188
191
  subagentParentTopicId?: string;
@@ -28,6 +28,8 @@ export interface DeferredInject {
28
28
  /** Topic execution epoch captured when this work was accepted. */
29
29
  runtimeEpoch?: number;
30
30
  userId: string;
31
+ /** Credential namespace when the executor and Vault owner differ. */
32
+ vaultUserId?: string;
31
33
  prompt: string;
32
34
  /** Inject source — the topic name/id this inject came from (never "user"). */
33
35
  origin: string;
@@ -105,8 +107,12 @@ export interface RoomQueryControl {
105
107
  durableRequestIds?: string[];
106
108
  /** Attachment ids currently being processed. User-turn preemption carries them forward. */
107
109
  attachments?: string[];
108
- /** Provider session id this turn resumed from. Superseding user turns restart from this base. */
110
+ /** Latest provider session id observed for this turn. */
109
111
  sessionId?: string | null;
112
+ /** True once the provider has published the native session backing this turn. */
113
+ providerSessionObserved?: boolean;
114
+ /** True once provider output proves that this turn's prompt reached the native session. */
115
+ providerTurnContentObserved?: boolean;
110
116
  abortController: AbortController;
111
117
  abortReason: AbortReason;
112
118
  /** Specific failure surfaced when infrastructure aborts the turn. */
@@ -12,7 +12,7 @@ export * from "./channel-context";
12
12
  export * from "./errors";
13
13
  export * from "./tasks";
14
14
  export * from "./turn-session";
15
- export { renderUserPromptBatch } from "./user-turn-envelope";
15
+ export { renderUserPromptBatch, renderUserTurnBatch } from "./user-turn-envelope";
16
16
  export * from "./visuals";
17
17
  /** Browser and background shell tools are part of every ordinary topic. */
18
18
  export declare function withDefaultPlaywright(configuredMcp: string[], isManager: boolean): string[];
@@ -48,6 +48,45 @@ export declare function deliverAskCallbackToCaller(pending: AskPendingFileRef &
48
48
  callerTopicId: string;
49
49
  callerUserId: string;
50
50
  }, sourceLabel: string, body: string, kind: "reply" | "error"): Promise<boolean>;
51
+ export type TopicRolloutReconstruction = {
52
+ kind: "rebuilt";
53
+ sessionId: string;
54
+ } | {
55
+ kind: "no-history";
56
+ } | {
57
+ kind: "failed";
58
+ error: string;
59
+ };
60
+ export declare function tryReconstructTopicRollout(opts: {
61
+ topicId: string;
62
+ topicTitle: string;
63
+ userId: string;
64
+ agent: AgentKind;
65
+ sessionId: string | null | undefined;
66
+ cwd: string;
67
+ model: string;
68
+ effort?: EffortLevel;
69
+ }): TopicRolloutReconstruction;
70
+ export type SessionRetryResolution = {
71
+ kind: "retry";
72
+ sessionId: string | null;
73
+ } | {
74
+ kind: "failed";
75
+ error: string;
76
+ };
77
+ export declare function resolveSessionRetry(opts: {
78
+ topicId: string;
79
+ topicTitle: string;
80
+ userId: string;
81
+ agent: AgentKind;
82
+ sessionId: string | null | undefined;
83
+ cwd: string;
84
+ silent: boolean;
85
+ model: string;
86
+ effort?: EffortLevel;
87
+ externalSessionOwner?: boolean;
88
+ onSessionReset?: () => void;
89
+ }): SessionRetryResolution;
51
90
  export interface AiTurnSettlement {
52
91
  queryId: string;
53
92
  kind: "completed" | "aborted" | "error";
@@ -106,6 +145,8 @@ export interface AiTurnExecutionOptions {
106
145
  export interface StartAiTurnParams extends AiTurnExecutionOptions {
107
146
  topic: AiTurnTopic;
108
147
  userId: string;
148
+ /** Credential namespace. Defaults to userId for backwards compatibility. */
149
+ vaultUserId?: string;
109
150
  prompt: string;
110
151
  allowAutoContinue: boolean;
111
152
  agentOverride?: AgentKind;
@@ -2,7 +2,14 @@
2
2
  export interface UserTurnEnvelope {
3
3
  prompt: string;
4
4
  attachments?: string[];
5
+ /** Authenticated human author. Execution may still run as the local principal. */
6
+ actorUserId?: string;
7
+ /** Display-only author label captured by the trusted ingress. */
8
+ actorLabel?: string;
5
9
  }
6
10
  export declare function legacyUserTurnEnvelope(prompt: string, attachments?: string[]): UserTurnEnvelope;
7
11
  export declare function flattenUserTurnAttachments(messages: readonly UserTurnEnvelope[]): string[] | undefined;
8
12
  export declare function renderUserPromptBatch(prompts: readonly string[]): string;
13
+ export declare function renderUserTurnPrompt(message: UserTurnEnvelope): string;
14
+ /** Render ordered user submissions while retaining their structured authorship. */
15
+ export declare function renderUserTurnBatch(messages: readonly UserTurnEnvelope[]): string;
@@ -19,10 +19,14 @@ export interface RuntimeUserTurnExecution {
19
19
  bridgeSessionFromHistory?: boolean;
20
20
  peerBridge?: PeerRuntimeBridgeContext;
21
21
  from?: string;
22
+ /** Vault namespace for this turn, independent from the local execution principal. */
23
+ vaultUserId?: string;
22
24
  /** Newly accepted user texts not yet recorded in the unified conversation log. */
23
25
  conversationPrompts?: string[];
24
26
  /** Number of leading userMessages already present in the unified conversation log. */
25
27
  loggedUserMessageCount?: number;
28
+ /** Native session whose provider output proves it accepted this request's user turn. */
29
+ providerSessionId?: string;
26
30
  /** Request ids whose ordered messages were folded into this replacement. */
27
31
  supersededRequestIds?: string[];
28
32
  }
@@ -71,10 +75,23 @@ export declare function mergeRuntimeUserTurnRequest(input: {
71
75
  execution: RuntimeUserTurnExecution;
72
76
  topicEpoch: number;
73
77
  alreadyIncludedRequestIds?: string[];
78
+ /** Requests already committed to the provider's native session; keep their lineage, not prompts. */
79
+ omitRequestIds?: string[];
74
80
  }): {
75
81
  requestId: string;
76
82
  supersededRequestIds: string[];
77
83
  };
84
+ /**
85
+ * Record that provider output proves the native session contains this durable
86
+ * turn. A session-id event alone is insufficient: some providers publish it
87
+ * before appending the user prompt. This marker lets a different runtime
88
+ * process omit only a demonstrably committed prompt when it merges a steering
89
+ * message after preemption.
90
+ *
91
+ * Match only the exact request id. A late session event from a superseded turn
92
+ * must not mark its replacement (whose prompts have not reached the provider).
93
+ */
94
+ export declare function markRuntimeUserTurnProviderSessionObserved(topicId: string, requestId: string, sessionId: string): boolean;
78
95
  export declare function markRuntimeUserTurnMessagesLogged(topicId: string, requestId: string, ownerId: string, loggedUserMessages: readonly UserTurnEnvelope[]): boolean;
79
96
  export declare function claimNextRuntimeUserTurnRequest(ownerId: string, now?: number): RuntimeUserTurnRequest | null;
80
97
  export declare function markRuntimeUserTurnRunning(topicId: string, requestId: string, ownerId: string, queryId: string): boolean;
@@ -169,6 +169,8 @@ export interface AgentQueryOptions {
169
169
  cwd: string;
170
170
  systemPrompt: string;
171
171
  userId?: string;
172
+ /** Credential namespace when it differs from the execution principal. */
173
+ vaultUserId?: string;
172
174
  session?: string;
173
175
  playwrightPort?: number;
174
176
  playwrightCapability?: string;
@@ -1 +1 @@
1
- export declare const NEGOTIUM_VERSION = "0.2.4";
1
+ export declare const NEGOTIUM_VERSION = "0.2.5";
package/dist/vault.js CHANGED
@@ -106,7 +106,6 @@ var BROWSER_DIR = resolveLocalStateDir("NEGOTIUM_BROWSER_DIR", "browser");
106
106
  var BROWSER_PROFILES_DIR = resolve(BROWSER_DIR, "profiles");
107
107
  var BINARIES_DIR = resolve(STATE_DIR, "binaries");
108
108
  var SECRETS_DIR = resolve(STATE_DIR, "secrets");
109
- var CONTEXTS_DIR = resolve(STATE_DIR, "data", "contexts");
110
109
  var DM_WORKSPACE_DIR = resolve(STATE_DIR, "data", "dm");
111
110
  var SESSION_WORKSPACE_DIR = resolve(STATE_DIR, "data", "sessions");
112
111
  var CLAUDE_EXECUTABLE_ENV = envText("NEGOTIUM_CLAUDE_EXECUTABLE");
@@ -249,7 +248,6 @@ mkdirSync(WORKSPACE_DIR, { recursive: true });
249
248
  mkdirSync(TOPIC_WORKSPACE_DIR, { recursive: true });
250
249
  mkdirSync(SHARED_WIKI_DIR, { recursive: true });
251
250
  mkdirSync(CRON_WORKSPACE_DIR, { recursive: true });
252
- mkdirSync(CONTEXTS_DIR, { recursive: true });
253
251
  mkdirSync(DM_WORKSPACE_DIR, { recursive: true });
254
252
  mkdirSync(SESSION_WORKSPACE_DIR, { recursive: true });
255
253
  mkdirSync(BROWSER_DIR, { recursive: true });
@@ -615,4 +613,4 @@ export {
615
613
  VAULT_DESCRIPTION_MAX_LENGTH
616
614
  };
617
615
 
618
- //# debugId=1738D0D84B1E4C1764756E2164756E21
616
+ //# debugId=330AC50C00EFAF5164756E2164756E21