negotium 0.2.2 → 0.2.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent-helpers.js +3117 -2915
- package/dist/agent-helpers.js.map +38 -37
- package/dist/background-bash.js.map +1 -1
- package/dist/browser-runtime.js +137 -21
- package/dist/browser-runtime.js.map +10 -9
- package/dist/{chunk-kc5kmr95.js → chunk-1s9ryz8g.js} +1195 -21
- package/dist/chunk-1s9ryz8g.js.map +35 -0
- package/dist/hosted-agent.js +60 -48
- package/dist/hosted-agent.js.map +10 -10
- package/dist/main.js +3038 -3357
- package/dist/main.js.map +35 -35
- package/dist/mcp-factories.js +6227 -6021
- package/dist/mcp-factories.js.map +40 -39
- package/dist/prompts.js.map +1 -1
- package/dist/query-runtime.js +22 -2
- package/dist/query-runtime.js.map +4 -4
- package/dist/registry.js +169 -213
- package/dist/registry.js.map +8 -9
- package/dist/rollout.js +1 -1
- package/dist/runtime/src/agents/codex-app-server.ts +136 -0
- package/dist/runtime/src/agents/codex-native-multi-agent.ts +1 -1
- package/dist/runtime/src/agents/codex-provider.ts +21 -11
- package/dist/runtime/src/agents/codex-registry.ts +9 -17
- package/dist/runtime/src/agents/contracts.ts +2 -0
- package/dist/runtime/src/agents/execution-host.ts +6 -0
- package/dist/runtime/src/agents/fork.ts +24 -18
- package/dist/runtime/src/agents/idle-archiver.ts +7 -2
- package/dist/runtime/src/agents/index.ts +2 -1
- package/dist/runtime/src/agents/maestro-registry.ts +26 -7
- package/dist/runtime/src/agents/memory-archive-policy.ts +20 -0
- package/dist/runtime/src/agents/rollout/codex.ts +6 -5
- package/dist/runtime/src/agents/rollout/shared.ts +3 -5
- package/dist/runtime/src/mcp/factories/session-comm.ts +12 -0
- package/dist/runtime/src/mcp/session-comm/default-host.ts +16 -0
- package/dist/runtime/src/mcp/session-comm/server.ts +25 -0
- package/dist/runtime/src/platform/config.ts +4 -1
- package/dist/runtime/src/platform/playwright/manager.ts +57 -1
- package/dist/runtime/src/platform/playwright/profile-management.ts +33 -0
- package/dist/runtime/src/platform/playwright/public-runtime.ts +5 -0
- package/dist/runtime/src/platform/playwright/vault-broker.ts +9 -10
- package/dist/runtime/src/storage/browser-profiles.ts +35 -10
- package/dist/runtime/src/storage/storage-host.ts +31 -5
- package/dist/runtime/src/storage/vault.ts +30 -2
- package/dist/runtime/src/topics/derive.ts +38 -2
- package/dist/runtime/src/topics/lifecycle.ts +12 -2
- package/dist/runtime/src/version.ts +1 -1
- package/dist/runtime-helpers.js +22 -2
- package/dist/runtime-helpers.js.map +4 -4
- package/dist/storage.js +22 -2
- package/dist/storage.js.map +4 -4
- package/dist/types/packages/core/src/agents/codex-app-server.d.ts +13 -0
- package/dist/types/packages/core/src/agents/codex-native-multi-agent.d.ts +1 -0
- package/dist/types/packages/core/src/agents/contracts.d.ts +2 -0
- package/dist/types/packages/core/src/agents/execution-host.d.ts +2 -0
- package/dist/types/packages/core/src/agents/fork.d.ts +8 -7
- package/dist/types/packages/core/src/agents/memory-archive-policy.d.ts +10 -0
- package/dist/types/packages/core/src/agents/rollout/codex.d.ts +4 -2
- package/dist/types/packages/core/src/mcp/factories/session-comm.d.ts +1 -0
- package/dist/types/packages/core/src/platform/playwright/manager.d.ts +15 -0
- package/dist/types/packages/core/src/platform/playwright/profile-management.d.ts +8 -0
- package/dist/types/packages/core/src/platform/playwright/public-runtime.d.ts +2 -1
- package/dist/types/packages/core/src/storage/browser-profiles.d.ts +3 -1
- package/dist/types/packages/core/src/storage/storage-host.d.ts +1 -0
- package/dist/types/packages/core/src/storage/vault.d.ts +8 -0
- package/dist/types/packages/core/src/version.d.ts +1 -1
- package/dist/vault.js +19 -3
- package/dist/vault.js.map +4 -4
- package/package.json +2 -2
- package/dist/chunk-kc5kmr95.js.map +0 -19
- package/dist/runtime/src/migration/single-user.ts +0 -805
package/dist/registry.js.map
CHANGED
|
@@ -1,18 +1,17 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../../../packages/core/src/agents/claude-registry.ts", "../../../packages/core/src/agents/codex-registry.ts", "../../../packages/core/src/
|
|
3
|
+
"sources": ["../../../packages/core/src/agents/claude-registry.ts", "../../../packages/core/src/agents/codex-registry.ts", "../../../packages/core/src/agents/codex-app-server.ts", "../../../packages/core/src/agents/codex-native-multi-agent.ts", "../../../packages/core/src/version.ts", "../../../packages/core/src/agents/maestro-registry.ts", "../../../packages/core/src/agents/registry.ts", "../src/registry.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
5
|
"import { existsSync, mkdirSync, readdirSync, renameSync, unlinkSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport type { AgentRegistry, AgentRegistryOperations } from \"#agents/contracts\";\nimport { encodeClaudeCwd, writeClaudeRollout } from \"#agents/rollout/claude\";\nimport { MODEL_FABLE, MODEL_OPUS, MODEL_SONNET } from \"#platform/config\";\nimport { logger } from \"#platform/logger\";\nimport { CLAUDE_EFFORT_VALUES, type EffortLevel } from \"#types\";\n\nconst ALIAS_MAP: Record<string, string> = {\n sonnet: MODEL_SONNET,\n opus: MODEL_OPUS,\n fable: MODEL_FABLE,\n};\n\nconst VALID_ALIASES = new Set(Object.keys(ALIAS_MAP));\nconst VALID_EFFORTS = new Set<EffortLevel>(CLAUDE_EFFORT_VALUES);\n\nexport const claudeRegistry: AgentRegistry = {\n kind: \"claude\",\n defaultModel: \"sonnet\",\n defaultEffort: \"high\",\n\n expandModelAlias(s) {\n return ALIAS_MAP[s] ?? s;\n },\n\n validateModel(s) {\n return VALID_ALIASES.has(s);\n },\n\n validEfforts: CLAUDE_EFFORT_VALUES,\n validateEffort(s) {\n return VALID_EFFORTS.has(s);\n },\n\n footerLabel(model, effort) {\n return effort ? `${model} · ${effort}` : model;\n },\n};\n\nexport const claudeRegistryOperations: AgentRegistryOperations = {\n writeRollout(opts) {\n // `reuseSessionId` (if any) becomes the SDK resume key + path component,\n // so claude→codex→claude lands at the original `~/.claude/projects/<dir>/<id>.jsonl`\n // instead of orphaning a fresh UUID every switch.\n const { sessionId, rolloutPath } = writeClaudeRollout({\n cwd: opts.cwd,\n entries: opts.entries,\n model: claudeRegistry.expandModelAlias(opts.model ?? claudeRegistry.defaultModel),\n ...(opts.reuseSessionId ? { sessionId: opts.reuseSessionId } : {}),\n });\n return { sessionId, rolloutPath };\n },\n\n // Claude has a native fork API in @anthropic-ai/claude-agent-sdk that produces\n // a byte-equivalent copy of the parent rollout. Preserves tool history\n // structurally, so the fork is indistinguishable from the parent on resume.\n //\n // SDK ≥0.3.19x semantics: `dir` is where to FIND the parent session (lookup\n // scope), NOT the destination — passing the derived topic's cwd made lookup\n // fail (\"Session … not found in project directory\"). The fork file is always\n // written NEXT TO the parent rollout, so after forking we move it into the\n // derived cwd's project dir where a resume from that cwd expects it.\n async forkSession({ parentSessionId, cwd, title }) {\n const { forkSession } = await import(\"@anthropic-ai/claude-agent-sdk\");\n // Omit `dir`: the parent session lives under the SOURCE topic's project\n // dir, which this registry never receives — global search finds it.\n const result = await forkSession(parentSessionId, {\n ...(title ? { title } : {}),\n });\n const projectsRoot = join(homedir(), \".claude\", \"projects\");\n const destDir = join(projectsRoot, encodeClaudeCwd(cwd));\n const destPath = join(destDir, `${result.sessionId}.jsonl`);\n if (!existsSync(destPath)) {\n const sourcePath = readdirSync(projectsRoot)\n .map((d) => join(projectsRoot, d, `${result.sessionId}.jsonl`))\n .find((p) => existsSync(p));\n if (!sourcePath) {\n throw new Error(\n `claude forkSession: fork rollout ${result.sessionId}.jsonl not found under ${projectsRoot}`,\n );\n }\n mkdirSync(destDir, { recursive: true });\n renameSync(sourcePath, destPath);\n }\n return {\n forkId: result.sessionId,\n // Same project-dir layout as cleanupRollouts below — NOT under\n // `cwd/.claude/sessions/`. A wrong path here makes cleanupAgentFork's\n // existsSync always false, so silent-fork rollouts accumulate forever.\n rolloutPath: destPath,\n };\n },\n\n // Each Claude rollout lives at `~/.claude/projects/<encoded-cwd>/<sessionId>.jsonl`.\n // The encoded-cwd is deterministic so we can compute the path directly\n // without globbing — fast and robust against the SDK changing date layout.\n async cleanupRollouts({ cwd, sessionIds }) {\n const projectsDir = join(homedir(), \".claude\", \"projects\", encodeClaudeCwd(cwd));\n const failures: unknown[] = [];\n for (const sid of sessionIds) {\n const path = join(projectsDir, `${sid}.jsonl`);\n try {\n unlinkSync(path);\n } catch (e) {\n if ((e as NodeJS.ErrnoException)?.code !== \"ENOENT\") {\n logger.warn({ err: e, path }, \"claude cleanupRollouts: unlink failed\");\n failures.push(e);\n }\n }\n }\n if (failures.length > 0) {\n throw new AggregateError(failures, \"claude cleanupRollouts failed\");\n }\n },\n};\n",
|
|
6
|
-
"import { existsSync, unlinkSync } from \"node:fs\";\nimport {
|
|
7
|
-
"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",
|
|
8
|
-
"/** Sanitize a topic/session name for use in file paths.\n * Replaces non-alphanumeric characters (excluding Korean) with underscores.\n * Empty input (or input consisting only of disallowed chars) returns \"_\" so\n * callers always get a non-empty single path component.\n * @param name The raw topic or session name.\n * @param lowercase Whether to lowercase the result (default: false).\n * Use true for wiki paths; leave false for log file paths.\n */\nexport function sanitizeTopicName(name: string, lowercase = false): string {\n const safe = name.replace(/[^a-zA-Z0-9가-힣_-]/g, \"_\") || \"_\";\n return lowercase ? safe.toLowerCase() : safe;\n}\n\n/** Sanitize a file name for use in file paths. Allows dots.\n * Pure-dot results (\".\", \"..\") are replaced with \"_\" to block path-traversal\n * when the sanitized value is used as a standalone path component.\n */\nexport function sanitizeFileName(name: string): string {\n const safe = name.replace(/[^a-zA-Z0-9._-]/g, \"_\") || \"_\";\n if (safe === \".\" || safe === \"..\") return \"_\";\n return safe;\n}\n\n/** Sanitize an arbitrary ID (no Korean, no dots) for use in file paths. */\nexport function sanitizeId(id: string): string {\n return id.replace(/[^a-zA-Z0-9_-]/g, \"_\") || \"_\";\n}\n",
|
|
9
|
-
"
|
|
10
|
-
"
|
|
11
|
-
"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 { readConversation } from \"#storage/conversations\";\nimport { MAESTRO_EFFORT_VALUES } from \"#types\";\n\nconst ALIAS_MAP: Record<string, string> = {\n \"deepseek-pro\": \"deepseek-v4-pro\",\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\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: pair.userText },\n { role: \"assistant\", content: pair.assistantText },\n ]);\n const lines = [\n {\n _meta: {\n version: 1,\n cwd: options.cwd,\n createdAt: existingCreatedAt(path) ?? new Date().toISOString(),\n sdkVersion: \"0.1.54\",\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 const rollout = writeRollout({\n cwd: options.cwd,\n entries: readConversation(options.userId, options.topicName),\n ...(options.model ? { model: options.model } : {}),\n ...(options.effort ? { effort: options.effort } : {}),\n });\n return { forkId: rollout.sessionId, rolloutPath: rollout.rolloutPath };\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",
|
|
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
|
+
"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
|
+
"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.4\";\n",
|
|
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 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\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: pair.userText },\n { role: \"assistant\", content: pair.assistantText },\n ]);\n const lines = [\n {\n _meta: {\n version: 1,\n cwd: options.cwd,\n createdAt: existingCreatedAt(path) ?? new Date().toISOString(),\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",
|
|
12
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",
|
|
13
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"
|
|
14
13
|
],
|
|
15
|
-
"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,SAC5C,QAAQ,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|
1
|
+
import { type ChildProcessWithoutNullStreams, spawn } from "node:child_process";
|
|
2
|
+
import { codexCliScriptPath } from "#agents/codex-native-multi-agent";
|
|
3
|
+
import { hostedCodexHomePath } from "#agents/execution-host";
|
|
4
|
+
import { latestCodexRolloutPath } from "#agents/rollout/codex";
|
|
5
|
+
import { NEGOTIUM_VERSION } from "#version";
|
|
6
|
+
|
|
7
|
+
interface CodexAppServerForkResult {
|
|
8
|
+
forkId: string;
|
|
9
|
+
rolloutPath: string;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
interface CodexAppServerForkHost {
|
|
13
|
+
spawnServer(): ChildProcessWithoutNullStreams;
|
|
14
|
+
findRolloutPath(threadId: string): string | undefined;
|
|
15
|
+
timeoutMs: number;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
type JsonRpcResponse = {
|
|
19
|
+
id?: number;
|
|
20
|
+
result?: { thread?: { id?: unknown } };
|
|
21
|
+
error?: { message?: unknown };
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
export function createCodexAppServerForker(host: CodexAppServerForkHost) {
|
|
25
|
+
return async (parentThreadId: string): Promise<CodexAppServerForkResult> => {
|
|
26
|
+
const child = host.spawnServer();
|
|
27
|
+
|
|
28
|
+
return await new Promise<CodexAppServerForkResult>((resolve, reject) => {
|
|
29
|
+
let settled = false;
|
|
30
|
+
let stdoutBuffer = "";
|
|
31
|
+
let stderr = "";
|
|
32
|
+
const timer = setTimeout(
|
|
33
|
+
() => finish(new Error("Codex thread fork timed out")),
|
|
34
|
+
host.timeoutMs,
|
|
35
|
+
);
|
|
36
|
+
|
|
37
|
+
const finish = (error?: Error, result?: CodexAppServerForkResult) => {
|
|
38
|
+
if (settled) return;
|
|
39
|
+
settled = true;
|
|
40
|
+
clearTimeout(timer);
|
|
41
|
+
try {
|
|
42
|
+
child.stdin.end();
|
|
43
|
+
child.kill();
|
|
44
|
+
} catch {
|
|
45
|
+
// The app server may already have exited after stdin closed.
|
|
46
|
+
}
|
|
47
|
+
if (error) reject(error);
|
|
48
|
+
else if (result) resolve(result);
|
|
49
|
+
else reject(new Error("Codex thread fork returned no result"));
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
const send = (message: Record<string, unknown>) => {
|
|
53
|
+
child.stdin.write(`${JSON.stringify(message)}\n`);
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
child.stderr.on("data", (chunk) => {
|
|
57
|
+
if (stderr.length < 8_192) stderr += String(chunk);
|
|
58
|
+
});
|
|
59
|
+
child.on("error", (error) => finish(error));
|
|
60
|
+
child.on("exit", (code, signal) => {
|
|
61
|
+
if (settled) return;
|
|
62
|
+
const detail = signal ? `signal ${signal}` : `code ${code ?? 1}`;
|
|
63
|
+
finish(
|
|
64
|
+
new Error(
|
|
65
|
+
`Codex app server exited with ${detail}${stderr.trim() ? `: ${stderr.trim()}` : ""}`,
|
|
66
|
+
),
|
|
67
|
+
);
|
|
68
|
+
});
|
|
69
|
+
child.stdout.on("data", (chunk) => {
|
|
70
|
+
stdoutBuffer += String(chunk);
|
|
71
|
+
for (;;) {
|
|
72
|
+
const newline = stdoutBuffer.indexOf("\n");
|
|
73
|
+
if (newline < 0) break;
|
|
74
|
+
const line = stdoutBuffer.slice(0, newline);
|
|
75
|
+
stdoutBuffer = stdoutBuffer.slice(newline + 1);
|
|
76
|
+
let message: JsonRpcResponse;
|
|
77
|
+
try {
|
|
78
|
+
message = JSON.parse(line) as JsonRpcResponse;
|
|
79
|
+
} catch {
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
if (message.id === 1) {
|
|
84
|
+
if (message.error) {
|
|
85
|
+
finish(new Error(String(message.error.message || "Codex initialization failed")));
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
send({ method: "initialized" });
|
|
89
|
+
send({ id: 2, method: "thread/fork", params: { threadId: parentThreadId } });
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
if (message.id !== 2) continue;
|
|
93
|
+
if (message.error) {
|
|
94
|
+
finish(new Error(String(message.error.message || "Codex thread fork failed")));
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
const forkId = message.result?.thread?.id;
|
|
98
|
+
if (typeof forkId !== "string" || !forkId) {
|
|
99
|
+
finish(new Error("Codex thread fork returned no thread id"));
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
const rolloutPath = host.findRolloutPath(forkId);
|
|
103
|
+
if (!rolloutPath) {
|
|
104
|
+
finish(new Error(`Codex thread fork rollout was not found for ${forkId}`));
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
finish(undefined, { forkId, rolloutPath });
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
send({
|
|
113
|
+
id: 1,
|
|
114
|
+
method: "initialize",
|
|
115
|
+
params: {
|
|
116
|
+
clientInfo: { name: "negotium", version: NEGOTIUM_VERSION },
|
|
117
|
+
},
|
|
118
|
+
});
|
|
119
|
+
});
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const forkCodexThread = createCodexAppServerForker({
|
|
124
|
+
spawnServer() {
|
|
125
|
+
return spawn(process.execPath, [codexCliScriptPath(), "app-server", "--stdio"], {
|
|
126
|
+
env: { ...process.env, CODEX_HOME: hostedCodexHomePath() },
|
|
127
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
128
|
+
});
|
|
129
|
+
},
|
|
130
|
+
findRolloutPath: latestCodexRolloutPath,
|
|
131
|
+
timeoutMs: 15_000,
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
export async function forkCodexSession(parentThreadId: string): Promise<CodexAppServerForkResult> {
|
|
135
|
+
return await forkCodexThread(parentThreadId);
|
|
136
|
+
}
|
|
@@ -40,7 +40,7 @@ const SAFE_BUNDLED_CODEX_VERSION = BUNDLED_CODEX_VERSION.replace(/[^a-zA-Z0-9._-
|
|
|
40
40
|
const NEGOTIUM_MODEL_CACHE = `negotium-models-cache-${SAFE_BUNDLED_CODEX_VERSION}.json`;
|
|
41
41
|
const NEGOTIUM_MODEL_CATALOG = `negotium-model-catalog-${SAFE_BUNDLED_CODEX_VERSION}.json`;
|
|
42
42
|
|
|
43
|
-
function codexCliScriptPath(): string {
|
|
43
|
+
export function codexCliScriptPath(): string {
|
|
44
44
|
return join(dirname(bundledCodexPackagePath), "bin", "codex.js");
|
|
45
45
|
}
|
|
46
46
|
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { execFileSync } from "node:child_process";
|
|
2
2
|
import { existsSync, readFileSync, realpathSync, statSync } from "node:fs";
|
|
3
|
+
import { homedir } from "node:os";
|
|
3
4
|
import { dirname, isAbsolute, join, relative, resolve } from "node:path";
|
|
4
5
|
import type {
|
|
5
6
|
FileChangeItem,
|
|
@@ -21,7 +22,11 @@ import {
|
|
|
21
22
|
snapshotCodexChildren,
|
|
22
23
|
unregisterOwnedCodexPids,
|
|
23
24
|
} from "#agents/codex-tree-kill";
|
|
24
|
-
import {
|
|
25
|
+
import {
|
|
26
|
+
hostedCodexAuthFilePath,
|
|
27
|
+
hostedCodexHomePath,
|
|
28
|
+
hostedMcpServers,
|
|
29
|
+
} from "#agents/execution-host";
|
|
25
30
|
import {
|
|
26
31
|
migrateCodexRolloutNativeMultiAgentMetadata,
|
|
27
32
|
readCodexPatchCallIds,
|
|
@@ -635,19 +640,24 @@ export async function* codexProvider(opts: AgentQueryOptions): AsyncGenerator<Un
|
|
|
635
640
|
"codexProvider: starting turn",
|
|
636
641
|
);
|
|
637
642
|
|
|
638
|
-
const
|
|
639
|
-
|
|
643
|
+
const hostedCodexHome = hostedCodexHomePath();
|
|
644
|
+
const inheritedCodexHome = process.env.CODEX_HOME || join(homedir(), ".codex");
|
|
645
|
+
const codexEnvironment =
|
|
646
|
+
scopedBrowserCapability || resolve(hostedCodexHome) !== resolve(inheritedCodexHome)
|
|
640
647
|
? {
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
(entry): entry is [string, string] => typeof entry[1] === "string",
|
|
645
|
-
),
|
|
648
|
+
...Object.fromEntries(
|
|
649
|
+
Object.entries(process.env).filter(
|
|
650
|
+
(entry): entry is [string, string] => typeof entry[1] === "string",
|
|
646
651
|
),
|
|
647
|
-
|
|
648
|
-
|
|
652
|
+
),
|
|
653
|
+
CODEX_HOME: hostedCodexHome,
|
|
654
|
+
...(scopedBrowserCapability
|
|
655
|
+
? { [CODEX_BROWSER_CAPABILITY_ENV]: scopedBrowserCapability }
|
|
656
|
+
: {}),
|
|
649
657
|
}
|
|
650
|
-
:
|
|
658
|
+
: undefined;
|
|
659
|
+
const codex = new Codex({
|
|
660
|
+
...(codexEnvironment ? { env: codexEnvironment } : {}),
|
|
651
661
|
config: {
|
|
652
662
|
// Otium exposes delegation through runtime.spawn_subagent so child work
|
|
653
663
|
// gets its own room/card and its result is routed back to the parent.
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { existsSync, unlinkSync } from "node:fs";
|
|
2
|
-
import { homedir } from "node:os";
|
|
3
2
|
import { join } from "node:path";
|
|
3
|
+
import { forkCodexSession } from "#agents/codex-app-server";
|
|
4
4
|
import type { AgentRegistry, AgentRegistryOperations } from "#agents/contracts";
|
|
5
|
+
import { hostedCodexHomePath } from "#agents/execution-host";
|
|
5
6
|
import { writeCodexRollout } from "#agents/rollout/codex";
|
|
6
7
|
import { logger } from "#platform/logger";
|
|
7
|
-
import { readConversation } from "#storage/conversations";
|
|
8
8
|
import { CODEX_EFFORT_VALUES, type EffortLevel } from "#types";
|
|
9
9
|
|
|
10
10
|
const VALID_EFFORTS = new Set<EffortLevel>(CODEX_EFFORT_VALUES);
|
|
@@ -64,20 +64,12 @@ export const codexRegistryOperations: AgentRegistryOperations = {
|
|
|
64
64
|
return { sessionId: threadId, rolloutPath };
|
|
65
65
|
},
|
|
66
66
|
|
|
67
|
-
//
|
|
68
|
-
//
|
|
69
|
-
//
|
|
70
|
-
//
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
const entries = readConversation(userId, topicName);
|
|
74
|
-
const { threadId, rolloutPath } = writeCodexRollout({
|
|
75
|
-
cwd,
|
|
76
|
-
entries,
|
|
77
|
-
model: model ?? codexRegistry.defaultModel,
|
|
78
|
-
...(effort ? { effort } : {}),
|
|
79
|
-
});
|
|
80
|
-
return { forkId: threadId, rolloutPath };
|
|
67
|
+
// The TypeScript SDK does not expose forking yet, but the bundled Codex App
|
|
68
|
+
// Server does. Native thread/fork preserves the provider's stored prefix,
|
|
69
|
+
// including tool structure, which gives prompt caching the best chance to
|
|
70
|
+
// reuse the parent context. Callers retain unified-log synthesis as fallback.
|
|
71
|
+
async forkSession({ parentSessionId }) {
|
|
72
|
+
return await forkCodexSession(parentSessionId);
|
|
81
73
|
},
|
|
82
74
|
|
|
83
75
|
// Codex stores rollouts at `~/.codex/sessions/<YYYY>/<MM>/<DD>/rollout-<ts>-<threadId>.jsonl`.
|
|
@@ -87,7 +79,7 @@ export const codexRegistryOperations: AgentRegistryOperations = {
|
|
|
87
79
|
// is well under a millisecond on a warm filesystem.
|
|
88
80
|
async cleanupRollouts({ sessionIds }) {
|
|
89
81
|
if (sessionIds.length === 0) return;
|
|
90
|
-
const sessionsDir = join(
|
|
82
|
+
const sessionsDir = join(hostedCodexHomePath(), "sessions");
|
|
91
83
|
// No sessions directory means there are no provider rollouts left to remove.
|
|
92
84
|
if (!existsSync(sessionsDir)) return;
|
|
93
85
|
const failures: unknown[] = [];
|
|
@@ -43,6 +43,8 @@ export interface ForkRegistryOptions {
|
|
|
43
43
|
export interface ForkRegistryResult {
|
|
44
44
|
forkId: string;
|
|
45
45
|
rolloutPath: string;
|
|
46
|
+
/** Additional provider-owned files created for the fork. */
|
|
47
|
+
cleanupPaths?: string[];
|
|
46
48
|
}
|
|
47
49
|
|
|
48
50
|
export interface CleanupRolloutsOptions {
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
|
+
import { dirname } from "node:path";
|
|
2
3
|
import {
|
|
3
4
|
referencesRuntimeSecretStorage as defaultReferencesRuntimeSecretStorage,
|
|
4
5
|
shouldRedirectVaultTool as defaultShouldRedirectVaultTool,
|
|
@@ -123,3 +124,8 @@ export function hostedClaudeCodeExecutablePath(): string | undefined {
|
|
|
123
124
|
export function hostedCodexAuthFilePath(): string {
|
|
124
125
|
return activeHost().codexAuthFilePath();
|
|
125
126
|
}
|
|
127
|
+
|
|
128
|
+
/** The one Codex state root used by auth, rollouts, native forks, and SDK resume. */
|
|
129
|
+
export function hostedCodexHomePath(): string {
|
|
130
|
+
return dirname(hostedCodexAuthFilePath());
|
|
131
|
+
}
|