negotium 0.6.1 → 0.6.3

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/registry.js CHANGED
@@ -122,7 +122,7 @@ import { createRequire } from "module";
122
122
  import { dirname, join as join2 } from "path";
123
123
 
124
124
  // ../../packages/core/src/version.ts
125
- var NEGOTIUM_VERSION = "0.6.1";
125
+ var NEGOTIUM_VERSION = "0.6.3";
126
126
 
127
127
  // ../../packages/core/src/agents/codex-native-multi-agent.ts
128
128
  var moduleRequire = createRequire(import.meta.url);
@@ -480,4 +480,4 @@ export {
480
480
  getRegistry2 as getRegistry
481
481
  };
482
482
 
483
- //# debugId=F29DD0ABB63ED0EE64756E2164756E21
483
+ //# debugId=F7C88DC7E37FC7BF64756E2164756E21
@@ -6,12 +6,12 @@
6
6
  "import { existsSync, unlinkSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { forkCodexSession } from \"#agents/codex-app-server\";\nimport type { AgentRegistry, AgentRegistryOperations } from \"#agents/contracts\";\nimport { hostedCodexHomePath } from \"#agents/execution-host\";\nimport { writeCodexRollout } from \"#agents/rollout/codex\";\nimport { logger } from \"#platform/logger\";\nimport { CODEX_EFFORT_VALUES, type EffortLevel } from \"#types\";\n\nconst VALID_EFFORTS = new Set<EffortLevel>(CODEX_EFFORT_VALUES);\n\n// Codex CLI's own empirical default is gpt-5.6-sol (`codex exec` 2026-07-10 →\n// \"model: gpt-5.6-sol\"), but we deliberately default to gpt-5.6-luna — the\n// cheapest/fastest GPT-5.6 tier — for a general always-on assistant where most\n// queries are light. Heavier work escalates to terra/sol via set_model. This\n// value is passed explicitly to the SDK (see event-processor resolveDefaultModel),\n// so the footer and the actual model stay in sync.\nexport const codexRegistry: AgentRegistry = {\n kind: \"codex\",\n defaultModel: \"gpt-5.6-luna\",\n // defaultEffort intentionally omitted — Codex SDK treats absence as\n // \"reasoning off\". Setting \"high\"/etc. would silently flip on reasoning.\n\n expandModelAlias(s) {\n return s;\n },\n\n validateModel(s) {\n // Codex doesn't publish a closed model list and OpenAI ships new IDs\n // (gpt-5.6-sol, gpt-5.6-terra, gpt-5.6-luna, o3, ...) frequently. Best-effort: accept any\n // non-empty string. Bad IDs surface at SDK call time with a clear error.\n return typeof s === \"string\" && s.length > 0;\n },\n\n validEfforts: CODEX_EFFORT_VALUES,\n validateEffort(s) {\n // GPT-5.6 accepts low/medium/high/xhigh/max; 'minimal'\n // was removed because the Codex API rejects it when default tools\n // (image_gen, web_search) are active.\n return VALID_EFFORTS.has(s);\n },\n\n footerLabel(model, effort) {\n // Codex omits effort to mean \"reasoning off\". Show `(off)` explicitly so\n // the user can distinguish from claude (which always has a default).\n return `${model} · ${effort ?? \"(off)\"}`;\n },\n};\n\nexport const codexRegistryOperations: AgentRegistryOperations = {\n writeRollout(opts) {\n // Codex SDK exposes the resume key as `threadId`; AgentRegistry unifies\n // the name to `sessionId` so callers don't branch on agent.\n // `reuseSessionId` (if any) is forwarded as `threadId` so claude→codex→claude\n // round-trips also keep one continuous codex thread instead of orphaning a\n // fresh uuidv7 on every switch.\n const { threadId, rolloutPath } = writeCodexRollout({\n cwd: opts.cwd,\n entries: opts.entries,\n model: opts.model ?? codexRegistry.defaultModel,\n ...(opts.effort ? { effort: opts.effort } : {}),\n ...(opts.reuseSessionId ? { threadId: opts.reuseSessionId } : {}),\n });\n return { sessionId: threadId, rolloutPath };\n },\n\n // The TypeScript SDK does not expose forking yet, but the bundled Codex App\n // Server does. Native thread/fork preserves the provider's stored prefix,\n // including tool structure, which gives prompt caching the best chance to\n // reuse the parent context. Callers retain unified-log synthesis as fallback.\n async forkSession({ parentSessionId }) {\n return await forkCodexSession(parentSessionId);\n },\n\n // Codex stores rollouts at `~/.codex/sessions/<YYYY>/<MM>/<DD>/rollout-<ts>-<threadId>.jsonl`.\n // The date prefix is unknown at cleanup time (it's the *original* write\n // timestamp, not \"now\"), so we glob across the whole sessions tree by\n // threadId suffix. With at most a few thousand files in active use this\n // is well under a millisecond on a warm filesystem.\n async cleanupRollouts({ sessionIds }) {\n if (sessionIds.length === 0) return;\n const sessionsDir = join(hostedCodexHomePath(), \"sessions\");\n // No sessions directory means there are no provider rollouts left to remove.\n if (!existsSync(sessionsDir)) return;\n const failures: unknown[] = [];\n // One Glob per threadId so a single corrupt entry can't poison the rest.\n // Bun.Glob's `scan` yields paths relative to its base dir.\n for (const tid of sessionIds) {\n try {\n const glob = new Bun.Glob(`**/rollout-*-${tid}.jsonl`);\n for await (const rel of glob.scan({ cwd: sessionsDir, onlyFiles: true })) {\n const path = join(sessionsDir, rel);\n try {\n unlinkSync(path);\n } catch (e) {\n if ((e as NodeJS.ErrnoException)?.code !== \"ENOENT\") {\n logger.warn({ err: e, path }, \"codex cleanupRollouts: unlink failed\");\n failures.push(e);\n }\n }\n }\n } catch (e) {\n logger.warn({ err: e, threadId: tid }, \"codex cleanupRollouts: scan failed\");\n failures.push(e);\n }\n }\n if (failures.length > 0) {\n throw new AggregateError(failures, \"codex cleanupRollouts failed\");\n }\n },\n};\n",
7
7
  "import { type ChildProcessWithoutNullStreams, spawn } from \"node:child_process\";\nimport { codexCliScriptPath } from \"#agents/codex-native-multi-agent\";\nimport { hostedCodexHomePath } from \"#agents/execution-host\";\nimport { latestCodexRolloutPath } from \"#agents/rollout/codex\";\nimport { NEGOTIUM_VERSION } from \"#version\";\n\ninterface CodexAppServerForkResult {\n forkId: string;\n rolloutPath: string;\n}\n\ninterface CodexAppServerForkHost {\n spawnServer(): ChildProcessWithoutNullStreams;\n findRolloutPath(threadId: string): string | undefined;\n timeoutMs: number;\n}\n\ntype JsonRpcResponse = {\n id?: number;\n result?: { thread?: { id?: unknown } };\n error?: { message?: unknown };\n};\n\nexport function createCodexAppServerForker(host: CodexAppServerForkHost) {\n return async (parentThreadId: string): Promise<CodexAppServerForkResult> => {\n const child = host.spawnServer();\n\n return await new Promise<CodexAppServerForkResult>((resolve, reject) => {\n let settled = false;\n let stdoutBuffer = \"\";\n let stderr = \"\";\n const timer = setTimeout(\n () => finish(new Error(\"Codex thread fork timed out\")),\n host.timeoutMs,\n );\n\n const finish = (error?: Error, result?: CodexAppServerForkResult) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n try {\n child.stdin.end();\n child.kill();\n } catch {\n // The app server may already have exited after stdin closed.\n }\n if (error) reject(error);\n else if (result) resolve(result);\n else reject(new Error(\"Codex thread fork returned no result\"));\n };\n\n const send = (message: Record<string, unknown>) => {\n child.stdin.write(`${JSON.stringify(message)}\\n`);\n };\n\n child.stderr.on(\"data\", (chunk) => {\n if (stderr.length < 8_192) stderr += String(chunk);\n });\n child.on(\"error\", (error) => finish(error));\n child.on(\"exit\", (code, signal) => {\n if (settled) return;\n const detail = signal ? `signal ${signal}` : `code ${code ?? 1}`;\n finish(\n new Error(\n `Codex app server exited with ${detail}${stderr.trim() ? `: ${stderr.trim()}` : \"\"}`,\n ),\n );\n });\n child.stdout.on(\"data\", (chunk) => {\n stdoutBuffer += String(chunk);\n for (;;) {\n const newline = stdoutBuffer.indexOf(\"\\n\");\n if (newline < 0) break;\n const line = stdoutBuffer.slice(0, newline);\n stdoutBuffer = stdoutBuffer.slice(newline + 1);\n let message: JsonRpcResponse;\n try {\n message = JSON.parse(line) as JsonRpcResponse;\n } catch {\n continue;\n }\n\n if (message.id === 1) {\n if (message.error) {\n finish(new Error(String(message.error.message || \"Codex initialization failed\")));\n return;\n }\n send({ method: \"initialized\" });\n send({ id: 2, method: \"thread/fork\", params: { threadId: parentThreadId } });\n continue;\n }\n if (message.id !== 2) continue;\n if (message.error) {\n finish(new Error(String(message.error.message || \"Codex thread fork failed\")));\n return;\n }\n const forkId = message.result?.thread?.id;\n if (typeof forkId !== \"string\" || !forkId) {\n finish(new Error(\"Codex thread fork returned no thread id\"));\n return;\n }\n const rolloutPath = host.findRolloutPath(forkId);\n if (!rolloutPath) {\n finish(new Error(`Codex thread fork rollout was not found for ${forkId}`));\n return;\n }\n finish(undefined, { forkId, rolloutPath });\n return;\n }\n });\n\n send({\n id: 1,\n method: \"initialize\",\n params: {\n clientInfo: { name: \"negotium\", version: NEGOTIUM_VERSION },\n },\n });\n });\n };\n}\n\nconst forkCodexThread = createCodexAppServerForker({\n spawnServer() {\n return spawn(process.execPath, [codexCliScriptPath(), \"app-server\", \"--stdio\"], {\n env: { ...process.env, CODEX_HOME: hostedCodexHomePath() },\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n });\n },\n findRolloutPath: latestCodexRolloutPath,\n timeoutMs: 15_000,\n});\n\nexport async function forkCodexSession(parentThreadId: string): Promise<CodexAppServerForkResult> {\n return await forkCodexThread(parentThreadId);\n}\n",
8
8
  "import { spawn } from \"node:child_process\";\nimport { randomUUID } from \"node:crypto\";\nimport {\n chmodSync,\n copyFileSync,\n existsSync,\n mkdtempSync,\n readFileSync,\n renameSync,\n rmSync,\n unlinkSync,\n writeFileSync,\n} from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { tmpdir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport { NEGOTIUM_VERSION } from \"#version\";\n\ntype CodexModel = Record<string, unknown>;\ntype CodexModelCache = {\n client_version?: unknown;\n models?: unknown;\n};\n\nconst moduleRequire = createRequire(import.meta.url);\nconst codexSdkPackagePath = moduleRequire.resolve(\"@openai/codex-sdk/package.json\");\nconst codexSdkRequire = createRequire(codexSdkPackagePath);\nconst bundledCodexPackagePath = codexSdkRequire.resolve(\"@openai/codex/package.json\");\n\nfunction readPackageVersion(packageJsonPath: string): string {\n const parsed = JSON.parse(readFileSync(packageJsonPath, \"utf8\")) as { version?: unknown };\n if (typeof parsed.version !== \"string\" || !parsed.version.trim()) {\n throw new Error(`Codex package has no valid version: ${packageJsonPath}`);\n }\n return parsed.version;\n}\n\nexport const BUNDLED_CODEX_VERSION = readPackageVersion(bundledCodexPackagePath);\nconst SAFE_BUNDLED_CODEX_VERSION = BUNDLED_CODEX_VERSION.replace(/[^a-zA-Z0-9._-]/g, \"_\");\nconst NEGOTIUM_MODEL_CACHE = `negotium-models-cache-${SAFE_BUNDLED_CODEX_VERSION}.json`;\nconst NEGOTIUM_MODEL_CATALOG = `negotium-model-catalog-${SAFE_BUNDLED_CODEX_VERSION}.json`;\n\nexport function codexCliScriptPath(): string {\n return join(dirname(bundledCodexPackagePath), \"bin\", \"codex.js\");\n}\n\nfunction parseCodexModelCache(contents: string, sourcePath: string): CodexModelCache {\n let parsed: CodexModelCache;\n try {\n parsed = JSON.parse(contents) as CodexModelCache;\n } catch (error) {\n throw new Error(`Codex model cache is invalid JSON: ${sourcePath}`, { cause: error });\n }\n if (!Array.isArray(parsed.models) || parsed.models.length === 0) {\n throw new Error(`Codex model cache has no models: ${sourcePath}`);\n }\n return parsed;\n}\n\nfunction readCodexModelCache(cachePath: string): {\n contents: string;\n parsed: CodexModelCache;\n} {\n const contents = readFileSync(cachePath, \"utf8\");\n return { contents, parsed: parseCodexModelCache(contents, cachePath) };\n}\n\nfunction readCompatibleCodexModelCache(cachePath: string): {\n contents: string;\n parsed: CodexModelCache;\n} {\n const cache = readCodexModelCache(cachePath);\n if (cache.parsed.client_version !== BUNDLED_CODEX_VERSION) {\n const found =\n typeof cache.parsed.client_version === \"string\"\n ? cache.parsed.client_version\n : \"missing or invalid\";\n throw new Error(\n `Codex model cache version ${found} does not match Negotium's bundled Codex ${BUNDLED_CODEX_VERSION}: ${cachePath}`,\n );\n }\n return cache;\n}\n\nfunction writePrivateFileAtomic(path: string, contents: string): void {\n if (existsSync(path) && readFileSync(path, \"utf8\") === contents) return;\n\n const tempPath = `${path}.${process.pid}.${randomUUID()}.tmp`;\n try {\n writeFileSync(tempPath, contents, { encoding: \"utf8\", mode: 0o600 });\n renameSync(tempPath, path);\n chmodSync(path, 0o600);\n } finally {\n try {\n unlinkSync(tempPath);\n } catch {\n // renameSync normally consumed the temporary file.\n }\n }\n}\n\nexport function bundledCodexModelCachePath(authFilePath: string): string {\n return join(dirname(authFilePath), NEGOTIUM_MODEL_CACHE);\n}\n\nasync function bootstrapCodexModelCache(codexHome: string, cachePath: string): Promise<void> {\n const child = spawn(process.execPath, [codexCliScriptPath(), \"app-server\", \"--stdio\"], {\n env: { ...process.env, CODEX_HOME: codexHome },\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n });\n\n await new Promise<void>((resolve, reject) => {\n let settled = false;\n let stdoutBuffer = \"\";\n let stderr = \"\";\n const timer = setTimeout(\n () => finish(new Error(\"timed out while refreshing the Codex model catalog\")),\n 15_000,\n );\n\n const finish = (error?: Error) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n try {\n child.stdin.end();\n child.kill();\n } catch {\n // The app server may already have exited after stdin closed.\n }\n if (error) reject(error);\n else if (!existsSync(cachePath)) reject(new Error(\"Codex did not create its model cache\"));\n else resolve();\n };\n\n const send = (message: Record<string, unknown>) => {\n child.stdin.write(`${JSON.stringify(message)}\\n`);\n };\n\n child.stderr.on(\"data\", (chunk) => {\n if (stderr.length < 4_096) stderr += String(chunk);\n });\n child.on(\"error\", (error) => finish(error));\n child.on(\"exit\", (code, signal) => {\n if (!settled) {\n finish(\n new Error(\n `Codex model catalog refresh exited with ${signal ? `signal ${signal}` : `code ${code ?? 1}`}${stderr.trim() ? `: ${stderr.trim()}` : \"\"}`,\n ),\n );\n }\n });\n child.stdout.on(\"data\", (chunk) => {\n stdoutBuffer += String(chunk);\n for (;;) {\n const newline = stdoutBuffer.indexOf(\"\\n\");\n if (newline < 0) break;\n const line = stdoutBuffer.slice(0, newline);\n stdoutBuffer = stdoutBuffer.slice(newline + 1);\n let message: { id?: number; error?: { message?: string } };\n try {\n message = JSON.parse(line) as typeof message;\n } catch {\n continue;\n }\n if (message.id === 1) {\n if (message.error) {\n finish(new Error(message.error.message || \"Codex initialization failed\"));\n return;\n }\n send({ method: \"initialized\" });\n send({ id: 2, method: \"model/list\", params: { includeHidden: true } });\n } else if (message.id === 2) {\n if (message.error) {\n finish(new Error(message.error.message || \"Codex model listing failed\"));\n } else {\n finish();\n }\n return;\n }\n }\n });\n\n send({\n id: 1,\n method: \"initialize\",\n params: {\n clientInfo: { name: \"negotium\", version: NEGOTIUM_VERSION },\n capabilities: { experimentalApi: true },\n },\n });\n });\n}\n\nasync function bootstrapIsolatedCodexModelCache(\n authFilePath: string,\n bootstrap: (codexHome: string, cachePath: string) => Promise<void>,\n): Promise<string> {\n const sourceHome = dirname(authFilePath);\n const isolatedHome = mkdtempSync(join(tmpdir(), \"negotium-codex-models-\"));\n const isolatedCachePath = join(isolatedHome, \"models_cache.json\");\n\n try {\n const isolatedAuthPath = join(isolatedHome, \"auth.json\");\n copyFileSync(authFilePath, isolatedAuthPath);\n chmodSync(isolatedAuthPath, 0o600);\n\n // Preserve custom provider configuration while keeping the bundled CLI's\n // cache write completely outside the user's shared CODEX_HOME.\n const sourceConfigPath = join(sourceHome, \"config.toml\");\n if (existsSync(sourceConfigPath)) {\n const isolatedConfigPath = join(isolatedHome, \"config.toml\");\n copyFileSync(sourceConfigPath, isolatedConfigPath);\n chmodSync(isolatedConfigPath, 0o600);\n }\n\n await bootstrap(isolatedHome, isolatedCachePath);\n return readCompatibleCodexModelCache(isolatedCachePath).contents;\n } finally {\n rmSync(isolatedHome, { recursive: true, force: true });\n }\n}\n\nexport async function ensureCodexModelCache(\n authFilePath: string,\n bootstrap: (codexHome: string, cachePath: string) => Promise<void> = bootstrapCodexModelCache,\n): Promise<string> {\n const codexHome = dirname(authFilePath);\n const configuredCachePath = process.env.NEGOTIUM_CODEX_MODELS_CACHE_FILE;\n if (configuredCachePath) {\n if (!existsSync(configuredCachePath)) {\n throw new Error(`Configured Codex model cache does not exist: ${configuredCachePath}`);\n }\n readCompatibleCodexModelCache(configuredCachePath);\n return configuredCachePath;\n }\n\n // The global Codex CLI owns models_cache.json and may update it to a schema\n // newer than the SDK bundled by Negotium. Snapshot a cache generated for our\n // exact bundled version so later global CLI updates cannot break turns.\n const bundledCachePath = bundledCodexModelCachePath(authFilePath);\n const sharedCachePath = join(codexHome, \"models_cache.json\");\n if (existsSync(sharedCachePath)) {\n try {\n const shared = readCompatibleCodexModelCache(sharedCachePath);\n // Keep model metadata fresh while the global CLI remains compatible.\n writePrivateFileAtomic(bundledCachePath, shared.contents);\n return bundledCachePath;\n } catch {\n // A compatible private snapshot is safer than failing because another\n // process briefly exposed an incomplete shared-cache write.\n }\n }\n\n if (existsSync(bundledCachePath)) {\n try {\n readCompatibleCodexModelCache(bundledCachePath);\n return bundledCachePath;\n } catch {\n // Re-bootstrap below instead of passing a corrupt or version-mismatched\n // private snapshot into this SDK version.\n }\n }\n\n const refreshedContents = await bootstrapIsolatedCodexModelCache(authFilePath, bootstrap);\n writePrivateFileAtomic(bundledCachePath, refreshedContents);\n return bundledCachePath;\n}\n\n/**\n * Codex can resolve model metadata before `features.multi_agent=false`, so a\n * model-advertised v1/v2 value may still register native collaboration tools.\n * Feed Codex an authoritative copy of its own catalog with only that field\n * disabled. Runtime MCP delegation remains available independently.\n */\nexport function writeCodexCatalogWithNativeMultiAgentDisabled(\n authFilePath: string,\n sourcePath: string,\n): string {\n const codexHome = dirname(authFilePath);\n const outputPath = join(codexHome, NEGOTIUM_MODEL_CATALOG);\n\n const parsed = readCodexModelCache(sourcePath).parsed;\n\n const models = (parsed.models as unknown[]).map((model, index): CodexModel => {\n if (!model || typeof model !== \"object\" || Array.isArray(model)) {\n throw new Error(`Codex model cache entry ${index} is invalid: ${sourcePath}`);\n }\n return { ...(model as CodexModel), multi_agent_version: \"disabled\" };\n });\n const contents = `${JSON.stringify({ models }, null, 2)}\\n`;\n writePrivateFileAtomic(outputPath, contents);\n return outputPath;\n}\n",
9
- "export const NEGOTIUM_VERSION = \"0.6.1\";\n",
9
+ "export const NEGOTIUM_VERSION = \"0.6.3\";\n",
10
10
  "import { randomUUID } from \"node:crypto\";\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join, resolve } from \"node:path\";\nimport type { AgentRegistry, AgentRegistryOperations } from \"#agents/contracts\";\nimport { assertUuidLike, ensureCwdExists, extractChatPairs } from \"#agents/rollout/shared\";\nimport { logger } from \"#platform/logger\";\nimport { MAESTRO_EFFORT_VALUES } from \"#types\";\n\nconst ALIAS_MAP: Record<string, string> = {\n \"deepseek-pro\": \"deepseek-v4-pro\",\n // \"deepseek-flash\" was disabled in 0.1.25 because DeepSeek had retired its\n // old flash model. \"DeepSeek-V4-Flash-0731\" (released 2026-07-31) is an\n // unrelated, currently-live model reusing a similar name — verified with a\n // live API call before re-enabling this alias.\n \"deepseek-flash\": \"deepseek-v4-flash\",\n kimi: \"kimi-k3\",\n \"kimi-pro\": \"kimi-k3\",\n \"kimi-code\": \"kimi-k2.7-code\",\n};\nconst VALID_MODELS = new Set([...Object.keys(ALIAS_MAP), ...Object.values(ALIAS_MAP)]);\nconst VALID_EFFORTS = new Set(MAESTRO_EFFORT_VALUES);\n\nexport const maestroRegistry: AgentRegistry = {\n kind: \"maestro\",\n defaultModel: \"deepseek-pro\",\n defaultEffort: \"medium\",\n expandModelAlias(model) {\n return ALIAS_MAP[model] ?? model;\n },\n validateModel(model) {\n return VALID_MODELS.has(model);\n },\n validEfforts: MAESTRO_EFFORT_VALUES,\n validateEffort(effort) {\n return VALID_EFFORTS.has(effort);\n },\n footerLabel(model, effort) {\n return effort ? `${model} · ${effort}` : model;\n },\n};\n\nfunction maestroSessionsDir(): string {\n return join(\n process.env.MAESTRO_DATA_DIR\n ? resolve(process.env.MAESTRO_DATA_DIR)\n : join(homedir(), \".maestro\"),\n \"sessions\",\n );\n}\n\nfunction maestroSessionPath(sessionId: string): string {\n return join(maestroSessionsDir(), `${sessionId}.jsonl`);\n}\n\nfunction maestroActiveSessionPath(sessionId: string): string {\n return join(maestroSessionsDir(), `${sessionId}.active.jsonl`);\n}\n\nfunction existingCreatedAt(path: string): string | undefined {\n if (!existsSync(path)) return undefined;\n try {\n const firstLine = readFileSync(path, \"utf8\").split(\"\\n\", 1)[0];\n const parsed = JSON.parse(firstLine) as { _meta?: { createdAt?: unknown } };\n return typeof parsed._meta?.createdAt === \"string\" ? parsed._meta.createdAt : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Placeholder for a synthesized turn whose text is blank.\n *\n * Moonshot (Kimi) hard-rejects the *whole* request when any history message has\n * empty content — `Kimi API 400: the message at position N with role 'user'\n * must not be empty` (verified against the live API, kimi-k3). DeepSeek's\n * validator is laxer today but the same shape is not worth relying on.\n *\n * maestro-agent-sdk 0.2.1 drops empty assistant slots, but only in the\n * *content-block* form (`content: []`); the pair encoder below writes plain\n * strings, and `content: \"\"` still reaches the wire and 400s. Blank sides are\n * reachable here from real conversations — an attachment-only user submission\n * records a `user_message` with `content: \"\"`, and `renderUserPromptBatch`\n * passes it through verbatim — so the synthesized session must not contain one.\n *\n * We substitute rather than drop: dropping a pair would silently delete a turn\n * from the historical narrative the next agent reads, while a one-line marker\n * keeps the turn boundary and tells the model why the slot is thin.\n */\nconst BLANK_TURN_PLACEHOLDER = \"(no text content in this turn)\";\n\nfunction nonEmptyTurnText(text: string): string {\n return text.trim().length > 0 ? text : BLANK_TURN_PLACEHOLDER;\n}\n\nfunction writeRollout(options: Parameters<AgentRegistryOperations[\"writeRollout\"]>[0]) {\n const sessionId = options.reuseSessionId ?? randomUUID();\n assertUuidLike(\"sessionId\", sessionId);\n ensureCwdExists(options.cwd);\n const path = maestroSessionPath(sessionId);\n mkdirSync(maestroSessionsDir(), { recursive: true });\n const messages = extractChatPairs(options.entries).flatMap((pair) => [\n { role: \"user\", content: nonEmptyTurnText(pair.userText) },\n { role: \"assistant\", content: nonEmptyTurnText(pair.assistantText) },\n ]);\n const lines = [\n {\n _meta: {\n version: 1,\n cwd: options.cwd,\n createdAt: existingCreatedAt(path) ?? new Date().toISOString(),\n // Deliberately a literal, not the SDK's `MAESTRO_SDK_VERSION`: this\n // module must not statically import maestro-agent-sdk (asserted by\n // tests/core/daemon-import-boundaries.test.ts — the SDK stays off the\n // daemon startup path). The value names the session *format* version\n // this encoder targets, which is what a reader of the header needs.\n sdkVersion: \"0.2.0\",\n },\n },\n ...messages,\n ];\n writeFileSync(path, `${lines.map((line) => JSON.stringify(line)).join(\"\\n\")}\\n`, {\n mode: 0o600,\n });\n return { sessionId, rolloutPath: path };\n}\n\nexport const maestroRegistryOperations: AgentRegistryOperations = {\n writeRollout(options) {\n return writeRollout(options);\n },\n async forkSession(options) {\n // Fork the full raw history while preserving the compacted working view.\n // A compacted parent that cannot copy its active projection is not a usable\n // cache-preserving fork, so let the caller fall back to bounded synthesis.\n const { deleteMaestroSession, forkSessionAt, loadRawMaestroSession } = await import(\n \"maestro-agent-sdk\"\n );\n const parentMessages = loadRawMaestroSession(options.parentSessionId);\n if (!parentMessages) {\n throw new Error(`Maestro parent session not found: ${options.parentSessionId}`);\n }\n const parentHasActiveProjection = existsSync(maestroActiveSessionPath(options.parentSessionId));\n const fork = forkSessionAt({\n parentSessionId: options.parentSessionId,\n messageIndex: parentMessages.length,\n cwd: options.cwd,\n userId: String(options.userId),\n });\n if (parentHasActiveProjection && !fork.activeProjectionForked) {\n deleteMaestroSession(fork.sessionId);\n throw new Error(`Maestro active projection could not be forked: ${options.parentSessionId}`);\n }\n const activePath = maestroActiveSessionPath(fork.sessionId);\n return {\n forkId: fork.sessionId,\n rolloutPath: fork.rolloutPath,\n ...(existsSync(activePath) ? { cleanupPaths: [activePath] } : {}),\n };\n },\n async cleanupRollouts(options) {\n // Keep the SDK off the daemon startup path, but use its canonical cleanup\n // once a Maestro session is actually being removed. It also clears memory,\n // task, todo, and in-process file-state sidecars.\n const { deleteMaestroSession } = await import(\"maestro-agent-sdk\");\n const failures: unknown[] = [];\n for (const sessionId of options.sessionIds) {\n try {\n deleteMaestroSession(sessionId);\n const remaining = [\n maestroSessionPath(sessionId),\n maestroActiveSessionPath(sessionId),\n ].filter(existsSync);\n if (remaining.length > 0) {\n throw new Error(`Maestro session files remain after cleanup: ${remaining.join(\", \")}`);\n }\n } catch (error) {\n logger.warn({ err: error, sessionId }, \"maestro cleanupRollouts: cleanup failed\");\n failures.push(error);\n }\n }\n if (failures.length > 0) {\n throw new AggregateError(failures, \"Maestro rollout cleanup failed\");\n }\n },\n};\n",
11
11
  "import { claudeRegistry, claudeRegistryOperations } from \"#agents/claude-registry\";\nimport { codexRegistry, codexRegistryOperations } from \"#agents/codex-registry\";\nimport type { AgentRegistry, AgentRegistryOperations } from \"#agents/contracts\";\nimport { maestroRegistry, maestroRegistryOperations } from \"#agents/maestro-registry\";\nimport type { AgentKind } from \"#types\";\n\nexport type {\n AgentRegistry,\n AgentRegistryOperations,\n CleanupRolloutsOptions,\n ForkRegistryOptions,\n ForkRegistryResult,\n WriteRolloutOptions,\n WriteRolloutResult,\n} from \"#agents/contracts\";\n\nconst REGISTRIES: Record<AgentKind, AgentRegistry> = {\n claude: claudeRegistry,\n codex: codexRegistry,\n maestro: maestroRegistry,\n};\n\nexport function getRegistry(agent: AgentKind): AgentRegistry {\n return REGISTRIES[agent];\n}\n\nconst OPERATIONS: Record<AgentKind, AgentRegistryOperations> = {\n claude: claudeRegistryOperations,\n codex: codexRegistryOperations,\n maestro: maestroRegistryOperations,\n};\n\nexport function getRegistryOperations(agent: AgentKind): AgentRegistryOperations {\n return OPERATIONS[agent];\n}\n",
12
12
  "import {\n type AgentRegistry,\n type AgentRegistryOperations,\n type CleanupRolloutsOptions,\n type ForkRegistryOptions,\n type ForkRegistryResult,\n getRegistry as resolveCoreRegistry,\n getRegistryOperations as resolveCoreRegistryOperations,\n type WriteRolloutOptions,\n type WriteRolloutResult,\n} from \"@negotium/core/registry\";\n\nexport type {\n AgentRegistry,\n AgentRegistryOperations,\n CleanupRolloutsOptions,\n ForkRegistryOptions,\n ForkRegistryResult,\n WriteRolloutOptions,\n WriteRolloutResult,\n};\n\nexport const getRegistry: typeof resolveCoreRegistry = (agent) => resolveCoreRegistry(agent);\n\nexport const getRegistryOperations: typeof resolveCoreRegistryOperations = (agent) =>\n resolveCoreRegistryOperations(agent);\n"
13
13
  ],
14
14
  "mappings": ";;;;;;;;;;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SubmitRuntimeGatewayTurnParams {
38
38
  * it exactly as usual, and only declines to queue the turn.
39
39
  */
40
40
  respond?: boolean;
41
+ /** Hide both the injected prompt and provider output from the visible topic. */
42
+ silent?: boolean;
41
43
  /** Answer inside this thread instead of the room's main flow (S-13). */
42
44
  threadRootId?: string;
43
45
  /** Host-uploaded file ids already staged in this node's file store. */
@@ -64,7 +66,20 @@ function duplicateResult(
64
66
  actorUserId: string,
65
67
  payloadHash: string,
66
68
  ): SubmitRuntimeGatewayTurnResult {
67
- const message = getApiMessage(submission.topicId, submission.messageId);
69
+ const message =
70
+ getApiMessage(submission.topicId, submission.messageId) ??
71
+ (params.silent
72
+ ? {
73
+ id: submission.messageId,
74
+ topicId: params.topic.id,
75
+ authorId: actorUserId,
76
+ authorName: params.actorLabel,
77
+ sourceAdapter: "runtime-gateway",
78
+ sourceMessageId: params.clientMessageId,
79
+ text: params.text,
80
+ createdAt: submission.createdAt,
81
+ }
82
+ : null);
68
83
  if (!message) throw new Error("gateway submission references a missing canonical message");
69
84
  if (submission.payloadHash && submission.payloadHash !== payloadHash) {
70
85
  throw new RuntimeGatewayIdempotencyConflictError();
@@ -123,6 +138,7 @@ function gatewayPayloadHash(
123
138
  // would otherwise reuse the silent ACK and never queue the turn (or
124
139
  // vice versa), with nothing to tell the caller it was ignored.
125
140
  params.respond ?? true,
141
+ params.silent ?? false,
126
142
  // Part of the identity of the turn: the same key asked in the channel
127
143
  // and in a thread are different turns, and replaying one as the other
128
144
  // would answer in the wrong place.
@@ -209,7 +225,7 @@ export function submitRuntimeGatewayTurn(
209
225
 
210
226
  try {
211
227
  db.transaction(() => {
212
- appendApiMessage(message, { notify: false });
228
+ if (!params.silent) appendApiMessage(message, { notify: false });
213
229
  // The only thing `respond: false` skips. Everything else — the canonical
214
230
  // message, the accepted event, the idempotency record — still happens, so
215
231
  // a silent message is indistinguishable from a normal one everywhere
@@ -236,6 +252,7 @@ export function submitRuntimeGatewayTurn(
236
252
  loggedUserMessageCount: 0,
237
253
  vaultUserId: params.vaultUserId,
238
254
  actorUserId,
255
+ silent: params.silent === true,
239
256
  // The adapter's capability grant has to ride the durable request:
240
257
  // the turn worker builds the runtime MCP from `execution`, so a
241
258
  // flag left here undefined is what makes `show_html` and friends
@@ -256,13 +273,15 @@ export function submitRuntimeGatewayTurn(
256
273
  messageId: message.id,
257
274
  },
258
275
  });
259
- const messageEvent = appendRuntimeEvent("runtime-gateway-ingress", {
260
- type: "message",
261
- topicId: params.topic.id,
262
- payload: message,
263
- });
276
+ const messageEvent = params.silent
277
+ ? null
278
+ : appendRuntimeEvent("runtime-gateway-ingress", {
279
+ type: "message",
280
+ topicId: params.topic.id,
281
+ payload: message,
282
+ });
264
283
  submission.ackCursor = acceptedEvent.seq;
265
- submission.messageCursor = messageEvent.seq;
284
+ submission.messageCursor = messageEvent?.seq ?? 0;
266
285
  recordRuntimeGatewaySubmission(submission);
267
286
  })();
268
287
  } catch {
@@ -899,6 +899,7 @@ async function drainOneDurableUserTurn(): Promise<void> {
899
899
  sessionType: execution?.sessionType,
900
900
  visualTools: execution?.visualTools,
901
901
  fileDeliveryTools: execution?.fileDeliveryTools,
902
+ silent: execution?.silent,
902
903
  bridgeSessionFromHistory: execution?.bridgeSessionFromHistory,
903
904
  peerBridge: execution?.peerBridge,
904
905
  from: execution?.from,
@@ -36,6 +36,8 @@ export interface RuntimeGatewayTurnInput {
36
36
  allowAutoContinue?: boolean;
37
37
  threadRootId?: string;
38
38
  respond?: boolean;
39
+ /** Run without adding the injected prompt or output to the visible transcript. */
40
+ silent?: boolean;
39
41
  attachments?: string[];
40
42
  visualTools?: boolean;
41
43
  fileDeliveryTools?: boolean;
@@ -53,6 +55,23 @@ export interface RuntimeGatewayTurnAcknowledgement {
53
55
  cursor: number;
54
56
  }
55
57
 
58
+ export interface RuntimeGatewayTopicDeriveInput {
59
+ userId: string;
60
+ copyHistory: boolean;
61
+ name?: string;
62
+ }
63
+
64
+ export interface RuntimeGatewayDerivedTopic {
65
+ id: string;
66
+ title: string;
67
+ kind?: string;
68
+ agent?: string;
69
+ defaultModel?: string;
70
+ defaultEffort?: string;
71
+ parentTopicId?: string;
72
+ isFork?: boolean;
73
+ }
74
+
56
75
  export interface RuntimeGatewaySseEvent {
57
76
  id?: number;
58
77
  event: string;
@@ -357,6 +376,38 @@ export class RuntimeGatewayClient {
357
376
  return body;
358
377
  }
359
378
 
379
+ async deriveTopic(
380
+ topicId: string,
381
+ input: RuntimeGatewayTopicDeriveInput,
382
+ ): Promise<RuntimeGatewayDerivedTopic> {
383
+ const response = await this.send(
384
+ `/topics/${encodeURIComponent(topicId)}/derive`,
385
+ {
386
+ method: "POST",
387
+ headers: { "content-type": "application/json" },
388
+ body: JSON.stringify({ v: RUNTIME_GATEWAY_VERSION, ...input }),
389
+ },
390
+ this.requestTimeoutMs,
391
+ );
392
+ if (response.status !== 201) {
393
+ throw new RuntimeGatewayError("Runtime Gateway topic derive failed", "http", response.status);
394
+ }
395
+ const body = await json(response);
396
+ const topic = record(body)?.topic;
397
+ const topicRecord = record(topic);
398
+ if (
399
+ !topicRecord ||
400
+ typeof topicRecord.id !== "string" ||
401
+ typeof topicRecord.title !== "string"
402
+ ) {
403
+ throw new RuntimeGatewayError(
404
+ "Runtime Gateway topic derive response is incompatible",
405
+ "protocol",
406
+ );
407
+ }
408
+ return topic as unknown as RuntimeGatewayDerivedTopic;
409
+ }
410
+
360
411
  async ensureManagerTopic(userId: string): Promise<RuntimeGatewayManagerTopic> {
361
412
  const response = await this.send(
362
413
  "/manager-topic",
@@ -29,6 +29,7 @@ export interface RuntimeUserTurnExecution {
29
29
  sessionType?: "dm" | "forum" | "ephemeral" | "manager" | "cron";
30
30
  visualTools?: boolean;
31
31
  fileDeliveryTools?: boolean;
32
+ silent?: boolean;
32
33
  bridgeSessionFromHistory?: boolean;
33
34
  peerBridge?: PeerRuntimeBridgeContext;
34
35
  from?: string;
@@ -1 +1 @@
1
- export const NEGOTIUM_VERSION = "0.6.1";
1
+ export const NEGOTIUM_VERSION = "0.6.3";
@@ -168,6 +168,23 @@ class RuntimeGatewayClient {
168
168
  }
169
169
  return body;
170
170
  }
171
+ async deriveTopic(topicId, input) {
172
+ const response = await this.send(`/topics/${encodeURIComponent(topicId)}/derive`, {
173
+ method: "POST",
174
+ headers: { "content-type": "application/json" },
175
+ body: JSON.stringify({ v: RUNTIME_GATEWAY_VERSION, ...input })
176
+ }, this.requestTimeoutMs);
177
+ if (response.status !== 201) {
178
+ throw new RuntimeGatewayError("Runtime Gateway topic derive failed", "http", response.status);
179
+ }
180
+ const body = await json(response);
181
+ const topic = record(body)?.topic;
182
+ const topicRecord = record(topic);
183
+ if (!topicRecord || typeof topicRecord.id !== "string" || typeof topicRecord.title !== "string") {
184
+ throw new RuntimeGatewayError("Runtime Gateway topic derive response is incompatible", "protocol");
185
+ }
186
+ return topic;
187
+ }
171
188
  async ensureManagerTopic(userId) {
172
189
  const response = await this.send("/manager-topic", {
173
190
  method: "POST",
@@ -333,4 +350,4 @@ export {
333
350
  RUNTIME_GATEWAY_CONTROL_PATH
334
351
  };
335
352
 
336
- //# debugId=F53492F833A8A39364756E2164756E21
353
+ //# debugId=A4DC2005942CF37964756E2164756E21
@@ -2,9 +2,9 @@
2
2
  "version": 3,
3
3
  "sources": ["../../../packages/core/src/runtime-gateway.ts"],
4
4
  "sourcesContent": [
5
- "export const RUNTIME_GATEWAY_VERSION = 1 as const;\nexport const RUNTIME_GATEWAY_CONTROL_PATH = \"/api/v1/control/runtime/v1\";\n\nexport type RuntimeGatewayErrorKind = \"config\" | \"timeout\" | \"transport\" | \"protocol\" | \"http\";\n\nexport class RuntimeGatewayError extends Error {\n constructor(\n message: string,\n public readonly kind: RuntimeGatewayErrorKind,\n public readonly status?: number,\n ) {\n super(message);\n }\n}\n\nexport interface RuntimeGatewayHealth {\n ok: true;\n v: typeof RUNTIME_GATEWAY_VERSION;\n nodeId?: string;\n aiName?: string;\n capabilities: string[];\n cursor: number;\n}\n\nexport interface RuntimeGatewayTurnInput {\n topicId: string;\n /** Canonical principal on the execution node. */\n userId: string;\n /** Product-side actor, when it differs from the execution principal. */\n actorUserId?: string;\n actorLabel?: string;\n vaultUserId?: string;\n text: string;\n clientMessageId: string;\n requestId?: string;\n allowAutoContinue?: boolean;\n threadRootId?: string;\n respond?: boolean;\n attachments?: string[];\n visualTools?: boolean;\n fileDeliveryTools?: boolean;\n}\n\nexport interface RuntimeGatewayTurnAcknowledgement {\n ok: true;\n v: typeof RUNTIME_GATEWAY_VERSION;\n accepted: true;\n deduplicated: boolean;\n requestId: string;\n clientMessageId: string;\n topicId: string;\n messageId: string;\n cursor: number;\n}\n\nexport interface RuntimeGatewaySseEvent {\n id?: number;\n event: string;\n data: unknown;\n}\n\nexport interface RuntimeGatewayTopicUsage {\n queries: number;\n inputTokens: number;\n outputTokens: number;\n cacheCreationInputTokens: number;\n cacheReadInputTokens: number;\n estimatedCostUsd: number;\n}\n\nexport interface RuntimeGatewayManagerTopic {\n id: string;\n title: string;\n kind: \"manager\";\n agent?: \"claude\" | \"codex\" | \"maestro\";\n participants: Array<{ userId: string; role: \"owner\" | \"member\" }>;\n}\n\nexport interface RuntimeGatewayCronJob {\n id: string;\n name: string;\n executionPrincipalUserId: string;\n actorOwnerUserId: string;\n topicId: string;\n source: \"prompt\" | \"script\";\n script: string | null;\n scriptExists: boolean;\n prompt: string | null;\n promptPreview: string | null;\n summary: string | null;\n schedule: string;\n timezone: string | null;\n enabled: boolean;\n agent: \"claude\" | \"codex\" | \"maestro\" | null;\n model: string | null;\n effort: string | null;\n nextRunAt: string;\n runCount: number;\n lastRun: Record<string, unknown> | null;\n createdAt: string;\n updatedAt: string;\n canMutate: boolean;\n}\n\nexport interface RuntimeGatewayCronCreateInput {\n userId: string;\n actorUserId: string;\n topicId: string;\n name: string;\n script: string;\n schedule: string;\n timezone?: string;\n agent?: \"claude\" | \"codex\" | \"maestro\";\n model?: string;\n effort?: string;\n}\n\nexport interface RuntimeGatewayCronPatch {\n name?: string;\n topicId?: string;\n script?: string;\n schedule?: string;\n timezone?: string | null;\n enabled?: boolean;\n agent?: \"claude\" | \"codex\" | \"maestro\" | null;\n model?: string | null;\n effort?: string | null;\n}\n\nexport type RuntimeGatewayToken = string | (() => string | Promise<string>);\nexport type RuntimeGatewayFetch = (\n input: string | URL | Request,\n init?: RequestInit,\n) => Promise<Response>;\n\nexport interface RuntimeGatewayClientOptions {\n baseUrl: string;\n token: RuntimeGatewayToken;\n /** Loopback control path or an authenticated relay forward prefix. */\n pathPrefix?: string;\n fetch?: RuntimeGatewayFetch;\n requestTimeoutMs?: number;\n compactTimeoutMs?: number;\n}\n\nfunction record(value: unknown): Record<string, unknown> | null {\n return value && typeof value === \"object\" && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : null;\n}\n\nasync function json(response: Response): Promise<unknown> {\n try {\n return await response.json();\n } catch {\n throw new RuntimeGatewayError(\n \"Runtime Gateway returned invalid JSON\",\n \"protocol\",\n response.status,\n );\n }\n}\n\nfunction validHealth(value: unknown): value is RuntimeGatewayHealth {\n const body = record(value);\n return Boolean(\n body?.ok === true &&\n body.v === RUNTIME_GATEWAY_VERSION &&\n Array.isArray(body.capabilities) &&\n typeof body.cursor === \"number\",\n );\n}\n\nfunction validTurnAck(value: unknown): value is RuntimeGatewayTurnAcknowledgement {\n const body = record(value);\n return Boolean(\n body?.ok === true &&\n body.v === RUNTIME_GATEWAY_VERSION &&\n body.accepted === true &&\n typeof body.deduplicated === \"boolean\" &&\n typeof body.requestId === \"string\" &&\n typeof body.clientMessageId === \"string\" &&\n typeof body.topicId === \"string\" &&\n typeof body.messageId === \"string\" &&\n typeof body.cursor === \"number\",\n );\n}\n\nfunction validManagerTopic(value: unknown): value is RuntimeGatewayManagerTopic {\n const topic = record(value);\n return Boolean(\n typeof topic?.id === \"string\" &&\n typeof topic.title === \"string\" &&\n topic.kind === \"manager\" &&\n Array.isArray(topic.participants),\n );\n}\n\nfunction validCronJob(value: unknown): value is RuntimeGatewayCronJob {\n const job = record(value);\n return Boolean(\n typeof job?.id === \"string\" &&\n typeof job.name === \"string\" &&\n typeof job.executionPrincipalUserId === \"string\" &&\n typeof job.actorOwnerUserId === \"string\" &&\n typeof job.topicId === \"string\" &&\n typeof job.schedule === \"string\" &&\n typeof job.enabled === \"boolean\" &&\n typeof job.nextRunAt === \"string\" &&\n typeof job.canMutate === \"boolean\",\n );\n}\n\nexport async function* parseRuntimeGatewaySse(\n body: ReadableStream<Uint8Array>,\n): AsyncGenerator<RuntimeGatewaySseEvent> {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n let event = \"message\";\n let id: number | undefined;\n let data: string[] = [];\n const flush = (): RuntimeGatewaySseEvent | null => {\n if (data.length === 0) return null;\n const raw = data.join(\"\\n\");\n data = [];\n try {\n return { event, id, data: JSON.parse(raw) };\n } catch {\n throw new RuntimeGatewayError(\"Runtime Gateway SSE event has invalid JSON\", \"protocol\");\n } finally {\n event = \"message\";\n id = undefined;\n }\n };\n try {\n while (true) {\n const chunk = await reader.read();\n if (chunk.done) break;\n buffer += decoder.decode(chunk.value, { stream: true }).replace(/\\r\\n/g, \"\\n\");\n let newline = buffer.indexOf(\"\\n\");\n while (newline >= 0) {\n const line = buffer.slice(0, newline);\n buffer = buffer.slice(newline + 1);\n if (line === \"\") {\n const parsed = flush();\n if (parsed) yield parsed;\n } else if (line.startsWith(\"event:\")) {\n event = line.slice(6).trim() || \"message\";\n } else if (line.startsWith(\"id:\")) {\n const parsed = Number.parseInt(line.slice(3).trim(), 10);\n if (Number.isFinite(parsed)) id = parsed;\n } else if (line.startsWith(\"data:\")) {\n data.push(line.slice(5).trimStart());\n }\n newline = buffer.indexOf(\"\\n\");\n }\n }\n buffer += decoder.decode();\n if (buffer.startsWith(\"data:\")) data.push(buffer.slice(5).trimStart());\n const parsed = flush();\n if (parsed) yield parsed;\n } finally {\n reader.releaseLock();\n }\n}\n\nexport class RuntimeGatewayClient {\n private readonly pathPrefix: string;\n private readonly request: RuntimeGatewayFetch;\n private readonly requestTimeoutMs: number;\n private readonly compactTimeoutMs: number;\n\n constructor(private readonly options: RuntimeGatewayClientOptions) {\n this.pathPrefix = options.pathPrefix ?? RUNTIME_GATEWAY_CONTROL_PATH;\n this.request = options.fetch ?? fetch;\n this.requestTimeoutMs = options.requestTimeoutMs ?? 5_000;\n this.compactTimeoutMs = options.compactTimeoutMs ?? 5 * 60_000;\n }\n\n private endpoint(path: string): string {\n if (!this.options.baseUrl || !this.options.token) {\n throw new RuntimeGatewayError(\"Runtime Gateway is not configured\", \"config\");\n }\n return `${this.options.baseUrl.replace(/\\/+$/, \"\")}${this.pathPrefix}${path}`;\n }\n\n private async authorization(): Promise<string> {\n try {\n const token =\n typeof this.options.token === \"function\" ? await this.options.token() : this.options.token;\n return `Bearer ${token}`;\n } catch (error) {\n throw new RuntimeGatewayError(\n error instanceof Error ? error.message : \"Runtime Gateway token resolution failed\",\n \"config\",\n );\n }\n }\n\n private async send(path: string, init: RequestInit, timeoutMs?: number): Promise<Response> {\n const authorization = await this.authorization();\n try {\n return await this.request(this.endpoint(path), {\n ...init,\n headers: { authorization, ...init.headers },\n signal: timeoutMs === undefined ? init.signal : AbortSignal.timeout(timeoutMs),\n });\n } catch (error) {\n if (error instanceof DOMException && error.name === \"TimeoutError\") {\n throw new RuntimeGatewayError(\"Runtime Gateway request timed out\", \"timeout\");\n }\n throw new RuntimeGatewayError(\"Runtime Gateway request failed\", \"transport\");\n }\n }\n\n async health(): Promise<RuntimeGatewayHealth> {\n const response = await this.send(\"/health\", { method: \"GET\" }, this.requestTimeoutMs);\n if (!response.ok) {\n throw new RuntimeGatewayError(\n \"Runtime Gateway health request failed\",\n \"http\",\n response.status,\n );\n }\n const body = await json(response);\n if (!validHealth(body)) {\n throw new RuntimeGatewayError(\"Runtime Gateway health response is incompatible\", \"protocol\");\n }\n return body;\n }\n\n async submitTurn(input: RuntimeGatewayTurnInput): Promise<RuntimeGatewayTurnAcknowledgement> {\n const response = await this.send(\n \"/turns\",\n {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ v: RUNTIME_GATEWAY_VERSION, ...input }),\n },\n this.requestTimeoutMs,\n );\n if (response.status !== 202) {\n throw new RuntimeGatewayError(\n \"Runtime Gateway turn was not accepted\",\n \"http\",\n response.status,\n );\n }\n const body = await json(response);\n if (!validTurnAck(body)) {\n throw new RuntimeGatewayError(\n \"Runtime Gateway turn acknowledgement is incompatible\",\n \"protocol\",\n );\n }\n return body;\n }\n\n async ensureManagerTopic(userId: string): Promise<RuntimeGatewayManagerTopic> {\n const response = await this.send(\n \"/manager-topic\",\n {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ v: RUNTIME_GATEWAY_VERSION, userId }),\n },\n this.requestTimeoutMs,\n );\n if (!response.ok) {\n throw new RuntimeGatewayError(\n \"Runtime Gateway manager topic request failed\",\n \"http\",\n response.status,\n );\n }\n const body = record(await json(response));\n if (body?.ok !== true || body.v !== RUNTIME_GATEWAY_VERSION || !validManagerTopic(body.topic)) {\n throw new RuntimeGatewayError(\n \"Runtime Gateway manager topic response is incompatible\",\n \"protocol\",\n );\n }\n return body.topic;\n }\n\n private async cronRequest(path: string, init: RequestInit): Promise<Record<string, unknown>> {\n const response = await this.send(path, init, this.requestTimeoutMs);\n if (!response.ok) {\n throw new RuntimeGatewayError(\"Runtime Gateway cron request failed\", \"http\", response.status);\n }\n const body = record(await json(response));\n if (body?.ok !== true || body.v !== RUNTIME_GATEWAY_VERSION) {\n throw new RuntimeGatewayError(\"Runtime Gateway cron response is incompatible\", \"protocol\");\n }\n return body;\n }\n\n async listCronScripts(): Promise<string[]> {\n const body = await this.cronRequest(\"/cron/scripts\", { method: \"GET\" });\n if (!Array.isArray(body.scripts) || !body.scripts.every((value) => typeof value === \"string\")) {\n throw new RuntimeGatewayError(\"Runtime Gateway cron scripts are incompatible\", \"protocol\");\n }\n return body.scripts;\n }\n\n async listCronJobs(\n userId: string,\n actorUserId: string,\n actorIsAdmin = false,\n ): Promise<RuntimeGatewayCronJob[]> {\n const search = new URLSearchParams({\n user: userId,\n actorUserId,\n actorIsAdmin: actorIsAdmin ? \"1\" : \"0\",\n });\n const body = await this.cronRequest(`/cron/jobs?${search}`, { method: \"GET\" });\n if (!Array.isArray(body.jobs) || !body.jobs.every(validCronJob)) {\n throw new RuntimeGatewayError(\"Runtime Gateway cron jobs are incompatible\", \"protocol\");\n }\n return body.jobs;\n }\n\n async createCronJob(input: RuntimeGatewayCronCreateInput): Promise<RuntimeGatewayCronJob> {\n const body = await this.cronRequest(\"/cron/jobs\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ v: RUNTIME_GATEWAY_VERSION, ...input }),\n });\n if (!validCronJob(body.job)) {\n throw new RuntimeGatewayError(\"Runtime Gateway cron job is incompatible\", \"protocol\");\n }\n return body.job;\n }\n\n async updateCronJob(\n jobId: string,\n userId: string,\n actorUserId: string,\n patch: RuntimeGatewayCronPatch,\n actorIsAdmin = false,\n ): Promise<RuntimeGatewayCronJob> {\n const body = await this.cronRequest(`/cron/jobs/${encodeURIComponent(jobId)}`, {\n method: \"PATCH\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({\n v: RUNTIME_GATEWAY_VERSION,\n userId,\n actorUserId,\n actorIsAdmin,\n patch,\n }),\n });\n if (!validCronJob(body.job)) {\n throw new RuntimeGatewayError(\"Runtime Gateway cron job is incompatible\", \"protocol\");\n }\n return body.job;\n }\n\n async deleteCronJob(\n jobId: string,\n userId: string,\n actorUserId: string,\n actorIsAdmin = false,\n ): Promise<string> {\n const search = new URLSearchParams({\n user: userId,\n actorUserId,\n actorIsAdmin: actorIsAdmin ? \"1\" : \"0\",\n });\n const body = await this.cronRequest(`/cron/jobs/${encodeURIComponent(jobId)}?${search}`, {\n method: \"DELETE\",\n });\n if (typeof body.deleted !== \"string\") {\n throw new RuntimeGatewayError(\"Runtime Gateway cron delete is incompatible\", \"protocol\");\n }\n return body.deleted;\n }\n\n async *events(\n after: number,\n topicId?: string,\n signal?: AbortSignal,\n ): AsyncGenerator<RuntimeGatewaySseEvent> {\n const search = new URLSearchParams({ after: String(Math.max(0, after)) });\n if (topicId) search.set(\"topicId\", topicId);\n const response = await this.send(`/events?${search}`, { method: \"GET\", signal });\n if (!response.ok || !response.body) {\n throw new RuntimeGatewayError(\"Runtime Gateway event stream failed\", \"http\", response.status);\n }\n yield* parseRuntimeGatewaySse(response.body);\n }\n\n async getTopicUsage(topicId: string, userId: string): Promise<RuntimeGatewayTopicUsage> {\n const response = await this.send(\n `/topics/${encodeURIComponent(topicId)}/usage?user=${encodeURIComponent(userId)}`,\n { method: \"GET\" },\n this.requestTimeoutMs,\n );\n if (!response.ok) {\n throw new RuntimeGatewayError(\n \"Runtime Gateway topic usage request failed\",\n \"http\",\n response.status,\n );\n }\n const usage = record(record(await json(response))?.usage);\n const read = (key: keyof RuntimeGatewayTopicUsage): number => {\n const value = usage?.[key];\n return typeof value === \"number\" && Number.isFinite(value) ? value : 0;\n };\n return {\n queries: read(\"queries\"),\n inputTokens: read(\"inputTokens\"),\n outputTokens: read(\"outputTokens\"),\n cacheCreationInputTokens: read(\"cacheCreationInputTokens\"),\n cacheReadInputTokens: read(\"cacheReadInputTokens\"),\n estimatedCostUsd: read(\"estimatedCostUsd\"),\n };\n }\n\n async abortTurn(topicId: string, userId: string): Promise<boolean> {\n const response = await this.send(\n `/topics/${encodeURIComponent(topicId)}/abort`,\n {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ v: RUNTIME_GATEWAY_VERSION, userId }),\n },\n this.requestTimeoutMs,\n );\n if (!response.ok) {\n throw new RuntimeGatewayError(\"Runtime Gateway turn abort failed\", \"http\", response.status);\n }\n const body = record(await json(response));\n if (\n body?.ok !== true ||\n body.v !== RUNTIME_GATEWAY_VERSION ||\n typeof body.aborted !== \"boolean\"\n ) {\n throw new RuntimeGatewayError(\n \"Runtime Gateway turn abort response is incompatible\",\n \"protocol\",\n );\n }\n return body.aborted;\n }\n\n async resetSession(\n topicId: string,\n userId: string,\n reason?: string,\n ): Promise<string | undefined> {\n return this.sessionCommand(topicId, userId, \"reset\", reason);\n }\n\n async compactSession(\n topicId: string,\n userId: string,\n reason?: string,\n ): Promise<string | undefined> {\n return this.sessionCommand(topicId, userId, \"compact\", reason);\n }\n\n private async sessionCommand(\n topicId: string,\n userId: string,\n command: \"reset\" | \"compact\",\n reason?: string,\n ): Promise<string | undefined> {\n const response = await this.send(\n `/topics/${encodeURIComponent(topicId)}/session/${command}`,\n {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({\n v: RUNTIME_GATEWAY_VERSION,\n userId,\n ...(reason ? { reason } : {}),\n }),\n },\n command === \"compact\" ? this.compactTimeoutMs : this.requestTimeoutMs,\n );\n if (!response.ok) {\n throw new RuntimeGatewayError(\n `Runtime Gateway session ${command} failed`,\n \"http\",\n response.status,\n );\n }\n const body = record(await json(response));\n if (body?.ok !== true || body.v !== RUNTIME_GATEWAY_VERSION) {\n throw new RuntimeGatewayError(\n `Runtime Gateway session ${command} response is incompatible`,\n \"protocol\",\n );\n }\n return typeof body.result === \"string\" ? body.result : undefined;\n }\n}\n"
5
+ "export const RUNTIME_GATEWAY_VERSION = 1 as const;\nexport const RUNTIME_GATEWAY_CONTROL_PATH = \"/api/v1/control/runtime/v1\";\n\nexport type RuntimeGatewayErrorKind = \"config\" | \"timeout\" | \"transport\" | \"protocol\" | \"http\";\n\nexport class RuntimeGatewayError extends Error {\n constructor(\n message: string,\n public readonly kind: RuntimeGatewayErrorKind,\n public readonly status?: number,\n ) {\n super(message);\n }\n}\n\nexport interface RuntimeGatewayHealth {\n ok: true;\n v: typeof RUNTIME_GATEWAY_VERSION;\n nodeId?: string;\n aiName?: string;\n capabilities: string[];\n cursor: number;\n}\n\nexport interface RuntimeGatewayTurnInput {\n topicId: string;\n /** Canonical principal on the execution node. */\n userId: string;\n /** Product-side actor, when it differs from the execution principal. */\n actorUserId?: string;\n actorLabel?: string;\n vaultUserId?: string;\n text: string;\n clientMessageId: string;\n requestId?: string;\n allowAutoContinue?: boolean;\n threadRootId?: string;\n respond?: boolean;\n /** Run without adding the injected prompt or output to the visible transcript. */\n silent?: boolean;\n attachments?: string[];\n visualTools?: boolean;\n fileDeliveryTools?: boolean;\n}\n\nexport interface RuntimeGatewayTurnAcknowledgement {\n ok: true;\n v: typeof RUNTIME_GATEWAY_VERSION;\n accepted: true;\n deduplicated: boolean;\n requestId: string;\n clientMessageId: string;\n topicId: string;\n messageId: string;\n cursor: number;\n}\n\nexport interface RuntimeGatewayTopicDeriveInput {\n userId: string;\n copyHistory: boolean;\n name?: string;\n}\n\nexport interface RuntimeGatewayDerivedTopic {\n id: string;\n title: string;\n kind?: string;\n agent?: string;\n defaultModel?: string;\n defaultEffort?: string;\n parentTopicId?: string;\n isFork?: boolean;\n}\n\nexport interface RuntimeGatewaySseEvent {\n id?: number;\n event: string;\n data: unknown;\n}\n\nexport interface RuntimeGatewayTopicUsage {\n queries: number;\n inputTokens: number;\n outputTokens: number;\n cacheCreationInputTokens: number;\n cacheReadInputTokens: number;\n estimatedCostUsd: number;\n}\n\nexport interface RuntimeGatewayManagerTopic {\n id: string;\n title: string;\n kind: \"manager\";\n agent?: \"claude\" | \"codex\" | \"maestro\";\n participants: Array<{ userId: string; role: \"owner\" | \"member\" }>;\n}\n\nexport interface RuntimeGatewayCronJob {\n id: string;\n name: string;\n executionPrincipalUserId: string;\n actorOwnerUserId: string;\n topicId: string;\n source: \"prompt\" | \"script\";\n script: string | null;\n scriptExists: boolean;\n prompt: string | null;\n promptPreview: string | null;\n summary: string | null;\n schedule: string;\n timezone: string | null;\n enabled: boolean;\n agent: \"claude\" | \"codex\" | \"maestro\" | null;\n model: string | null;\n effort: string | null;\n nextRunAt: string;\n runCount: number;\n lastRun: Record<string, unknown> | null;\n createdAt: string;\n updatedAt: string;\n canMutate: boolean;\n}\n\nexport interface RuntimeGatewayCronCreateInput {\n userId: string;\n actorUserId: string;\n topicId: string;\n name: string;\n script: string;\n schedule: string;\n timezone?: string;\n agent?: \"claude\" | \"codex\" | \"maestro\";\n model?: string;\n effort?: string;\n}\n\nexport interface RuntimeGatewayCronPatch {\n name?: string;\n topicId?: string;\n script?: string;\n schedule?: string;\n timezone?: string | null;\n enabled?: boolean;\n agent?: \"claude\" | \"codex\" | \"maestro\" | null;\n model?: string | null;\n effort?: string | null;\n}\n\nexport type RuntimeGatewayToken = string | (() => string | Promise<string>);\nexport type RuntimeGatewayFetch = (\n input: string | URL | Request,\n init?: RequestInit,\n) => Promise<Response>;\n\nexport interface RuntimeGatewayClientOptions {\n baseUrl: string;\n token: RuntimeGatewayToken;\n /** Loopback control path or an authenticated relay forward prefix. */\n pathPrefix?: string;\n fetch?: RuntimeGatewayFetch;\n requestTimeoutMs?: number;\n compactTimeoutMs?: number;\n}\n\nfunction record(value: unknown): Record<string, unknown> | null {\n return value && typeof value === \"object\" && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : null;\n}\n\nasync function json(response: Response): Promise<unknown> {\n try {\n return await response.json();\n } catch {\n throw new RuntimeGatewayError(\n \"Runtime Gateway returned invalid JSON\",\n \"protocol\",\n response.status,\n );\n }\n}\n\nfunction validHealth(value: unknown): value is RuntimeGatewayHealth {\n const body = record(value);\n return Boolean(\n body?.ok === true &&\n body.v === RUNTIME_GATEWAY_VERSION &&\n Array.isArray(body.capabilities) &&\n typeof body.cursor === \"number\",\n );\n}\n\nfunction validTurnAck(value: unknown): value is RuntimeGatewayTurnAcknowledgement {\n const body = record(value);\n return Boolean(\n body?.ok === true &&\n body.v === RUNTIME_GATEWAY_VERSION &&\n body.accepted === true &&\n typeof body.deduplicated === \"boolean\" &&\n typeof body.requestId === \"string\" &&\n typeof body.clientMessageId === \"string\" &&\n typeof body.topicId === \"string\" &&\n typeof body.messageId === \"string\" &&\n typeof body.cursor === \"number\",\n );\n}\n\nfunction validManagerTopic(value: unknown): value is RuntimeGatewayManagerTopic {\n const topic = record(value);\n return Boolean(\n typeof topic?.id === \"string\" &&\n typeof topic.title === \"string\" &&\n topic.kind === \"manager\" &&\n Array.isArray(topic.participants),\n );\n}\n\nfunction validCronJob(value: unknown): value is RuntimeGatewayCronJob {\n const job = record(value);\n return Boolean(\n typeof job?.id === \"string\" &&\n typeof job.name === \"string\" &&\n typeof job.executionPrincipalUserId === \"string\" &&\n typeof job.actorOwnerUserId === \"string\" &&\n typeof job.topicId === \"string\" &&\n typeof job.schedule === \"string\" &&\n typeof job.enabled === \"boolean\" &&\n typeof job.nextRunAt === \"string\" &&\n typeof job.canMutate === \"boolean\",\n );\n}\n\nexport async function* parseRuntimeGatewaySse(\n body: ReadableStream<Uint8Array>,\n): AsyncGenerator<RuntimeGatewaySseEvent> {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n let event = \"message\";\n let id: number | undefined;\n let data: string[] = [];\n const flush = (): RuntimeGatewaySseEvent | null => {\n if (data.length === 0) return null;\n const raw = data.join(\"\\n\");\n data = [];\n try {\n return { event, id, data: JSON.parse(raw) };\n } catch {\n throw new RuntimeGatewayError(\"Runtime Gateway SSE event has invalid JSON\", \"protocol\");\n } finally {\n event = \"message\";\n id = undefined;\n }\n };\n try {\n while (true) {\n const chunk = await reader.read();\n if (chunk.done) break;\n buffer += decoder.decode(chunk.value, { stream: true }).replace(/\\r\\n/g, \"\\n\");\n let newline = buffer.indexOf(\"\\n\");\n while (newline >= 0) {\n const line = buffer.slice(0, newline);\n buffer = buffer.slice(newline + 1);\n if (line === \"\") {\n const parsed = flush();\n if (parsed) yield parsed;\n } else if (line.startsWith(\"event:\")) {\n event = line.slice(6).trim() || \"message\";\n } else if (line.startsWith(\"id:\")) {\n const parsed = Number.parseInt(line.slice(3).trim(), 10);\n if (Number.isFinite(parsed)) id = parsed;\n } else if (line.startsWith(\"data:\")) {\n data.push(line.slice(5).trimStart());\n }\n newline = buffer.indexOf(\"\\n\");\n }\n }\n buffer += decoder.decode();\n if (buffer.startsWith(\"data:\")) data.push(buffer.slice(5).trimStart());\n const parsed = flush();\n if (parsed) yield parsed;\n } finally {\n reader.releaseLock();\n }\n}\n\nexport class RuntimeGatewayClient {\n private readonly pathPrefix: string;\n private readonly request: RuntimeGatewayFetch;\n private readonly requestTimeoutMs: number;\n private readonly compactTimeoutMs: number;\n\n constructor(private readonly options: RuntimeGatewayClientOptions) {\n this.pathPrefix = options.pathPrefix ?? RUNTIME_GATEWAY_CONTROL_PATH;\n this.request = options.fetch ?? fetch;\n this.requestTimeoutMs = options.requestTimeoutMs ?? 5_000;\n this.compactTimeoutMs = options.compactTimeoutMs ?? 5 * 60_000;\n }\n\n private endpoint(path: string): string {\n if (!this.options.baseUrl || !this.options.token) {\n throw new RuntimeGatewayError(\"Runtime Gateway is not configured\", \"config\");\n }\n return `${this.options.baseUrl.replace(/\\/+$/, \"\")}${this.pathPrefix}${path}`;\n }\n\n private async authorization(): Promise<string> {\n try {\n const token =\n typeof this.options.token === \"function\" ? await this.options.token() : this.options.token;\n return `Bearer ${token}`;\n } catch (error) {\n throw new RuntimeGatewayError(\n error instanceof Error ? error.message : \"Runtime Gateway token resolution failed\",\n \"config\",\n );\n }\n }\n\n private async send(path: string, init: RequestInit, timeoutMs?: number): Promise<Response> {\n const authorization = await this.authorization();\n try {\n return await this.request(this.endpoint(path), {\n ...init,\n headers: { authorization, ...init.headers },\n signal: timeoutMs === undefined ? init.signal : AbortSignal.timeout(timeoutMs),\n });\n } catch (error) {\n if (error instanceof DOMException && error.name === \"TimeoutError\") {\n throw new RuntimeGatewayError(\"Runtime Gateway request timed out\", \"timeout\");\n }\n throw new RuntimeGatewayError(\"Runtime Gateway request failed\", \"transport\");\n }\n }\n\n async health(): Promise<RuntimeGatewayHealth> {\n const response = await this.send(\"/health\", { method: \"GET\" }, this.requestTimeoutMs);\n if (!response.ok) {\n throw new RuntimeGatewayError(\n \"Runtime Gateway health request failed\",\n \"http\",\n response.status,\n );\n }\n const body = await json(response);\n if (!validHealth(body)) {\n throw new RuntimeGatewayError(\"Runtime Gateway health response is incompatible\", \"protocol\");\n }\n return body;\n }\n\n async submitTurn(input: RuntimeGatewayTurnInput): Promise<RuntimeGatewayTurnAcknowledgement> {\n const response = await this.send(\n \"/turns\",\n {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ v: RUNTIME_GATEWAY_VERSION, ...input }),\n },\n this.requestTimeoutMs,\n );\n if (response.status !== 202) {\n throw new RuntimeGatewayError(\n \"Runtime Gateway turn was not accepted\",\n \"http\",\n response.status,\n );\n }\n const body = await json(response);\n if (!validTurnAck(body)) {\n throw new RuntimeGatewayError(\n \"Runtime Gateway turn acknowledgement is incompatible\",\n \"protocol\",\n );\n }\n return body;\n }\n\n async deriveTopic(\n topicId: string,\n input: RuntimeGatewayTopicDeriveInput,\n ): Promise<RuntimeGatewayDerivedTopic> {\n const response = await this.send(\n `/topics/${encodeURIComponent(topicId)}/derive`,\n {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ v: RUNTIME_GATEWAY_VERSION, ...input }),\n },\n this.requestTimeoutMs,\n );\n if (response.status !== 201) {\n throw new RuntimeGatewayError(\"Runtime Gateway topic derive failed\", \"http\", response.status);\n }\n const body = await json(response);\n const topic = record(body)?.topic;\n const topicRecord = record(topic);\n if (\n !topicRecord ||\n typeof topicRecord.id !== \"string\" ||\n typeof topicRecord.title !== \"string\"\n ) {\n throw new RuntimeGatewayError(\n \"Runtime Gateway topic derive response is incompatible\",\n \"protocol\",\n );\n }\n return topic as unknown as RuntimeGatewayDerivedTopic;\n }\n\n async ensureManagerTopic(userId: string): Promise<RuntimeGatewayManagerTopic> {\n const response = await this.send(\n \"/manager-topic\",\n {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ v: RUNTIME_GATEWAY_VERSION, userId }),\n },\n this.requestTimeoutMs,\n );\n if (!response.ok) {\n throw new RuntimeGatewayError(\n \"Runtime Gateway manager topic request failed\",\n \"http\",\n response.status,\n );\n }\n const body = record(await json(response));\n if (body?.ok !== true || body.v !== RUNTIME_GATEWAY_VERSION || !validManagerTopic(body.topic)) {\n throw new RuntimeGatewayError(\n \"Runtime Gateway manager topic response is incompatible\",\n \"protocol\",\n );\n }\n return body.topic;\n }\n\n private async cronRequest(path: string, init: RequestInit): Promise<Record<string, unknown>> {\n const response = await this.send(path, init, this.requestTimeoutMs);\n if (!response.ok) {\n throw new RuntimeGatewayError(\"Runtime Gateway cron request failed\", \"http\", response.status);\n }\n const body = record(await json(response));\n if (body?.ok !== true || body.v !== RUNTIME_GATEWAY_VERSION) {\n throw new RuntimeGatewayError(\"Runtime Gateway cron response is incompatible\", \"protocol\");\n }\n return body;\n }\n\n async listCronScripts(): Promise<string[]> {\n const body = await this.cronRequest(\"/cron/scripts\", { method: \"GET\" });\n if (!Array.isArray(body.scripts) || !body.scripts.every((value) => typeof value === \"string\")) {\n throw new RuntimeGatewayError(\"Runtime Gateway cron scripts are incompatible\", \"protocol\");\n }\n return body.scripts;\n }\n\n async listCronJobs(\n userId: string,\n actorUserId: string,\n actorIsAdmin = false,\n ): Promise<RuntimeGatewayCronJob[]> {\n const search = new URLSearchParams({\n user: userId,\n actorUserId,\n actorIsAdmin: actorIsAdmin ? \"1\" : \"0\",\n });\n const body = await this.cronRequest(`/cron/jobs?${search}`, { method: \"GET\" });\n if (!Array.isArray(body.jobs) || !body.jobs.every(validCronJob)) {\n throw new RuntimeGatewayError(\"Runtime Gateway cron jobs are incompatible\", \"protocol\");\n }\n return body.jobs;\n }\n\n async createCronJob(input: RuntimeGatewayCronCreateInput): Promise<RuntimeGatewayCronJob> {\n const body = await this.cronRequest(\"/cron/jobs\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ v: RUNTIME_GATEWAY_VERSION, ...input }),\n });\n if (!validCronJob(body.job)) {\n throw new RuntimeGatewayError(\"Runtime Gateway cron job is incompatible\", \"protocol\");\n }\n return body.job;\n }\n\n async updateCronJob(\n jobId: string,\n userId: string,\n actorUserId: string,\n patch: RuntimeGatewayCronPatch,\n actorIsAdmin = false,\n ): Promise<RuntimeGatewayCronJob> {\n const body = await this.cronRequest(`/cron/jobs/${encodeURIComponent(jobId)}`, {\n method: \"PATCH\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({\n v: RUNTIME_GATEWAY_VERSION,\n userId,\n actorUserId,\n actorIsAdmin,\n patch,\n }),\n });\n if (!validCronJob(body.job)) {\n throw new RuntimeGatewayError(\"Runtime Gateway cron job is incompatible\", \"protocol\");\n }\n return body.job;\n }\n\n async deleteCronJob(\n jobId: string,\n userId: string,\n actorUserId: string,\n actorIsAdmin = false,\n ): Promise<string> {\n const search = new URLSearchParams({\n user: userId,\n actorUserId,\n actorIsAdmin: actorIsAdmin ? \"1\" : \"0\",\n });\n const body = await this.cronRequest(`/cron/jobs/${encodeURIComponent(jobId)}?${search}`, {\n method: \"DELETE\",\n });\n if (typeof body.deleted !== \"string\") {\n throw new RuntimeGatewayError(\"Runtime Gateway cron delete is incompatible\", \"protocol\");\n }\n return body.deleted;\n }\n\n async *events(\n after: number,\n topicId?: string,\n signal?: AbortSignal,\n ): AsyncGenerator<RuntimeGatewaySseEvent> {\n const search = new URLSearchParams({ after: String(Math.max(0, after)) });\n if (topicId) search.set(\"topicId\", topicId);\n const response = await this.send(`/events?${search}`, { method: \"GET\", signal });\n if (!response.ok || !response.body) {\n throw new RuntimeGatewayError(\"Runtime Gateway event stream failed\", \"http\", response.status);\n }\n yield* parseRuntimeGatewaySse(response.body);\n }\n\n async getTopicUsage(topicId: string, userId: string): Promise<RuntimeGatewayTopicUsage> {\n const response = await this.send(\n `/topics/${encodeURIComponent(topicId)}/usage?user=${encodeURIComponent(userId)}`,\n { method: \"GET\" },\n this.requestTimeoutMs,\n );\n if (!response.ok) {\n throw new RuntimeGatewayError(\n \"Runtime Gateway topic usage request failed\",\n \"http\",\n response.status,\n );\n }\n const usage = record(record(await json(response))?.usage);\n const read = (key: keyof RuntimeGatewayTopicUsage): number => {\n const value = usage?.[key];\n return typeof value === \"number\" && Number.isFinite(value) ? value : 0;\n };\n return {\n queries: read(\"queries\"),\n inputTokens: read(\"inputTokens\"),\n outputTokens: read(\"outputTokens\"),\n cacheCreationInputTokens: read(\"cacheCreationInputTokens\"),\n cacheReadInputTokens: read(\"cacheReadInputTokens\"),\n estimatedCostUsd: read(\"estimatedCostUsd\"),\n };\n }\n\n async abortTurn(topicId: string, userId: string): Promise<boolean> {\n const response = await this.send(\n `/topics/${encodeURIComponent(topicId)}/abort`,\n {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ v: RUNTIME_GATEWAY_VERSION, userId }),\n },\n this.requestTimeoutMs,\n );\n if (!response.ok) {\n throw new RuntimeGatewayError(\"Runtime Gateway turn abort failed\", \"http\", response.status);\n }\n const body = record(await json(response));\n if (\n body?.ok !== true ||\n body.v !== RUNTIME_GATEWAY_VERSION ||\n typeof body.aborted !== \"boolean\"\n ) {\n throw new RuntimeGatewayError(\n \"Runtime Gateway turn abort response is incompatible\",\n \"protocol\",\n );\n }\n return body.aborted;\n }\n\n async resetSession(\n topicId: string,\n userId: string,\n reason?: string,\n ): Promise<string | undefined> {\n return this.sessionCommand(topicId, userId, \"reset\", reason);\n }\n\n async compactSession(\n topicId: string,\n userId: string,\n reason?: string,\n ): Promise<string | undefined> {\n return this.sessionCommand(topicId, userId, \"compact\", reason);\n }\n\n private async sessionCommand(\n topicId: string,\n userId: string,\n command: \"reset\" | \"compact\",\n reason?: string,\n ): Promise<string | undefined> {\n const response = await this.send(\n `/topics/${encodeURIComponent(topicId)}/session/${command}`,\n {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({\n v: RUNTIME_GATEWAY_VERSION,\n userId,\n ...(reason ? { reason } : {}),\n }),\n },\n command === \"compact\" ? this.compactTimeoutMs : this.requestTimeoutMs,\n );\n if (!response.ok) {\n throw new RuntimeGatewayError(\n `Runtime Gateway session ${command} failed`,\n \"http\",\n response.status,\n );\n }\n const body = record(await json(response));\n if (body?.ok !== true || body.v !== RUNTIME_GATEWAY_VERSION) {\n throw new RuntimeGatewayError(\n `Runtime Gateway session ${command} response is incompatible`,\n \"protocol\",\n );\n }\n return typeof body.result === \"string\" ? body.result : undefined;\n }\n}\n"
6
6
  ],
7
- "mappings": ";;AAAO,IAAM,0BAA0B;AAChC,IAAM,+BAA+B;AAAA;AAIrC,MAAM,4BAA4B,MAAM;AAAA,EAG3B;AAAA,EACA;AAAA,EAHlB,WAAW,CACT,SACgB,MACA,QAChB;AAAA,IACA,MAAM,OAAO;AAAA,IAHG;AAAA,IACA;AAAA;AAIpB;AAoIA,SAAS,MAAM,CAAC,OAAgD;AAAA,EAC9D,OAAO,SAAS,OAAO,UAAU,aAAa,MAAM,QAAQ,KAAK,IAC5D,QACD;AAAA;AAGN,eAAe,IAAI,CAAC,UAAsC;AAAA,EACxD,IAAI;AAAA,IACF,OAAO,MAAM,SAAS,KAAK;AAAA,IAC3B,MAAM;AAAA,IACN,MAAM,IAAI,oBACR,yCACA,YACA,SAAS,MACX;AAAA;AAAA;AAIJ,SAAS,WAAW,CAAC,OAA+C;AAAA,EAClE,MAAM,OAAO,OAAO,KAAK;AAAA,EACzB,OAAO,QACL,MAAM,OAAO,QACX,KAAK,MAAM,2BACX,MAAM,QAAQ,KAAK,YAAY,KAC/B,OAAO,KAAK,WAAW,QAC3B;AAAA;AAGF,SAAS,YAAY,CAAC,OAA4D;AAAA,EAChF,MAAM,OAAO,OAAO,KAAK;AAAA,EACzB,OAAO,QACL,MAAM,OAAO,QACX,KAAK,MAAM,2BACX,KAAK,aAAa,QAClB,OAAO,KAAK,iBAAiB,aAC7B,OAAO,KAAK,cAAc,YAC1B,OAAO,KAAK,oBAAoB,YAChC,OAAO,KAAK,YAAY,YACxB,OAAO,KAAK,cAAc,YAC1B,OAAO,KAAK,WAAW,QAC3B;AAAA;AAGF,SAAS,iBAAiB,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AAQ;AAAA,MACR,SAAS,EAAE,gBAAgB,mBAAmB;AAAA,MAC9C,MAAM,KAAK,UAAU;AAAA,QACnB,GAAG;AAAA,QACH;AAAA,WACI,SAAS,EAAE,OAAO,IAAI,CAAC;AAAA,MAC7B,CAAC;AAAA,IACH,GACA,YAAY,YAAY,KAAK,mBAAmB,KAAK,gBACvD;AAAA,IACA,KAAK,SAAS,IAAI;AAAA,MAChB,MAAM,IAAI,oBACR,2BAA2B,kBAC3B,QACA,SAAS,MACX;AAAA,IACF;AAAA,IACA,MAAM,OAAO,OAAO,MAAM,KAAK,QAAQ,CAAC;AAAA,IACxC,IAAI,MAAM,OAAO,QAAQ,KAAK,MAAM,yBAAyB;AAAA,MAC3D,MAAM,IAAI,oBACR,2BAA2B,oCAC3B,UACF;AAAA,IACF;AAAA,IACA,OAAO,OAAO,KAAK,WAAW,WAAW,KAAK,SAAS;AAAA;AAE3D;",
8
+ "debugId": "A4DC2005942CF37964756E2164756E21",
9
9
  "names": []
10
10
  }
@@ -28,6 +28,8 @@ export interface RuntimeGatewayTurnInput {
28
28
  allowAutoContinue?: boolean;
29
29
  threadRootId?: string;
30
30
  respond?: boolean;
31
+ /** Run without adding the injected prompt or output to the visible transcript. */
32
+ silent?: boolean;
31
33
  attachments?: string[];
32
34
  visualTools?: boolean;
33
35
  fileDeliveryTools?: boolean;
@@ -43,6 +45,21 @@ export interface RuntimeGatewayTurnAcknowledgement {
43
45
  messageId: string;
44
46
  cursor: number;
45
47
  }
48
+ export interface RuntimeGatewayTopicDeriveInput {
49
+ userId: string;
50
+ copyHistory: boolean;
51
+ name?: string;
52
+ }
53
+ export interface RuntimeGatewayDerivedTopic {
54
+ id: string;
55
+ title: string;
56
+ kind?: string;
57
+ agent?: string;
58
+ defaultModel?: string;
59
+ defaultEffort?: string;
60
+ parentTopicId?: string;
61
+ isFork?: boolean;
62
+ }
46
63
  export interface RuntimeGatewaySseEvent {
47
64
  id?: number;
48
65
  event: string;
@@ -138,6 +155,7 @@ export declare class RuntimeGatewayClient {
138
155
  private send;
139
156
  health(): Promise<RuntimeGatewayHealth>;
140
157
  submitTurn(input: RuntimeGatewayTurnInput): Promise<RuntimeGatewayTurnAcknowledgement>;
158
+ deriveTopic(topicId: string, input: RuntimeGatewayTopicDeriveInput): Promise<RuntimeGatewayDerivedTopic>;
141
159
  ensureManagerTopic(userId: string): Promise<RuntimeGatewayManagerTopic>;
142
160
  private cronRequest;
143
161
  listCronScripts(): Promise<string[]>;
@@ -16,6 +16,7 @@ export interface RuntimeUserTurnExecution {
16
16
  sessionType?: "dm" | "forum" | "ephemeral" | "manager" | "cron";
17
17
  visualTools?: boolean;
18
18
  fileDeliveryTools?: boolean;
19
+ silent?: boolean;
19
20
  bridgeSessionFromHistory?: boolean;
20
21
  peerBridge?: PeerRuntimeBridgeContext;
21
22
  from?: string;
@@ -1 +1 @@
1
- export declare const NEGOTIUM_VERSION = "0.6.1";
1
+ export declare const NEGOTIUM_VERSION = "0.6.3";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "negotium",
3
- "version": "0.6.1",
3
+ "version": "0.6.3",
4
4
  "type": "module",
5
5
  "description": "Install the Negotium multi-agent runtime and CLI with one package",
6
6
  "license": "Apache-2.0",