@dreb/coding-agent 2.64.0 → 2.64.1
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/README.md +1 -1
- package/dist/core/output-guard.d.ts +9 -1
- package/dist/core/output-guard.d.ts.map +1 -1
- package/dist/core/output-guard.js +75 -20
- package/dist/core/output-guard.js.map +1 -1
- package/dist/modes/rpc/index.d.ts +1 -0
- package/dist/modes/rpc/index.d.ts.map +1 -1
- package/dist/modes/rpc/index.js +1 -0
- package/dist/modes/rpc/index.js.map +1 -1
- package/dist/modes/rpc/rpc-client.d.ts +1 -0
- package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-client.js +21 -1
- package/dist/modes/rpc/rpc-client.js.map +1 -1
- package/dist/modes/rpc/rpc-event-projection.d.ts +7 -0
- package/dist/modes/rpc/rpc-event-projection.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-event-projection.js +161 -0
- package/dist/modes/rpc/rpc-event-projection.js.map +1 -1
- package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-mode.js +10 -7
- package/dist/modes/rpc/rpc-mode.js.map +1 -1
- package/docs/dashboard.md +15 -1
- package/docs/rpc.md +14 -0
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rpc-client.js","sourceRoot":"","sources":["../../../src/modes/rpc/rpc-client.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAqB,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAM9D,OAAO,EAAE,qBAAqB,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AA0BtE,+EAA+E;AAC/E,QAAQ;AACR,+EAA+E;AAE/E;;;GAGG;AACH,MAAM,aAAa,GAAG,GAAG,CAAC;AA2D1B,SAAS,YAAY,CAAC,KAAc,EAAuB;IAC1D,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,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GAAG,OAAO,EAAE,EAAE,EAAgB,CAAC;QAErD,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE,CAAC;YACvC,MAAM,OAAO,GAAG,UAAU,CAAC,GAAG,EAAE,CAAC;gBAChC,IAAI,CAAC,eAAe,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;gBAChC,MAAM,CAAC,IAAI,KAAK,CAAC,mCAAmC,OAAO,CAAC,IAAI,aAAa,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;YAAA,CAC7F,EAAE,SAAS,CAAC,CAAC;YAEd,IAAI,CAAC,eAAe,CAAC,GAAG,CAAC,EAAE,EAAE;gBAC5B,OAAO,EAAE,CAAC,QAAQ,EAAE,EAAE,CAAC;oBACtB,YAAY,CAAC,OAAO,CAAC,CAAC;oBACtB,OAAO,CAAC,QAAQ,CAAC,CAAC;gBAAA,CAClB;gBACD,MAAM,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC;oBAClB,YAAY,CAAC,OAAO,CAAC,CAAC;oBACtB,MAAM,CAAC,KAAK,CAAC,CAAC;gBAAA,CACd;aACD,CAAC,CAAC;YAEH,IAAI,CAAC,OAAQ,CAAC,KAAM,CAAC,KAAK,CAAC,iBAAiB,CAAC,WAAW,CAAC,CAAC,CAAC;QAAA,CAC3D,CAAC,CAAC;IAAA,CACH;IAEO,OAAO,CAAI,QAAqB,EAAK;QAC5C,IAAI,CAAC,QAAQ,CAAC,OAAO,EAAE,CAAC;YACvB,MAAM,aAAa,GAAG,QAAoD,CAAC;YAC3E,MAAM,IAAI,KAAK,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC;QACtC,CAAC;QACD,8EAA8E;QAC9E,mFAAmF;QACnF,MAAM,eAAe,GAAG,QAAkE,CAAC;QAC3F,OAAO,eAAe,CAAC,IAAS,CAAC;IAAA,CACjC;CACD","sourcesContent":["/**\n * RPC Client for programmatic access to the coding agent.\n *\n * Spawns the agent in RPC mode and provides a typed API for all operations.\n */\n\nimport { type ChildProcess, spawn } from \"node:child_process\";\nimport type { AgentMessage, ThinkingLevel } from \"@dreb/agent-core\";\nimport type { ImageContent } from \"@dreb/ai\";\nimport type { SessionStats } from \"../../core/agent-session.js\";\nimport type { BashResult } from \"../../core/bash-executor.js\";\nimport type { CompactionResult } from \"../../core/compaction/index.js\";\nimport { attachJsonlLineReader, serializeJsonLine } from \"./jsonl.js\";\nimport type {\n\tRpcAgentTypeInfo,\n\tRpcBackgroundAgentInfo,\n\tRpcCommand,\n\tRpcContextTrustEvaluation,\n\tRpcContextTrustMutationResult,\n\tRpcDashboardSnapshot,\n\tRpcDashboardSnapshotBarrierEvent,\n\tRpcEvent,\n\tRpcExtensionUIRequest,\n\tRpcExtensionUIResponse,\n\tRpcPendingMessages,\n\tRpcPerformanceStats,\n\tRpcResources,\n\tRpcResponse,\n\tRpcSessionInfo,\n\tRpcSessionState,\n\tRpcSettingsSetResult,\n\tRpcSettingsSnapshot,\n\tRpcSettingsUpdate,\n\tRpcSlashCommand,\n\tRpcTreeNode,\n\tRpcTrustedFolderRemovalResult,\n} from \"./rpc-types.js\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Grace period (ms) start() waits for the child to initialize before treating\n * it as alive. An 'error'/'exit' event during this window rejects start() early.\n */\nconst INIT_GRACE_MS = 100;\n\n/** Distributive Omit that works with union types */\ntype DistributiveOmit<T, K extends keyof T> = T extends unknown ? Omit<T, K> : never;\n\n/** RpcCommand without the id field (for internal send) */\ntype RpcCommandBody = DistributiveOmit<RpcCommand, \"id\">;\n\nexport interface RpcClientOptions {\n\t/** Path to the CLI entry point (default: searches for dist/cli.js) */\n\tcliPath?: string;\n\t/** Working directory for the agent */\n\tcwd?: string;\n\t/** Environment variables */\n\tenv?: Record<string, string>;\n\t/** Provider to use */\n\tprovider?: string;\n\t/** Model ID to use */\n\tmodel?: string;\n\t/** Additional CLI arguments */\n\targs?: string[];\n\t/**\n\t * Run the agent child process under this OS user id.\n\t * Forwarded directly to `child_process.spawn`. The parent process must hold\n\t * `CAP_SETUID` (typically by running as root) for this to succeed; otherwise\n\t * the spawn fails and `start()` rejects. Omitted when unset (default behavior).\n\t */\n\tuid?: number;\n\t/**\n\t * Run the agent child process under this OS group id.\n\t * Forwarded directly to `child_process.spawn`. The parent process must hold\n\t * `CAP_SETGID` (typically by running as root) for this to succeed; otherwise\n\t * the spawn fails and `start()` rejects. Omitted when unset (default behavior).\n\t */\n\tgid?: number;\n}\n\nexport interface ModelInfo {\n\tprovider: string;\n\tid: string;\n\tcontextWindow: number;\n\treasoning: boolean;\n}\n\n/**\n * Listener for non-response messages streamed by the RPC server. The wire carries\n * the full {@link RpcEvent} union: session events, extension UI requests, and\n * RPC-specific ordering markers such as `dashboard_snapshot_barrier`.\n */\nexport type RpcEventListener = (event: RpcEvent) => void;\n\nexport type RpcExitInfo =\n\t| { code: number | null; signal: NodeJS.Signals | null; error?: undefined }\n\t| { code?: undefined; signal?: undefined; error: Error };\n\nexport type RpcExitListener = (info: RpcExitInfo) => void;\n\ntype JsonRecord = Record<string, unknown>;\n\nfunction isJsonRecord(value: unknown): value is JsonRecord {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isRpcResponseMessage(value: unknown): value is RpcResponse {\n\treturn isJsonRecord(value) && value.type === \"response\";\n}\n\nfunction isRpcDashboardSnapshotBarrierEvent(value: unknown): value is RpcDashboardSnapshotBarrierEvent {\n\treturn isJsonRecord(value) && value.type === \"dashboard_snapshot_barrier\" && typeof value.snapshotId === \"string\";\n}\n\nfunction isRpcExtensionUIRequestMessage(value: unknown): value is RpcExtensionUIRequest {\n\treturn (\n\t\tisJsonRecord(value) &&\n\t\tvalue.type === \"extension_ui_request\" &&\n\t\ttypeof value.id === \"string\" &&\n\t\ttypeof value.method === \"string\"\n\t);\n}\n\nfunction isRpcEvent(value: unknown): value is RpcEvent {\n\tif (!isJsonRecord(value) || typeof value.type !== \"string\" || value.type === \"response\") {\n\t\treturn false;\n\t}\n\tif (value.type === \"dashboard_snapshot_barrier\") {\n\t\treturn isRpcDashboardSnapshotBarrierEvent(value);\n\t}\n\tif (value.type === \"extension_ui_request\") {\n\t\treturn isRpcExtensionUIRequestMessage(value);\n\t}\n\treturn true;\n}\n\n// ============================================================================\n// RPC Client\n// ============================================================================\n\nexport class RpcClient {\n\tprivate process: ChildProcess | null = null;\n\tprivate stopReadingStdout: (() => void) | null = null;\n\tprivate eventListeners: RpcEventListener[] = [];\n\tprivate exitListeners = new Set<RpcExitListener>();\n\tprivate pendingRequests: Map<string, { resolve: (response: RpcResponse) => void; reject: (error: Error) => void }> =\n\t\tnew Map();\n\tprivate requestId = 0;\n\tprivate stderr = \"\";\n\tprivate _dead = false;\n\tprivate spawnError: Error | null = null;\n\n\tconstructor(private options: RpcClientOptions = {}) {}\n\n\t/**\n\t * Start the RPC agent process.\n\t */\n\tasync start(): Promise<void> {\n\t\tif (this.process) {\n\t\t\tthrow new Error(\"Client already started\");\n\t\t}\n\n\t\tconst cliPath = this.options.cliPath ?? \"dist/cli.js\";\n\t\tconst args = [\"--mode\", \"rpc\"];\n\n\t\tif (this.options.provider) {\n\t\t\targs.push(\"--provider\", this.options.provider);\n\t\t}\n\t\tif (this.options.model) {\n\t\t\targs.push(\"--model\", this.options.model);\n\t\t}\n\t\tif (this.options.args) {\n\t\t\targs.push(...this.options.args);\n\t\t}\n\n\t\tthis.process = spawn(\"node\", [cliPath, ...args], {\n\t\t\tcwd: this.options.cwd,\n\t\t\tenv: { ...process.env, ...this.options.env },\n\t\t\tstdio: [\"pipe\", \"pipe\", \"pipe\"],\n\t\t\t...(this.options.uid != null ? { uid: this.options.uid } : {}),\n\t\t\t...(this.options.gid != null ? { gid: this.options.gid } : {}),\n\t\t});\n\n\t\tthis._dead = false;\n\t\tthis.spawnError = null;\n\n\t\t// Collect stderr for debugging\n\t\tthis.process.stderr?.on(\"data\", (data) => {\n\t\t\tthis.stderr += data.toString();\n\t\t});\n\n\t\t// Detect process exit and spawn failures for the whole session lifecycle —\n\t\t// reject pending requests so callers don't hang. Capture the process\n\t\t// reference so stale handlers from a previous process don't clobber state\n\t\t// after a stop()/start() cycle.\n\t\tconst procRef = this.process;\n\t\tprocRef.on(\"exit\", (code, signal) => {\n\t\t\t// Guard: skip if this handler belongs to an old, already-stopped process\n\t\t\tif (this.process !== procRef) return;\n\t\t\tthis.failPendingRequests(`RPC process exited with code ${code}, signal ${signal}`);\n\t\t\tthis.notifyExitListeners({ code, signal });\n\t\t});\n\n\t\t// Spawn failures surface asynchronously as an 'error' event rather than a\n\t\t// thrown exception (e.g. EPERM when dropping to a uid/gid the parent lacks\n\t\t// CAP_SETUID/CAP_SETGID for, or unsupported on Windows). Without a listener\n\t\t// an 'error' event would crash the process; record the cause so start() can\n\t\t// fail loudly and a later send() can report the real reason instead of a\n\t\t// generic \"not running\".\n\t\tprocRef.on(\"error\", (err) => {\n\t\t\t// Guard: skip if this handler belongs to an old, already-stopped process\n\t\t\tif (this.process !== procRef) return;\n\t\t\tthis.spawnError = err;\n\t\t\tthis.failPendingRequests(`RPC process failed to spawn: ${err.message}`);\n\t\t\tthis.notifyExitListeners({ error: err });\n\t\t});\n\n\t\t// Set up strict JSONL reader for stdout.\n\t\tthis.stopReadingStdout = attachJsonlLineReader(this.process.stdout!, (line) => {\n\t\t\tthis.handleLine(line);\n\t\t});\n\n\t\t// Give the process a moment to initialize, but settle as soon as an\n\t\t// 'error' or 'exit' event arrives. Racing the grace period against those\n\t\t// events (instead of a blind fixed sleep) guarantees that a failed\n\t\t// privilege drop (uid/gid EPERM) rejects start() loudly no matter when\n\t\t// libuv delivers the event — a fixed sleep could expire first and let\n\t\t// start() resolve despite the child never running.\n\t\tawait new Promise<void>((resolve, reject) => {\n\t\t\tconst onError = (err: Error) => {\n\t\t\t\tcleanup();\n\t\t\t\treject(new Error(`Agent process failed to spawn: ${err.message}. Stderr: ${this.stderr}`));\n\t\t\t};\n\t\t\tconst onExit = (code: number | null, signal: NodeJS.Signals | null) => {\n\t\t\t\tcleanup();\n\t\t\t\treject(\n\t\t\t\t\tnew Error(\n\t\t\t\t\t\t`Agent process exited immediately with code ${code}, signal ${signal}. Stderr: ${this.stderr}`,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t};\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tcleanup();\n\t\t\t\tresolve();\n\t\t\t}, INIT_GRACE_MS);\n\t\t\tconst cleanup = () => {\n\t\t\t\tclearTimeout(timer);\n\t\t\t\tprocRef.off(\"error\", onError);\n\t\t\t\tprocRef.off(\"exit\", onExit);\n\t\t\t};\n\t\t\tprocRef.once(\"error\", onError);\n\t\t\tprocRef.once(\"exit\", onExit);\n\t\t});\n\n\t\t// Belt-and-suspenders: a process that exited exactly as the grace timer\n\t\t// fired (so the race resolved instead of rejecting) still surfaces loudly.\n\t\tif (this.process.exitCode !== null) {\n\t\t\tthrow new Error(`Agent process exited immediately with code ${this.process.exitCode}. Stderr: ${this.stderr}`);\n\t\t}\n\t}\n\n\t/**\n\t * Stop the RPC agent process.\n\t */\n\tasync stop(): Promise<void> {\n\t\tif (!this.process) return;\n\n\t\tthis.stopReadingStdout?.();\n\t\tthis.stopReadingStdout = null;\n\t\tthis.process.kill(\"SIGTERM\");\n\n\t\t// Wait for process to exit\n\t\tawait new Promise<void>((resolve) => {\n\t\t\tconst timeout = setTimeout(() => {\n\t\t\t\tthis.process?.kill(\"SIGKILL\");\n\t\t\t\tresolve();\n\t\t\t}, 1000);\n\n\t\t\tthis.process?.on(\"exit\", () => {\n\t\t\t\tclearTimeout(timeout);\n\t\t\t\tresolve();\n\t\t\t});\n\t\t});\n\n\t\tthis.process = null;\n\t\tthis._dead = true;\n\t\tthis.pendingRequests.clear();\n\t}\n\n\t/**\n\t * Subscribe to agent events.\n\t */\n\tonEvent(listener: RpcEventListener): () => void {\n\t\tthis.eventListeners.push(listener);\n\t\treturn () => {\n\t\t\tconst index = this.eventListeners.indexOf(listener);\n\t\t\tif (index !== -1) {\n\t\t\t\tthis.eventListeners.splice(index, 1);\n\t\t\t}\n\t\t};\n\t}\n\n\t/**\n\t * Subscribe to child process death/spawn-failure notifications.\n\t */\n\tonExit(listener: RpcExitListener): () => void {\n\t\tthis.exitListeners.add(listener);\n\t\treturn () => {\n\t\t\tthis.exitListeners.delete(listener);\n\t\t};\n\t}\n\n\t/**\n\t * Get collected stderr output (useful for debugging).\n\t */\n\tgetStderr(): string {\n\t\treturn this.stderr;\n\t}\n\n\t// =========================================================================\n\t// Command Methods\n\t// =========================================================================\n\n\t/**\n\t * Send a prompt to the agent.\n\t * Returns immediately after sending; use onEvent() to receive streaming events.\n\t * Use waitForIdle() to wait for completion.\n\t */\n\tasync prompt(message: string, images?: ImageContent[]): Promise<void> {\n\t\tawait this.send({ type: \"prompt\", message, images });\n\t}\n\n\t/**\n\t * Queue a steering message to interrupt the agent mid-run.\n\t */\n\tasync steer(message: string, images?: ImageContent[]): Promise<void> {\n\t\tawait this.send({ type: \"steer\", message, images });\n\t}\n\n\t/**\n\t * Queue a follow-up message to be processed after the agent finishes.\n\t */\n\tasync followUp(message: string, images?: ImageContent[]): Promise<void> {\n\t\tawait this.send({ type: \"follow_up\", message, images });\n\t}\n\n\t/** Queue an unchanged steering message in a specific live background agent. */\n\tasync steerBackgroundAgent(agentId: string, message: string): Promise<void> {\n\t\tconst response = await this.send({ type: \"steer_background_agent\", agentId, message });\n\t\tthis.getData(response);\n\t}\n\n\t/** Read the selected live background agent's pending steering queue. */\n\tasync getBackgroundAgentPending(agentId: string): Promise<{\n\t\tsteeringMode: \"all\" | \"one-at-a-time\";\n\t\tpending: RpcPendingMessages;\n\t}> {\n\t\tconst response = await this.send({ type: \"get_background_agent_pending\", agentId });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Abort current operation.\n\t */\n\tasync abort(): Promise<void> {\n\t\tawait this.send({ type: \"abort\" });\n\t}\n\n\t/**\n\t * Start a new session, optionally with parent tracking.\n\t * @param parentSession - Optional parent session path for lineage tracking\n\t * @returns Object with `cancelled: true` if an extension cancelled the new session\n\t */\n\tasync newSession(parentSession?: string): Promise<{ cancelled: boolean }> {\n\t\tconst response = await this.send({ type: \"new_session\", parentSession });\n\t\treturn this.getData(response);\n\t}\n\n\t/** Reload extensions, skills, prompts, themes, and other session resources. */\n\tasync reload(): Promise<void> {\n\t\tawait this.send({ type: \"reload\" });\n\t}\n\n\t/** Run `/dream` or one of its backup-path forms. */\n\tasync dream(args?: string): Promise<{ message: string }> {\n\t\tconst response = await this.send({ type: \"dream\", args });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Get current session state.\n\t */\n\tasync getState(): Promise<RpcSessionState> {\n\t\tconst response = await this.send({ type: \"get_state\" });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Capture a dashboard recovery snapshot. The RPC stream emits a matching\n\t * `dashboard_snapshot_barrier` immediately before this response; consumers\n\t * need that event's EventHub sequence before applying the snapshot.\n\t */\n\tasync getDashboardSnapshot(): Promise<RpcDashboardSnapshot> {\n\t\tconst response = await this.send({ type: \"get_dashboard_snapshot\" });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Get loaded context/resources metadata (paths/names only, no file contents).\n\t */\n\tasync getResources(): Promise<RpcResources> {\n\t\tconst response = await this.send({ type: \"get_resources\" });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Get current git branch for the agent cwd.\n\t */\n\tasync getGitBranch(): Promise<string | null> {\n\t\tconst response = await this.send({ type: \"get_git_branch\" });\n\t\treturn this.getData<{ branch: string | null }>(response).branch;\n\t}\n\n\t/**\n\t * Get cached same-day cost across all sessions, primed by the server on first call.\n\t */\n\tasync getDailyCost(): Promise<number> {\n\t\tconst response = await this.send({ type: \"get_daily_cost\" });\n\t\treturn this.getData<{ cost: number }>(response).cost;\n\t}\n\n\t/**\n\t * Set model by provider and ID.\n\t */\n\tasync setModel(provider: string, modelId: string): Promise<{ provider: string; id: string }> {\n\t\tconst response = await this.send({ type: \"set_model\", provider, modelId });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Cycle to next model.\n\t */\n\tasync cycleModel(): Promise<{\n\t\tmodel: { provider: string; id: string };\n\t\tthinkingLevel: ThinkingLevel;\n\t\tisScoped: boolean;\n\t} | null> {\n\t\tconst response = await this.send({ type: \"cycle_model\" });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Get list of available models.\n\t */\n\tasync getAvailableModels(): Promise<ModelInfo[]> {\n\t\tconst response = await this.send({ type: \"get_available_models\" });\n\t\treturn this.getData<{ models: ModelInfo[] }>(response).models;\n\t}\n\n\t/**\n\t * Resolve a model pattern using the same logic as CLI/TUI.\n\t * Runs server-side so API keys never leave the process.\n\t * Returns null if no match found.\n\t */\n\tasync resolveModel(pattern: string): Promise<{ model: ModelInfo; warning?: string } | null> {\n\t\tconst response = await this.send({ type: \"resolve_model\", pattern });\n\t\treturn this.getData<{ model: ModelInfo; warning?: string } | null>(response);\n\t}\n\n\t/**\n\t * Hatch a new buddy companion. Runs inside the agent process\n\t * so API keys never leave the process boundary.\n\t */\n\tasync buddyHatch(): Promise<import(\"../../core/buddy/buddy-types.js\").BuddyState> {\n\t\tconst response = await this.send({ type: \"buddy_hatch\" });\n\t\treturn this.getData<{ state: import(\"../../core/buddy/buddy-types.js\").BuddyState }>(response).state;\n\t}\n\n\t/**\n\t * Reroll the buddy companion. Runs inside the agent process\n\t * so API keys never leave the process boundary.\n\t */\n\tasync buddyReroll(): Promise<import(\"../../core/buddy/buddy-types.js\").BuddyState> {\n\t\tconst response = await this.send({ type: \"buddy_reroll\" });\n\t\treturn this.getData<{ state: import(\"../../core/buddy/buddy-types.js\").BuddyState }>(response).state;\n\t}\n\n\t/**\n\t * Set thinking level.\n\t */\n\tasync setThinkingLevel(level: ThinkingLevel): Promise<void> {\n\t\tawait this.send({ type: \"set_thinking_level\", level });\n\t}\n\n\t/**\n\t * Cycle thinking level.\n\t */\n\tasync cycleThinkingLevel(): Promise<{ level: ThinkingLevel } | null> {\n\t\tconst response = await this.send({ type: \"cycle_thinking_level\" });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Set steering mode.\n\t */\n\tasync setSteeringMode(mode: \"all\" | \"one-at-a-time\"): Promise<void> {\n\t\tawait this.send({ type: \"set_steering_mode\", mode });\n\t}\n\n\t/**\n\t * Set follow-up mode.\n\t */\n\tasync setFollowUpMode(mode: \"all\" | \"one-at-a-time\"): Promise<void> {\n\t\tawait this.send({ type: \"set_follow_up_mode\", mode });\n\t}\n\n\t/**\n\t * Get pending steering and follow-up messages without clearing them.\n\t */\n\tasync getPendingMessages(): Promise<RpcPendingMessages> {\n\t\tconst response = await this.send({ type: \"get_pending_messages\" });\n\t\treturn this.getData<RpcPendingMessages>(response);\n\t}\n\n\t/**\n\t * Clear pending steering and follow-up messages, returning the cleared text.\n\t */\n\tasync clearPendingMessages(): Promise<RpcPendingMessages> {\n\t\tconst response = await this.send({ type: \"clear_pending_messages\" });\n\t\treturn this.getData<RpcPendingMessages>(response);\n\t}\n\n\t/**\n\t * Compact session context.\n\t */\n\tasync compact(customInstructions?: string): Promise<CompactionResult> {\n\t\tconst response = await this.send({ type: \"compact\", customInstructions });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Set auto-compaction enabled/disabled.\n\t */\n\tasync setAutoCompaction(enabled: boolean): Promise<void> {\n\t\tawait this.send({ type: \"set_auto_compaction\", enabled });\n\t}\n\n\t/**\n\t * Abort in-progress compaction.\n\t */\n\tasync abortCompaction(): Promise<void> {\n\t\tawait this.send({ type: \"abort_compaction\" });\n\t}\n\n\t/**\n\t * Set auto-retry enabled/disabled.\n\t */\n\tasync setAutoRetry(enabled: boolean): Promise<void> {\n\t\tawait this.send({ type: \"set_auto_retry\", enabled });\n\t}\n\n\t/**\n\t * Abort in-progress retry.\n\t */\n\tasync abortRetry(): Promise<void> {\n\t\tawait this.send({ type: \"abort_retry\" });\n\t}\n\n\t/**\n\t * Execute a bash command.\n\t */\n\tasync bash(command: string): Promise<BashResult> {\n\t\tconst response = await this.send({ type: \"bash\", command });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Abort running bash command.\n\t */\n\tasync abortBash(): Promise<void> {\n\t\tawait this.send({ type: \"abort_bash\" });\n\t}\n\n\t/**\n\t * Get session statistics.\n\t */\n\tasync getSessionStats(): Promise<SessionStats> {\n\t\tconst response = await this.send({ type: \"get_session_stats\" });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Get performance statistics.\n\t */\n\tasync getPerformanceStats(): Promise<RpcPerformanceStats> {\n\t\tconst response = await this.send({ type: \"get_performance_stats\" });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Export session to HTML.\n\t */\n\tasync exportHtml(outputPath?: string): Promise<{ path: string }> {\n\t\tconst response = await this.send({ type: \"export_html\", outputPath });\n\t\treturn this.getData(response);\n\t}\n\n\t/** Import a JSONL file into the current runtime. */\n\tasync importJsonl(inputPath: string): Promise<{ cancelled: boolean }> {\n\t\tconst response = await this.send({ type: \"import_jsonl\", inputPath });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Switch to a different session file.\n\t * @returns Object with `cancelled: true` if an extension cancelled the switch\n\t */\n\tasync switchSession(sessionPath: string): Promise<{ cancelled: boolean }> {\n\t\tconst response = await this.send({ type: \"switch_session\", sessionPath });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Delete a session file, trying trash first and falling back to unlink.\n\t * Throws on failure, including when attempting to delete the active session.\n\t */\n\tasync deleteSession(sessionPath: string): Promise<{ method: \"trash\" | \"unlink\" }> {\n\t\tconst response = await this.send({ type: \"delete_session\", sessionPath });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Fork from a specific message.\n\t * @returns Object with `text` (the message text) and `cancelled` (if extension cancelled)\n\t */\n\tasync fork(entryId: string): Promise<{ text: string; cancelled: boolean }> {\n\t\tconst response = await this.send({ type: \"fork\", entryId });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Get messages available for forking.\n\t */\n\tasync getForkMessages(): Promise<Array<{ entryId: string; text: string; role: \"user\" | \"assistant\" }>> {\n\t\tconst response = await this.send({ type: \"get_fork_messages\" });\n\t\treturn this.getData<{ messages: Array<{ entryId: string; text: string; role: \"user\" | \"assistant\" }> }>(response)\n\t\t\t.messages;\n\t}\n\n\t/**\n\t * Get the session tree and current leaf.\n\t */\n\tasync getTree(): Promise<{ roots: RpcTreeNode[]; leafId: string | null }> {\n\t\tconst response = await this.send({ type: \"get_tree\" });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Navigate to a session tree entry.\n\t * @param targetId Entry ID to navigate to\n\t * @param options Navigation options; timeoutMs is client-side only and is not sent over RPC\n\t * @returns Object with `cancelled: true` if navigation was cancelled, and `editorText` when re-editing a message\n\t */\n\tasync navigateTree(\n\t\ttargetId: string,\n\t\toptions?: {\n\t\t\tsummarize?: boolean;\n\t\t\tcustomInstructions?: string;\n\t\t\treplaceInstructions?: boolean;\n\t\t\tlabel?: string;\n\t\t\ttimeoutMs?: number;\n\t\t},\n\t): Promise<{ cancelled: boolean; editorText?: string }> {\n\t\tconst { timeoutMs = 300000, ...commandOptions } = options ?? {};\n\t\tconst response = await this.send({ type: \"navigate_tree\", targetId, ...commandOptions }, timeoutMs);\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Get text of last assistant message.\n\t */\n\tasync getLastAssistantText(): Promise<string | null> {\n\t\tconst response = await this.send({ type: \"get_last_assistant_text\" });\n\t\treturn this.getData<{ text: string | null }>(response).text;\n\t}\n\n\t/**\n\t * Set the session display name.\n\t */\n\tasync setSessionName(name: string): Promise<void> {\n\t\tawait this.send({ type: \"set_session_name\", name });\n\t}\n\n\t/**\n\t * Get all messages in the session.\n\t */\n\tasync getMessages(): Promise<AgentMessage[]> {\n\t\tconst response = await this.send({ type: \"get_messages\" });\n\t\treturn this.getData<{ messages: AgentMessage[] }>(response).messages;\n\t}\n\n\t/**\n\t * Get discoverable commands, including built-ins that require client-side handling.\n\t */\n\tasync getCommands(): Promise<RpcSlashCommand[]> {\n\t\tconst response = await this.send({ type: \"get_commands\" });\n\t\treturn this.getData<{ commands: RpcSlashCommand[] }>(response).commands;\n\t}\n\n\t/**\n\t * List sessions for the current working directory.\n\t * Returns sessions sorted by most recently modified first.\n\t */\n\tasync listSessions(): Promise<RpcSessionInfo[]> {\n\t\tconst response = await this.send({ type: \"list_sessions\" });\n\t\treturn this.getData<{ sessions: RpcSessionInfo[] }>(response).sessions;\n\t}\n\n\t/**\n\t * List sessions across all projects.\n\t * Returns sessions sorted by most recently modified first. May be slow with many sessions.\n\t */\n\tasync listAllSessions(): Promise<RpcSessionInfo[]> {\n\t\tconst response = await this.send({ type: \"list_all_sessions\" });\n\t\treturn this.getData<{ sessions: RpcSessionInfo[] }>(response).sessions;\n\t}\n\n\t/**\n\t * List background subagents tracked by the server's registry (running and\n\t * recently completed), including session dir/file paths where known.\n\t */\n\tasync listBackgroundAgents(): Promise<RpcBackgroundAgentInfo[]> {\n\t\tconst response = await this.send({ type: \"list_background_agents\" });\n\t\treturn this.getData<{ agents: RpcBackgroundAgentInfo[] }>(response).agents;\n\t}\n\n\t/**\n\t * List discoverable subagent types for the server's current working directory.\n\t */\n\tasync listAgentTypes(): Promise<RpcAgentTypeInfo[]> {\n\t\tconst response = await this.send({ type: \"list_agent_types\" });\n\t\treturn this.getData<{ agentTypes: RpcAgentTypeInfo[] }>(response).agentTypes;\n\t}\n\n\t/**\n\t * Answer an extension UI request (select/confirm/input/editor) previously\n\t * received as an `extension_ui_request` event. Fire-and-forget: the server\n\t * does not send a response to this message.\n\t */\n\tsendExtensionUIResponse(response: RpcExtensionUIResponse): void {\n\t\tif (this._dead || !this.process?.stdin) {\n\t\t\tconst cause = this.spawnError ? ` Spawn error: ${this.spawnError.message}.` : \"\";\n\t\t\tthrow new Error(`RPC process is not running.${cause} Stderr: ${this.stderr}`);\n\t\t}\n\t\tthis.process.stdin.write(serializeJsonLine(response));\n\t}\n\n\t/**\n\t * Get the dreb version.\n\t */\n\tasync getVersion(): Promise<string> {\n\t\tconst response = await this.send({ type: \"get_version\" });\n\t\treturn this.getData<{ version: string }>(response).version;\n\t}\n\n\t/**\n\t * Get the persistent default settings (SettingsManager-backed).\n\t * These seed fresh runtimes — for live session state use getState().\n\t */\n\tasync getSettings(): Promise<RpcSettingsSnapshot> {\n\t\tconst response = await this.send({ type: \"get_settings\" });\n\t\treturn this.getData<RpcSettingsSnapshot>(response);\n\t}\n\n\t/**\n\t * Update persistent default settings. Validates the whole payload before applying\n\t * anything (atomic: on any invalid field, nothing changes). Does NOT touch live\n\t * session state — use setModel/setThinkingLevel/etc. for that.\n\t * Returns the full settings snapshot after the write, plus any loud warnings\n\t * (for example project-level agent model overrides shadowing global writes).\n\t */\n\tasync setSettings(settings: RpcSettingsUpdate): Promise<RpcSettingsSetResult> {\n\t\tconst response = await this.send({ type: \"set_settings\", settings });\n\t\treturn this.getData<RpcSettingsSetResult>(response);\n\t}\n\n\t/** Evaluate an existing directory against the server's global context-trust policy. */\n\tasync evaluateContextTrust(path: string): Promise<RpcContextTrustEvaluation> {\n\t\tconst response = await this.send({ type: \"evaluate_context_trust\", path });\n\t\treturn this.getData<RpcContextTrustEvaluation>(response);\n\t}\n\n\t/** Add an existing directory as a canonical global trusted context root. */\n\tasync trustContextFolder(path: string): Promise<RpcContextTrustMutationResult> {\n\t\tconst response = await this.send({ type: \"trust_context_folder\", path });\n\t\treturn this.getData<RpcContextTrustMutationResult>(response);\n\t}\n\n\t/** Remove the root that currently grants the directory context trust. */\n\tasync untrustContextFolder(path: string): Promise<RpcContextTrustMutationResult> {\n\t\tconst response = await this.send({ type: \"untrust_context_folder\", path });\n\t\treturn this.getData<RpcContextTrustMutationResult>(response);\n\t}\n\n\t/** Remove a configured trusted-folder string exactly as stored. */\n\tasync removeTrustedContextFolder(path: string): Promise<RpcTrustedFolderRemovalResult> {\n\t\tconst response = await this.send({ type: \"remove_trusted_context_folder\", path });\n\t\treturn this.getData<RpcTrustedFolderRemovalResult>(response);\n\t}\n\n\t// =========================================================================\n\t// Helpers\n\t// =========================================================================\n\n\t/**\n\t * Wait for agent to become idle (no streaming).\n\t * Resolves when agent_end event is received.\n\t */\n\twaitForIdle(timeout = 60000): Promise<void> {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tunsubscribe();\n\t\t\t\treject(new Error(`Timeout waiting for agent to become idle. Stderr: ${this.stderr}`));\n\t\t\t}, timeout);\n\n\t\t\tconst unsubscribe = this.onEvent((event) => {\n\t\t\t\tif (event.type === \"agent_end\") {\n\t\t\t\t\tclearTimeout(timer);\n\t\t\t\t\tunsubscribe();\n\t\t\t\t\tresolve();\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t}\n\n\t/**\n\t * Collect events until agent becomes idle.\n\t */\n\tcollectEvents(timeout = 60000): Promise<RpcEvent[]> {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst events: RpcEvent[] = [];\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tunsubscribe();\n\t\t\t\treject(new Error(`Timeout collecting events. Stderr: ${this.stderr}`));\n\t\t\t}, timeout);\n\n\t\t\tconst unsubscribe = this.onEvent((event) => {\n\t\t\t\tevents.push(event);\n\t\t\t\tif (event.type === \"agent_end\") {\n\t\t\t\t\tclearTimeout(timer);\n\t\t\t\t\tunsubscribe();\n\t\t\t\t\tresolve(events);\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t}\n\n\t/**\n\t * Send prompt and wait for completion, returning all events.\n\t */\n\tasync promptAndWait(message: string, images?: ImageContent[], timeout = 60000): Promise<RpcEvent[]> {\n\t\tconst eventsPromise = this.collectEvents(timeout);\n\t\tawait this.prompt(message, images);\n\t\treturn eventsPromise;\n\t}\n\n\t// =========================================================================\n\t// Internal\n\t// =========================================================================\n\n\t/**\n\t * Mark the client dead and reject every in-flight request with `message`.\n\t * Shared by the 'exit' and 'error' handlers so both failure paths surface\n\t * loudly and consistently instead of leaving callers hanging.\n\t */\n\tprivate failPendingRequests(message: string): void {\n\t\tthis._dead = true;\n\t\tfor (const pending of this.pendingRequests.values()) {\n\t\t\tpending.reject(new Error(message));\n\t\t}\n\t\tthis.pendingRequests.clear();\n\t}\n\n\tprivate notifyExitListeners(info: RpcExitInfo): void {\n\t\tfor (const listener of this.exitListeners) {\n\t\t\tlistener(info);\n\t\t}\n\t}\n\n\tprivate handleLine(line: string): void {\n\t\ttry {\n\t\t\tconst data: unknown = JSON.parse(line);\n\n\t\t\t// Check if it's a response to a pending request. Unknown/unsolicited\n\t\t\t// response frames are not events and should not be forwarded to listeners.\n\t\t\tif (isRpcResponseMessage(data)) {\n\t\t\t\tif (typeof data.id === \"string\" && this.pendingRequests.has(data.id)) {\n\t\t\t\t\tconst pending = this.pendingRequests.get(data.id)!;\n\t\t\t\t\tthis.pendingRequests.delete(data.id);\n\t\t\t\t\tpending.resolve(data);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (!isRpcEvent(data)) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tfor (const listener of this.eventListeners) {\n\t\t\t\tlistener(data);\n\t\t\t}\n\t\t} catch {\n\t\t\t// Ignore non-JSON lines\n\t\t}\n\t}\n\n\tprivate async send(command: RpcCommandBody, timeoutMs = 30000): Promise<RpcResponse> {\n\t\tif (this._dead || !this.process?.stdin) {\n\t\t\t// Surface the real spawn cause (e.g. uid/gid EPERM) if one was captured,\n\t\t\t// rather than a generic message that hides why the process is gone.\n\t\t\tthrow new Error(\n\t\t\t\tthis.spawnError ? `RPC process not running: ${this.spawnError.message}` : \"RPC process not running\",\n\t\t\t);\n\t\t}\n\n\t\tconst id = `req_${++this.requestId}`;\n\t\tconst fullCommand = { ...command, id } as RpcCommand;\n\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst timeout = setTimeout(() => {\n\t\t\t\tthis.pendingRequests.delete(id);\n\t\t\t\treject(new Error(`Timeout waiting for response to ${command.type}. Stderr: ${this.stderr}`));\n\t\t\t}, timeoutMs);\n\n\t\t\tthis.pendingRequests.set(id, {\n\t\t\t\tresolve: (response) => {\n\t\t\t\t\tclearTimeout(timeout);\n\t\t\t\t\tresolve(response);\n\t\t\t\t},\n\t\t\t\treject: (error) => {\n\t\t\t\t\tclearTimeout(timeout);\n\t\t\t\t\treject(error);\n\t\t\t\t},\n\t\t\t});\n\n\t\t\tthis.process!.stdin!.write(serializeJsonLine(fullCommand));\n\t\t});\n\t}\n\n\tprivate getData<T>(response: RpcResponse): T {\n\t\tif (!response.success) {\n\t\t\tconst errorResponse = response as Extract<RpcResponse, { success: false }>;\n\t\t\tthrow new Error(errorResponse.error);\n\t\t}\n\t\t// Type assertion: we trust response.data matches T based on the command sent.\n\t\t// This is safe because each public method specifies the correct T for its command.\n\t\tconst successResponse = response as Extract<RpcResponse, { success: true; data: unknown }>;\n\t\treturn successResponse.data as T;\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"rpc-client.js","sourceRoot":"","sources":["../../../src/modes/rpc/rpc-client.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAqB,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAM9D,OAAO,EAAE,qBAAqB,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AA0BtE,+EAA+E;AAC/E,QAAQ;AACR,+EAA+E;AAE/E;;;GAGG;AACH,MAAM,aAAa,GAAG,GAAG,CAAC;AAC1B,sFAAsF;AACtF,MAAM,iBAAiB,GAAG,IAAI,CAAC;AA2D/B,SAAS,YAAY,CAAC,KAAc,EAAuB;IAC1D,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAAA,CAC5E;AAED,SAAS,oBAAoB,CAAC,KAAc,EAAwB;IACnE,OAAO,YAAY,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,IAAI,KAA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AC;oBACtB,OAAO,CAAC,QAAQ,CAAC,CAAC;gBAAA,CAClB;gBACD,MAAM,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC;oBAClB,YAAY,CAAC,OAAO,CAAC,CAAC;oBACtB,MAAM,CAAC,KAAK,CAAC,CAAC;gBAAA,CACd;aACD,CAAC,CAAC;YAEH,IAAI,CAAC,OAAQ,CAAC,KAAM,CAAC,KAAK,CAAC,iBAAiB,CAAC,WAAW,CAAC,CAAC,CAAC;QAAA,CAC3D,CAAC,CAAC;IAAA,CACH;IAEO,OAAO,CAAI,QAAqB,EAAK;QAC5C,IAAI,CAAC,QAAQ,CAAC,OAAO,EAAE,CAAC;YACvB,MAAM,aAAa,GAAG,QAAoD,CAAC;YAC3E,MAAM,IAAI,KAAK,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC;QACtC,CAAC;QACD,8EAA8E;QAC9E,mFAAmF;QACnF,MAAM,eAAe,GAAG,QAAkE,CAAC;QAC3F,OAAO,eAAe,CAAC,IAAS,CAAC;IAAA,CACjC;CACD","sourcesContent":["/**\n * RPC Client for programmatic access to the coding agent.\n *\n * Spawns the agent in RPC mode and provides a typed API for all operations.\n */\n\nimport { type ChildProcess, spawn } from \"node:child_process\";\nimport type { AgentMessage, ThinkingLevel } from \"@dreb/agent-core\";\nimport type { ImageContent } from \"@dreb/ai\";\nimport type { SessionStats } from \"../../core/agent-session.js\";\nimport type { BashResult } from \"../../core/bash-executor.js\";\nimport type { CompactionResult } from \"../../core/compaction/index.js\";\nimport { attachJsonlLineReader, serializeJsonLine } from \"./jsonl.js\";\nimport type {\n\tRpcAgentTypeInfo,\n\tRpcBackgroundAgentInfo,\n\tRpcCommand,\n\tRpcContextTrustEvaluation,\n\tRpcContextTrustMutationResult,\n\tRpcDashboardSnapshot,\n\tRpcDashboardSnapshotBarrierEvent,\n\tRpcEvent,\n\tRpcExtensionUIRequest,\n\tRpcExtensionUIResponse,\n\tRpcPendingMessages,\n\tRpcPerformanceStats,\n\tRpcResources,\n\tRpcResponse,\n\tRpcSessionInfo,\n\tRpcSessionState,\n\tRpcSettingsSetResult,\n\tRpcSettingsSnapshot,\n\tRpcSettingsUpdate,\n\tRpcSlashCommand,\n\tRpcTreeNode,\n\tRpcTrustedFolderRemovalResult,\n} from \"./rpc-types.js\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Grace period (ms) start() waits for the child to initialize before treating\n * it as alive. An 'error'/'exit' event during this window rejects start() early.\n */\nconst INIT_GRACE_MS = 100;\n/** Maximum child-stderr characters attached to exit notifications for diagnostics. */\nconst STDERR_TAIL_CHARS = 2000;\n\n/** Distributive Omit that works with union types */\ntype DistributiveOmit<T, K extends keyof T> = T extends unknown ? Omit<T, K> : never;\n\n/** RpcCommand without the id field (for internal send) */\ntype RpcCommandBody = DistributiveOmit<RpcCommand, \"id\">;\n\nexport interface RpcClientOptions {\n\t/** Path to the CLI entry point (default: searches for dist/cli.js) */\n\tcliPath?: string;\n\t/** Working directory for the agent */\n\tcwd?: string;\n\t/** Environment variables */\n\tenv?: Record<string, string>;\n\t/** Provider to use */\n\tprovider?: string;\n\t/** Model ID to use */\n\tmodel?: string;\n\t/** Additional CLI arguments */\n\targs?: string[];\n\t/**\n\t * Run the agent child process under this OS user id.\n\t * Forwarded directly to `child_process.spawn`. The parent process must hold\n\t * `CAP_SETUID` (typically by running as root) for this to succeed; otherwise\n\t * the spawn fails and `start()` rejects. Omitted when unset (default behavior).\n\t */\n\tuid?: number;\n\t/**\n\t * Run the agent child process under this OS group id.\n\t * Forwarded directly to `child_process.spawn`. The parent process must hold\n\t * `CAP_SETGID` (typically by running as root) for this to succeed; otherwise\n\t * the spawn fails and `start()` rejects. Omitted when unset (default behavior).\n\t */\n\tgid?: number;\n}\n\nexport interface ModelInfo {\n\tprovider: string;\n\tid: string;\n\tcontextWindow: number;\n\treasoning: boolean;\n}\n\n/**\n * Listener for non-response messages streamed by the RPC server. The wire carries\n * the full {@link RpcEvent} union: session events, extension UI requests, and\n * RPC-specific ordering markers such as `dashboard_snapshot_barrier`.\n */\nexport type RpcEventListener = (event: RpcEvent) => void;\n\nexport type RpcExitInfo =\n\t| { code: number | null; signal: NodeJS.Signals | null; stderrTail?: string; error?: undefined }\n\t| { code?: undefined; signal?: undefined; error: Error };\n\nexport type RpcExitListener = (info: RpcExitInfo) => void;\n\ntype JsonRecord = Record<string, unknown>;\n\nfunction isJsonRecord(value: unknown): value is JsonRecord {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isRpcResponseMessage(value: unknown): value is RpcResponse {\n\treturn isJsonRecord(value) && value.type === \"response\";\n}\n\nfunction isRpcDashboardSnapshotBarrierEvent(value: unknown): value is RpcDashboardSnapshotBarrierEvent {\n\treturn isJsonRecord(value) && value.type === \"dashboard_snapshot_barrier\" && typeof value.snapshotId === \"string\";\n}\n\nfunction isRpcExtensionUIRequestMessage(value: unknown): value is RpcExtensionUIRequest {\n\treturn (\n\t\tisJsonRecord(value) &&\n\t\tvalue.type === \"extension_ui_request\" &&\n\t\ttypeof value.id === \"string\" &&\n\t\ttypeof value.method === \"string\"\n\t);\n}\n\nfunction isRpcEvent(value: unknown): value is RpcEvent {\n\tif (!isJsonRecord(value) || typeof value.type !== \"string\" || value.type === \"response\") {\n\t\treturn false;\n\t}\n\tif (value.type === \"dashboard_snapshot_barrier\") {\n\t\treturn isRpcDashboardSnapshotBarrierEvent(value);\n\t}\n\tif (value.type === \"extension_ui_request\") {\n\t\treturn isRpcExtensionUIRequestMessage(value);\n\t}\n\treturn true;\n}\n\n// ============================================================================\n// RPC Client\n// ============================================================================\n\nexport class RpcClient {\n\tprivate process: ChildProcess | null = null;\n\tprivate stopReadingStdout: (() => void) | null = null;\n\tprivate eventListeners: RpcEventListener[] = [];\n\tprivate exitListeners = new Set<RpcExitListener>();\n\tprivate pendingRequests: Map<string, { resolve: (response: RpcResponse) => void; reject: (error: Error) => void }> =\n\t\tnew Map();\n\tprivate requestId = 0;\n\tprivate stderr = \"\";\n\tprivate _dead = false;\n\tprivate spawnError: Error | null = null;\n\n\tconstructor(private options: RpcClientOptions = {}) {}\n\n\t/**\n\t * Start the RPC agent process.\n\t */\n\tasync start(): Promise<void> {\n\t\tif (this.process) {\n\t\t\tthrow new Error(\"Client already started\");\n\t\t}\n\n\t\tconst cliPath = this.options.cliPath ?? \"dist/cli.js\";\n\t\tconst args = [\"--mode\", \"rpc\"];\n\n\t\tif (this.options.provider) {\n\t\t\targs.push(\"--provider\", this.options.provider);\n\t\t}\n\t\tif (this.options.model) {\n\t\t\targs.push(\"--model\", this.options.model);\n\t\t}\n\t\tif (this.options.args) {\n\t\t\targs.push(...this.options.args);\n\t\t}\n\n\t\tthis.process = spawn(\"node\", [cliPath, ...args], {\n\t\t\tcwd: this.options.cwd,\n\t\t\tenv: { ...process.env, ...this.options.env },\n\t\t\tstdio: [\"pipe\", \"pipe\", \"pipe\"],\n\t\t\t...(this.options.uid != null ? { uid: this.options.uid } : {}),\n\t\t\t...(this.options.gid != null ? { gid: this.options.gid } : {}),\n\t\t});\n\n\t\tthis._dead = false;\n\t\tthis.spawnError = null;\n\n\t\t// Collect stderr for debugging\n\t\tthis.process.stderr?.on(\"data\", (data) => {\n\t\t\tthis.stderr += data.toString();\n\t\t});\n\n\t\t// Detect process exit and spawn failures for the whole session lifecycle —\n\t\t// reject pending requests so callers don't hang. Capture the process\n\t\t// reference so stale handlers from a previous process don't clobber state\n\t\t// after a stop()/start() cycle.\n\t\tconst procRef = this.process;\n\t\tprocRef.on(\"exit\", (code, signal) => {\n\t\t\t// Guard: skip if this handler belongs to an old, already-stopped process\n\t\t\tif (this.process !== procRef) return;\n\t\t\tthis.failPendingRequests(`RPC process exited with code ${code}, signal ${signal}`);\n\t\t\t// Surface the child's own fatal diagnostic (e.g. the stdout\n\t\t\t// backpressure abort) in the exit notification so dashboard\n\t\t\t// diagnostics can show the real cause instead of a bare exit code.\n\t\t\tthis.notifyExitListeners({ code, signal, stderrTail: this.stderr.slice(-STDERR_TAIL_CHARS) });\n\t\t});\n\n\t\t// Child stdio pipes fail asynchronously as 'error' events (e.g. EPIPE\n\t\t// when writing a large prompt to the stdin of a dying child). An\n\t\t// unhandled pipe 'error' would crash this process — for the dashboard\n\t\t// that means every session dies at once — so record the cause and fail\n\t\t// in-flight requests the same way the 'exit' handler does. The 'exit'\n\t\t// handler still owns the exit notification; this only stops the crash.\n\t\tconst onPipeError = (stream: string) => (error: Error) => {\n\t\t\tif (this.process !== procRef) return;\n\t\t\tthis.stderr += `\\n[child ${stream} error: ${error.message}]`;\n\t\t\tthis.failPendingRequests(\n\t\t\t\t`RPC process ${stream} error: ${error.message}. Stderr: ${this.stderr.slice(-STDERR_TAIL_CHARS)}`,\n\t\t\t);\n\t\t};\n\t\tthis.process.stdin?.on(\"error\", onPipeError(\"stdin\"));\n\t\tthis.process.stdout?.on(\"error\", onPipeError(\"stdout\"));\n\t\tthis.process.stderr?.on(\"error\", onPipeError(\"stderr\"));\n\n\t\t// Spawn failures surface asynchronously as an 'error' event rather than a\n\t\t// thrown exception (e.g. EPERM when dropping to a uid/gid the parent lacks\n\t\t// CAP_SETUID/CAP_SETGID for, or unsupported on Windows). Without a listener\n\t\t// an 'error' event would crash the process; record the cause so start() can\n\t\t// fail loudly and a later send() can report the real reason instead of a\n\t\t// generic \"not running\".\n\t\tprocRef.on(\"error\", (err) => {\n\t\t\t// Guard: skip if this handler belongs to an old, already-stopped process\n\t\t\tif (this.process !== procRef) return;\n\t\t\tthis.spawnError = err;\n\t\t\tthis.failPendingRequests(`RPC process failed to spawn: ${err.message}`);\n\t\t\tthis.notifyExitListeners({ error: err });\n\t\t});\n\n\t\t// Set up strict JSONL reader for stdout.\n\t\tthis.stopReadingStdout = attachJsonlLineReader(this.process.stdout!, (line) => {\n\t\t\tthis.handleLine(line);\n\t\t});\n\n\t\t// Give the process a moment to initialize, but settle as soon as an\n\t\t// 'error' or 'exit' event arrives. Racing the grace period against those\n\t\t// events (instead of a blind fixed sleep) guarantees that a failed\n\t\t// privilege drop (uid/gid EPERM) rejects start() loudly no matter when\n\t\t// libuv delivers the event — a fixed sleep could expire first and let\n\t\t// start() resolve despite the child never running.\n\t\tawait new Promise<void>((resolve, reject) => {\n\t\t\tconst onError = (err: Error) => {\n\t\t\t\tcleanup();\n\t\t\t\treject(new Error(`Agent process failed to spawn: ${err.message}. Stderr: ${this.stderr}`));\n\t\t\t};\n\t\t\tconst onExit = (code: number | null, signal: NodeJS.Signals | null) => {\n\t\t\t\tcleanup();\n\t\t\t\treject(\n\t\t\t\t\tnew Error(\n\t\t\t\t\t\t`Agent process exited immediately with code ${code}, signal ${signal}. Stderr: ${this.stderr}`,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t};\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tcleanup();\n\t\t\t\tresolve();\n\t\t\t}, INIT_GRACE_MS);\n\t\t\tconst cleanup = () => {\n\t\t\t\tclearTimeout(timer);\n\t\t\t\tprocRef.off(\"error\", onError);\n\t\t\t\tprocRef.off(\"exit\", onExit);\n\t\t\t};\n\t\t\tprocRef.once(\"error\", onError);\n\t\t\tprocRef.once(\"exit\", onExit);\n\t\t});\n\n\t\t// Belt-and-suspenders: a process that exited exactly as the grace timer\n\t\t// fired (so the race resolved instead of rejecting) still surfaces loudly.\n\t\tif (this.process.exitCode !== null) {\n\t\t\tthrow new Error(`Agent process exited immediately with code ${this.process.exitCode}. Stderr: ${this.stderr}`);\n\t\t}\n\t}\n\n\t/**\n\t * Stop the RPC agent process.\n\t */\n\tasync stop(): Promise<void> {\n\t\tif (!this.process) return;\n\n\t\tthis.stopReadingStdout?.();\n\t\tthis.stopReadingStdout = null;\n\t\tthis.process.kill(\"SIGTERM\");\n\n\t\t// Wait for process to exit\n\t\tawait new Promise<void>((resolve) => {\n\t\t\tconst timeout = setTimeout(() => {\n\t\t\t\tthis.process?.kill(\"SIGKILL\");\n\t\t\t\tresolve();\n\t\t\t}, 1000);\n\n\t\t\tthis.process?.on(\"exit\", () => {\n\t\t\t\tclearTimeout(timeout);\n\t\t\t\tresolve();\n\t\t\t});\n\t\t});\n\n\t\tthis.process = null;\n\t\tthis._dead = true;\n\t\tthis.pendingRequests.clear();\n\t}\n\n\t/**\n\t * Subscribe to agent events.\n\t */\n\tonEvent(listener: RpcEventListener): () => void {\n\t\tthis.eventListeners.push(listener);\n\t\treturn () => {\n\t\t\tconst index = this.eventListeners.indexOf(listener);\n\t\t\tif (index !== -1) {\n\t\t\t\tthis.eventListeners.splice(index, 1);\n\t\t\t}\n\t\t};\n\t}\n\n\t/**\n\t * Subscribe to child process death/spawn-failure notifications.\n\t */\n\tonExit(listener: RpcExitListener): () => void {\n\t\tthis.exitListeners.add(listener);\n\t\treturn () => {\n\t\t\tthis.exitListeners.delete(listener);\n\t\t};\n\t}\n\n\t/**\n\t * Get collected stderr output (useful for debugging).\n\t */\n\tgetStderr(): string {\n\t\treturn this.stderr;\n\t}\n\n\t// =========================================================================\n\t// Command Methods\n\t// =========================================================================\n\n\t/**\n\t * Send a prompt to the agent.\n\t * Returns immediately after sending; use onEvent() to receive streaming events.\n\t * Use waitForIdle() to wait for completion.\n\t */\n\tasync prompt(message: string, images?: ImageContent[]): Promise<void> {\n\t\tawait this.send({ type: \"prompt\", message, images });\n\t}\n\n\t/**\n\t * Queue a steering message to interrupt the agent mid-run.\n\t */\n\tasync steer(message: string, images?: ImageContent[]): Promise<void> {\n\t\tawait this.send({ type: \"steer\", message, images });\n\t}\n\n\t/**\n\t * Queue a follow-up message to be processed after the agent finishes.\n\t */\n\tasync followUp(message: string, images?: ImageContent[]): Promise<void> {\n\t\tawait this.send({ type: \"follow_up\", message, images });\n\t}\n\n\t/** Queue an unchanged steering message in a specific live background agent. */\n\tasync steerBackgroundAgent(agentId: string, message: string): Promise<void> {\n\t\tconst response = await this.send({ type: \"steer_background_agent\", agentId, message });\n\t\tthis.getData(response);\n\t}\n\n\t/** Read the selected live background agent's pending steering queue. */\n\tasync getBackgroundAgentPending(agentId: string): Promise<{\n\t\tsteeringMode: \"all\" | \"one-at-a-time\";\n\t\tpending: RpcPendingMessages;\n\t}> {\n\t\tconst response = await this.send({ type: \"get_background_agent_pending\", agentId });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Abort current operation.\n\t */\n\tasync abort(): Promise<void> {\n\t\tawait this.send({ type: \"abort\" });\n\t}\n\n\t/**\n\t * Start a new session, optionally with parent tracking.\n\t * @param parentSession - Optional parent session path for lineage tracking\n\t * @returns Object with `cancelled: true` if an extension cancelled the new session\n\t */\n\tasync newSession(parentSession?: string): Promise<{ cancelled: boolean }> {\n\t\tconst response = await this.send({ type: \"new_session\", parentSession });\n\t\treturn this.getData(response);\n\t}\n\n\t/** Reload extensions, skills, prompts, themes, and other session resources. */\n\tasync reload(): Promise<void> {\n\t\tawait this.send({ type: \"reload\" });\n\t}\n\n\t/** Run `/dream` or one of its backup-path forms. */\n\tasync dream(args?: string): Promise<{ message: string }> {\n\t\tconst response = await this.send({ type: \"dream\", args });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Get current session state.\n\t */\n\tasync getState(): Promise<RpcSessionState> {\n\t\tconst response = await this.send({ type: \"get_state\" });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Capture a dashboard recovery snapshot. The RPC stream emits a matching\n\t * `dashboard_snapshot_barrier` immediately before this response; consumers\n\t * need that event's EventHub sequence before applying the snapshot.\n\t */\n\tasync getDashboardSnapshot(): Promise<RpcDashboardSnapshot> {\n\t\tconst response = await this.send({ type: \"get_dashboard_snapshot\" });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Get loaded context/resources metadata (paths/names only, no file contents).\n\t */\n\tasync getResources(): Promise<RpcResources> {\n\t\tconst response = await this.send({ type: \"get_resources\" });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Get current git branch for the agent cwd.\n\t */\n\tasync getGitBranch(): Promise<string | null> {\n\t\tconst response = await this.send({ type: \"get_git_branch\" });\n\t\treturn this.getData<{ branch: string | null }>(response).branch;\n\t}\n\n\t/**\n\t * Get cached same-day cost across all sessions, primed by the server on first call.\n\t */\n\tasync getDailyCost(): Promise<number> {\n\t\tconst response = await this.send({ type: \"get_daily_cost\" });\n\t\treturn this.getData<{ cost: number }>(response).cost;\n\t}\n\n\t/**\n\t * Set model by provider and ID.\n\t */\n\tasync setModel(provider: string, modelId: string): Promise<{ provider: string; id: string }> {\n\t\tconst response = await this.send({ type: \"set_model\", provider, modelId });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Cycle to next model.\n\t */\n\tasync cycleModel(): Promise<{\n\t\tmodel: { provider: string; id: string };\n\t\tthinkingLevel: ThinkingLevel;\n\t\tisScoped: boolean;\n\t} | null> {\n\t\tconst response = await this.send({ type: \"cycle_model\" });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Get list of available models.\n\t */\n\tasync getAvailableModels(): Promise<ModelInfo[]> {\n\t\tconst response = await this.send({ type: \"get_available_models\" });\n\t\treturn this.getData<{ models: ModelInfo[] }>(response).models;\n\t}\n\n\t/**\n\t * Resolve a model pattern using the same logic as CLI/TUI.\n\t * Runs server-side so API keys never leave the process.\n\t * Returns null if no match found.\n\t */\n\tasync resolveModel(pattern: string): Promise<{ model: ModelInfo; warning?: string } | null> {\n\t\tconst response = await this.send({ type: \"resolve_model\", pattern });\n\t\treturn this.getData<{ model: ModelInfo; warning?: string } | null>(response);\n\t}\n\n\t/**\n\t * Hatch a new buddy companion. Runs inside the agent process\n\t * so API keys never leave the process boundary.\n\t */\n\tasync buddyHatch(): Promise<import(\"../../core/buddy/buddy-types.js\").BuddyState> {\n\t\tconst response = await this.send({ type: \"buddy_hatch\" });\n\t\treturn this.getData<{ state: import(\"../../core/buddy/buddy-types.js\").BuddyState }>(response).state;\n\t}\n\n\t/**\n\t * Reroll the buddy companion. Runs inside the agent process\n\t * so API keys never leave the process boundary.\n\t */\n\tasync buddyReroll(): Promise<import(\"../../core/buddy/buddy-types.js\").BuddyState> {\n\t\tconst response = await this.send({ type: \"buddy_reroll\" });\n\t\treturn this.getData<{ state: import(\"../../core/buddy/buddy-types.js\").BuddyState }>(response).state;\n\t}\n\n\t/**\n\t * Set thinking level.\n\t */\n\tasync setThinkingLevel(level: ThinkingLevel): Promise<void> {\n\t\tawait this.send({ type: \"set_thinking_level\", level });\n\t}\n\n\t/**\n\t * Cycle thinking level.\n\t */\n\tasync cycleThinkingLevel(): Promise<{ level: ThinkingLevel } | null> {\n\t\tconst response = await this.send({ type: \"cycle_thinking_level\" });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Set steering mode.\n\t */\n\tasync setSteeringMode(mode: \"all\" | \"one-at-a-time\"): Promise<void> {\n\t\tawait this.send({ type: \"set_steering_mode\", mode });\n\t}\n\n\t/**\n\t * Set follow-up mode.\n\t */\n\tasync setFollowUpMode(mode: \"all\" | \"one-at-a-time\"): Promise<void> {\n\t\tawait this.send({ type: \"set_follow_up_mode\", mode });\n\t}\n\n\t/**\n\t * Get pending steering and follow-up messages without clearing them.\n\t */\n\tasync getPendingMessages(): Promise<RpcPendingMessages> {\n\t\tconst response = await this.send({ type: \"get_pending_messages\" });\n\t\treturn this.getData<RpcPendingMessages>(response);\n\t}\n\n\t/**\n\t * Clear pending steering and follow-up messages, returning the cleared text.\n\t */\n\tasync clearPendingMessages(): Promise<RpcPendingMessages> {\n\t\tconst response = await this.send({ type: \"clear_pending_messages\" });\n\t\treturn this.getData<RpcPendingMessages>(response);\n\t}\n\n\t/**\n\t * Compact session context.\n\t */\n\tasync compact(customInstructions?: string): Promise<CompactionResult> {\n\t\tconst response = await this.send({ type: \"compact\", customInstructions });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Set auto-compaction enabled/disabled.\n\t */\n\tasync setAutoCompaction(enabled: boolean): Promise<void> {\n\t\tawait this.send({ type: \"set_auto_compaction\", enabled });\n\t}\n\n\t/**\n\t * Abort in-progress compaction.\n\t */\n\tasync abortCompaction(): Promise<void> {\n\t\tawait this.send({ type: \"abort_compaction\" });\n\t}\n\n\t/**\n\t * Set auto-retry enabled/disabled.\n\t */\n\tasync setAutoRetry(enabled: boolean): Promise<void> {\n\t\tawait this.send({ type: \"set_auto_retry\", enabled });\n\t}\n\n\t/**\n\t * Abort in-progress retry.\n\t */\n\tasync abortRetry(): Promise<void> {\n\t\tawait this.send({ type: \"abort_retry\" });\n\t}\n\n\t/**\n\t * Execute a bash command.\n\t */\n\tasync bash(command: string): Promise<BashResult> {\n\t\tconst response = await this.send({ type: \"bash\", command });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Abort running bash command.\n\t */\n\tasync abortBash(): Promise<void> {\n\t\tawait this.send({ type: \"abort_bash\" });\n\t}\n\n\t/**\n\t * Get session statistics.\n\t */\n\tasync getSessionStats(): Promise<SessionStats> {\n\t\tconst response = await this.send({ type: \"get_session_stats\" });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Get performance statistics.\n\t */\n\tasync getPerformanceStats(): Promise<RpcPerformanceStats> {\n\t\tconst response = await this.send({ type: \"get_performance_stats\" });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Export session to HTML.\n\t */\n\tasync exportHtml(outputPath?: string): Promise<{ path: string }> {\n\t\tconst response = await this.send({ type: \"export_html\", outputPath });\n\t\treturn this.getData(response);\n\t}\n\n\t/** Import a JSONL file into the current runtime. */\n\tasync importJsonl(inputPath: string): Promise<{ cancelled: boolean }> {\n\t\tconst response = await this.send({ type: \"import_jsonl\", inputPath });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Switch to a different session file.\n\t * @returns Object with `cancelled: true` if an extension cancelled the switch\n\t */\n\tasync switchSession(sessionPath: string): Promise<{ cancelled: boolean }> {\n\t\tconst response = await this.send({ type: \"switch_session\", sessionPath });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Delete a session file, trying trash first and falling back to unlink.\n\t * Throws on failure, including when attempting to delete the active session.\n\t */\n\tasync deleteSession(sessionPath: string): Promise<{ method: \"trash\" | \"unlink\" }> {\n\t\tconst response = await this.send({ type: \"delete_session\", sessionPath });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Fork from a specific message.\n\t * @returns Object with `text` (the message text) and `cancelled` (if extension cancelled)\n\t */\n\tasync fork(entryId: string): Promise<{ text: string; cancelled: boolean }> {\n\t\tconst response = await this.send({ type: \"fork\", entryId });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Get messages available for forking.\n\t */\n\tasync getForkMessages(): Promise<Array<{ entryId: string; text: string; role: \"user\" | \"assistant\" }>> {\n\t\tconst response = await this.send({ type: \"get_fork_messages\" });\n\t\treturn this.getData<{ messages: Array<{ entryId: string; text: string; role: \"user\" | \"assistant\" }> }>(response)\n\t\t\t.messages;\n\t}\n\n\t/**\n\t * Get the session tree and current leaf.\n\t */\n\tasync getTree(): Promise<{ roots: RpcTreeNode[]; leafId: string | null }> {\n\t\tconst response = await this.send({ type: \"get_tree\" });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Navigate to a session tree entry.\n\t * @param targetId Entry ID to navigate to\n\t * @param options Navigation options; timeoutMs is client-side only and is not sent over RPC\n\t * @returns Object with `cancelled: true` if navigation was cancelled, and `editorText` when re-editing a message\n\t */\n\tasync navigateTree(\n\t\ttargetId: string,\n\t\toptions?: {\n\t\t\tsummarize?: boolean;\n\t\t\tcustomInstructions?: string;\n\t\t\treplaceInstructions?: boolean;\n\t\t\tlabel?: string;\n\t\t\ttimeoutMs?: number;\n\t\t},\n\t): Promise<{ cancelled: boolean; editorText?: string }> {\n\t\tconst { timeoutMs = 300000, ...commandOptions } = options ?? {};\n\t\tconst response = await this.send({ type: \"navigate_tree\", targetId, ...commandOptions }, timeoutMs);\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Get text of last assistant message.\n\t */\n\tasync getLastAssistantText(): Promise<string | null> {\n\t\tconst response = await this.send({ type: \"get_last_assistant_text\" });\n\t\treturn this.getData<{ text: string | null }>(response).text;\n\t}\n\n\t/**\n\t * Set the session display name.\n\t */\n\tasync setSessionName(name: string): Promise<void> {\n\t\tawait this.send({ type: \"set_session_name\", name });\n\t}\n\n\t/**\n\t * Get all messages in the session.\n\t */\n\tasync getMessages(): Promise<AgentMessage[]> {\n\t\tconst response = await this.send({ type: \"get_messages\" });\n\t\treturn this.getData<{ messages: AgentMessage[] }>(response).messages;\n\t}\n\n\t/**\n\t * Get discoverable commands, including built-ins that require client-side handling.\n\t */\n\tasync getCommands(): Promise<RpcSlashCommand[]> {\n\t\tconst response = await this.send({ type: \"get_commands\" });\n\t\treturn this.getData<{ commands: RpcSlashCommand[] }>(response).commands;\n\t}\n\n\t/**\n\t * List sessions for the current working directory.\n\t * Returns sessions sorted by most recently modified first.\n\t */\n\tasync listSessions(): Promise<RpcSessionInfo[]> {\n\t\tconst response = await this.send({ type: \"list_sessions\" });\n\t\treturn this.getData<{ sessions: RpcSessionInfo[] }>(response).sessions;\n\t}\n\n\t/**\n\t * List sessions across all projects.\n\t * Returns sessions sorted by most recently modified first. May be slow with many sessions.\n\t */\n\tasync listAllSessions(): Promise<RpcSessionInfo[]> {\n\t\tconst response = await this.send({ type: \"list_all_sessions\" });\n\t\treturn this.getData<{ sessions: RpcSessionInfo[] }>(response).sessions;\n\t}\n\n\t/**\n\t * List background subagents tracked by the server's registry (running and\n\t * recently completed), including session dir/file paths where known.\n\t */\n\tasync listBackgroundAgents(): Promise<RpcBackgroundAgentInfo[]> {\n\t\tconst response = await this.send({ type: \"list_background_agents\" });\n\t\treturn this.getData<{ agents: RpcBackgroundAgentInfo[] }>(response).agents;\n\t}\n\n\t/**\n\t * List discoverable subagent types for the server's current working directory.\n\t */\n\tasync listAgentTypes(): Promise<RpcAgentTypeInfo[]> {\n\t\tconst response = await this.send({ type: \"list_agent_types\" });\n\t\treturn this.getData<{ agentTypes: RpcAgentTypeInfo[] }>(response).agentTypes;\n\t}\n\n\t/**\n\t * Answer an extension UI request (select/confirm/input/editor) previously\n\t * received as an `extension_ui_request` event. Fire-and-forget: the server\n\t * does not send a response to this message.\n\t */\n\tsendExtensionUIResponse(response: RpcExtensionUIResponse): void {\n\t\tif (this._dead || !this.process?.stdin) {\n\t\t\tconst cause = this.spawnError ? ` Spawn error: ${this.spawnError.message}.` : \"\";\n\t\t\tthrow new Error(`RPC process is not running.${cause} Stderr: ${this.stderr}`);\n\t\t}\n\t\tthis.process.stdin.write(serializeJsonLine(response));\n\t}\n\n\t/**\n\t * Get the dreb version.\n\t */\n\tasync getVersion(): Promise<string> {\n\t\tconst response = await this.send({ type: \"get_version\" });\n\t\treturn this.getData<{ version: string }>(response).version;\n\t}\n\n\t/**\n\t * Get the persistent default settings (SettingsManager-backed).\n\t * These seed fresh runtimes — for live session state use getState().\n\t */\n\tasync getSettings(): Promise<RpcSettingsSnapshot> {\n\t\tconst response = await this.send({ type: \"get_settings\" });\n\t\treturn this.getData<RpcSettingsSnapshot>(response);\n\t}\n\n\t/**\n\t * Update persistent default settings. Validates the whole payload before applying\n\t * anything (atomic: on any invalid field, nothing changes). Does NOT touch live\n\t * session state — use setModel/setThinkingLevel/etc. for that.\n\t * Returns the full settings snapshot after the write, plus any loud warnings\n\t * (for example project-level agent model overrides shadowing global writes).\n\t */\n\tasync setSettings(settings: RpcSettingsUpdate): Promise<RpcSettingsSetResult> {\n\t\tconst response = await this.send({ type: \"set_settings\", settings });\n\t\treturn this.getData<RpcSettingsSetResult>(response);\n\t}\n\n\t/** Evaluate an existing directory against the server's global context-trust policy. */\n\tasync evaluateContextTrust(path: string): Promise<RpcContextTrustEvaluation> {\n\t\tconst response = await this.send({ type: \"evaluate_context_trust\", path });\n\t\treturn this.getData<RpcContextTrustEvaluation>(response);\n\t}\n\n\t/** Add an existing directory as a canonical global trusted context root. */\n\tasync trustContextFolder(path: string): Promise<RpcContextTrustMutationResult> {\n\t\tconst response = await this.send({ type: \"trust_context_folder\", path });\n\t\treturn this.getData<RpcContextTrustMutationResult>(response);\n\t}\n\n\t/** Remove the root that currently grants the directory context trust. */\n\tasync untrustContextFolder(path: string): Promise<RpcContextTrustMutationResult> {\n\t\tconst response = await this.send({ type: \"untrust_context_folder\", path });\n\t\treturn this.getData<RpcContextTrustMutationResult>(response);\n\t}\n\n\t/** Remove a configured trusted-folder string exactly as stored. */\n\tasync removeTrustedContextFolder(path: string): Promise<RpcTrustedFolderRemovalResult> {\n\t\tconst response = await this.send({ type: \"remove_trusted_context_folder\", path });\n\t\treturn this.getData<RpcTrustedFolderRemovalResult>(response);\n\t}\n\n\t// =========================================================================\n\t// Helpers\n\t// =========================================================================\n\n\t/**\n\t * Wait for agent to become idle (no streaming).\n\t * Resolves when agent_end event is received.\n\t */\n\twaitForIdle(timeout = 60000): Promise<void> {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tunsubscribe();\n\t\t\t\treject(new Error(`Timeout waiting for agent to become idle. Stderr: ${this.stderr}`));\n\t\t\t}, timeout);\n\n\t\t\tconst unsubscribe = this.onEvent((event) => {\n\t\t\t\tif (event.type === \"agent_end\") {\n\t\t\t\t\tclearTimeout(timer);\n\t\t\t\t\tunsubscribe();\n\t\t\t\t\tresolve();\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t}\n\n\t/**\n\t * Collect events until agent becomes idle.\n\t */\n\tcollectEvents(timeout = 60000): Promise<RpcEvent[]> {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst events: RpcEvent[] = [];\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tunsubscribe();\n\t\t\t\treject(new Error(`Timeout collecting events. Stderr: ${this.stderr}`));\n\t\t\t}, timeout);\n\n\t\t\tconst unsubscribe = this.onEvent((event) => {\n\t\t\t\tevents.push(event);\n\t\t\t\tif (event.type === \"agent_end\") {\n\t\t\t\t\tclearTimeout(timer);\n\t\t\t\t\tunsubscribe();\n\t\t\t\t\tresolve(events);\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t}\n\n\t/**\n\t * Send prompt and wait for completion, returning all events.\n\t */\n\tasync promptAndWait(message: string, images?: ImageContent[], timeout = 60000): Promise<RpcEvent[]> {\n\t\tconst eventsPromise = this.collectEvents(timeout);\n\t\tawait this.prompt(message, images);\n\t\treturn eventsPromise;\n\t}\n\n\t// =========================================================================\n\t// Internal\n\t// =========================================================================\n\n\t/**\n\t * Mark the client dead and reject every in-flight request with `message`.\n\t * Shared by the 'exit' and 'error' handlers so both failure paths surface\n\t * loudly and consistently instead of leaving callers hanging.\n\t */\n\tprivate failPendingRequests(message: string): void {\n\t\tthis._dead = true;\n\t\tfor (const pending of this.pendingRequests.values()) {\n\t\t\tpending.reject(new Error(message));\n\t\t}\n\t\tthis.pendingRequests.clear();\n\t}\n\n\tprivate notifyExitListeners(info: RpcExitInfo): void {\n\t\tfor (const listener of this.exitListeners) {\n\t\t\tlistener(info);\n\t\t}\n\t}\n\n\tprivate handleLine(line: string): void {\n\t\ttry {\n\t\t\tconst data: unknown = JSON.parse(line);\n\n\t\t\t// Check if it's a response to a pending request. Unknown/unsolicited\n\t\t\t// response frames are not events and should not be forwarded to listeners.\n\t\t\tif (isRpcResponseMessage(data)) {\n\t\t\t\tif (typeof data.id === \"string\" && this.pendingRequests.has(data.id)) {\n\t\t\t\t\tconst pending = this.pendingRequests.get(data.id)!;\n\t\t\t\t\tthis.pendingRequests.delete(data.id);\n\t\t\t\t\tpending.resolve(data);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (!isRpcEvent(data)) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tfor (const listener of this.eventListeners) {\n\t\t\t\tlistener(data);\n\t\t\t}\n\t\t} catch {\n\t\t\t// Ignore non-JSON lines\n\t\t}\n\t}\n\n\tprivate async send(command: RpcCommandBody, timeoutMs = 30000): Promise<RpcResponse> {\n\t\tif (this._dead || !this.process?.stdin) {\n\t\t\t// Surface the real spawn cause (e.g. uid/gid EPERM) if one was captured,\n\t\t\t// rather than a generic message that hides why the process is gone.\n\t\t\tthrow new Error(\n\t\t\t\tthis.spawnError ? `RPC process not running: ${this.spawnError.message}` : \"RPC process not running\",\n\t\t\t);\n\t\t}\n\n\t\tconst id = `req_${++this.requestId}`;\n\t\tconst fullCommand = { ...command, id } as RpcCommand;\n\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst timeout = setTimeout(() => {\n\t\t\t\tthis.pendingRequests.delete(id);\n\t\t\t\treject(new Error(`Timeout waiting for response to ${command.type}. Stderr: ${this.stderr}`));\n\t\t\t}, timeoutMs);\n\n\t\t\tthis.pendingRequests.set(id, {\n\t\t\t\tresolve: (response) => {\n\t\t\t\t\tclearTimeout(timeout);\n\t\t\t\t\tresolve(response);\n\t\t\t\t},\n\t\t\t\treject: (error) => {\n\t\t\t\t\tclearTimeout(timeout);\n\t\t\t\t\treject(error);\n\t\t\t\t},\n\t\t\t});\n\n\t\t\tthis.process!.stdin!.write(serializeJsonLine(fullCommand));\n\t\t});\n\t}\n\n\tprivate getData<T>(response: RpcResponse): T {\n\t\tif (!response.success) {\n\t\t\tconst errorResponse = response as Extract<RpcResponse, { success: false }>;\n\t\t\tthrow new Error(errorResponse.error);\n\t\t}\n\t\t// Type assertion: we trust response.data matches T based on the command sent.\n\t\t// This is safe because each public method specifies the correct T for its command.\n\t\tconst successResponse = response as Extract<RpcResponse, { success: true; data: unknown }>;\n\t\treturn successResponse.data as T;\n\t}\n}\n"]}
|
|
@@ -26,4 +26,11 @@
|
|
|
26
26
|
* subscribers (and the session's own state) share the same object.
|
|
27
27
|
*/
|
|
28
28
|
export declare function projectDashboardRpcEvent(event: Record<string, unknown>): Record<string, unknown>;
|
|
29
|
+
/**
|
|
30
|
+
* Create the dashboard-mode RPC event projector for one runRpcMode process.
|
|
31
|
+
*
|
|
32
|
+
* Composes the per-event field projection with process-lifetime image dedupe.
|
|
33
|
+
* Dashboard-mode sessions only — generic RPC consumers keep the full protocol.
|
|
34
|
+
*/
|
|
35
|
+
export declare function createDashboardRpcEventProjector(): (event: Record<string, unknown>) => Record<string, unknown>;
|
|
29
36
|
//# sourceMappingURL=rpc-event-projection.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rpc-event-projection.d.ts","sourceRoot":"","sources":["../../../src/modes/rpc/rpc-event-projection.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAYH;;;;;;;GAOG;AACH,wBAAgB,wBAAwB,CAAC,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAgBhG","sourcesContent":["/**\n * Dashboard-mode RPC event projection.\n *\n * `message_update` events carry two cumulative copies of the growing assistant\n * message: the top-level `message` field and `assistantMessageEvent.partial`.\n * Serializing both for every token makes the child->parent JSONL pipe quadratic\n * in response length and floods the stdout queue (see issue 448).\n *\n * The dashboard never reads those fields: its browser reducer consumes only\n * the delta fields (`delta`, `content`, `toolCall`, `contentIndex`), and its\n * authoritative transcript comes from `message_end` plus `get_dashboard_snapshot`\n * RPC responses. The dashboard's own EventHub already strips the same fields at\n * the browser SSE boundary (projectDashboardEvent); this module applies the same\n * removal one boundary earlier, before JSONL serialization in runRpcMode.\n *\n * Only the quadratic `message_update` fields are removed here. Broader bounding\n * (agent_end messages, tool_execution_update args, retry discardedPartial,\n * images) remains the EventHub's browser-facing concern.\n */\n\nfunction omit(event: Record<string, unknown>, ...keys: string[]): Record<string, unknown> {\n\tconst copy = { ...event };\n\tfor (const key of keys) delete copy[key];\n\treturn copy;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Project a single agent session event for dashboard-mode RPC transport.\n *\n * Unknown event types are returned exactly as received (same reference) so\n * extensions and future event types remain forward-safe. Projected events are\n * shallow copies — the input event is never mutated, because other session\n * subscribers (and the session's own state) share the same object.\n */\nexport function projectDashboardRpcEvent(event: Record<string, unknown>): Record<string, unknown> {\n\tswitch (event.type) {\n\t\tcase \"message_update\": {\n\t\t\tconst projected = omit(event, \"message\");\n\t\t\tconst streamEvent = event.assistantMessageEvent;\n\t\t\treturn isPlainObject(streamEvent)\n\t\t\t\t? { ...projected, assistantMessageEvent: omit(streamEvent, \"partial\") }\n\t\t\t\t: projected;\n\t\t}\n\t\tcase \"background_agent_event\": {\n\t\t\tconst child = event.event;\n\t\t\treturn isPlainObject(child) ? { ...event, event: projectDashboardRpcEvent(child) } : event;\n\t\t}\n\t\tdefault:\n\t\t\treturn event;\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"rpc-event-projection.d.ts","sourceRoot":"","sources":["../../../src/modes/rpc/rpc-event-projection.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAcH;;;;;;;GAOG;AACH,wBAAgB,wBAAwB,CAAC,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAgBhG;AA8JD;;;;;GAKG;AACH,wBAAgB,gCAAgC,IAAI,CAAC,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAM9G","sourcesContent":["/**\n * Dashboard-mode RPC event projection.\n *\n * `message_update` events carry two cumulative copies of the growing assistant\n * message: the top-level `message` field and `assistantMessageEvent.partial`.\n * Serializing both for every token makes the child->parent JSONL pipe quadratic\n * in response length and floods the stdout queue (see issue 448).\n *\n * The dashboard never reads those fields: its browser reducer consumes only\n * the delta fields (`delta`, `content`, `toolCall`, `contentIndex`), and its\n * authoritative transcript comes from `message_end` plus `get_dashboard_snapshot`\n * RPC responses. The dashboard's own EventHub already strips the same fields at\n * the browser SSE boundary (projectDashboardEvent); this module applies the same\n * removal one boundary earlier, before JSONL serialization in runRpcMode.\n *\n * Only the quadratic `message_update` fields are removed here. Broader bounding\n * (agent_end messages, tool_execution_update args, retry discardedPartial,\n * images) remains the EventHub's browser-facing concern.\n */\n\nimport { createHash } from \"node:crypto\";\n\nfunction omit(event: Record<string, unknown>, ...keys: string[]): Record<string, unknown> {\n\tconst copy = { ...event };\n\tfor (const key of keys) delete copy[key];\n\treturn copy;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Project a single agent session event for dashboard-mode RPC transport.\n *\n * Unknown event types are returned exactly as received (same reference) so\n * extensions and future event types remain forward-safe. Projected events are\n * shallow copies — the input event is never mutated, because other session\n * subscribers (and the session's own state) share the same object.\n */\nexport function projectDashboardRpcEvent(event: Record<string, unknown>): Record<string, unknown> {\n\tswitch (event.type) {\n\t\tcase \"message_update\": {\n\t\t\tconst projected = omit(event, \"message\");\n\t\t\tconst streamEvent = event.assistantMessageEvent;\n\t\t\treturn isPlainObject(streamEvent)\n\t\t\t\t? { ...projected, assistantMessageEvent: omit(streamEvent, \"partial\") }\n\t\t\t\t: projected;\n\t\t}\n\t\tcase \"background_agent_event\": {\n\t\t\tconst child = event.event;\n\t\t\treturn isPlainObject(child) ? { ...event, event: projectDashboardRpcEvent(child) } : event;\n\t\t}\n\t\tdefault:\n\t\t\treturn event;\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Image dedupe (dashboard mode)\n//\n// Inline image blocks cross the JSONL pipe multiple times per turn: prompt\n// re-emission (message_start + message_end), each tool result\n// (tool_execution_end + message_start + message_end), and the agent_end\n// transcript. A turn with several multi-MiB images easily fills the child\n// stdout queue while the dashboard is busy decoding, and the stdout guard\n// kills the session (issue 495).\n//\n// The dashboard already treats images content-globally: its server projection\n// replaces every inline image with an image_reference whose id is\n// sha256(mimeType + 0x00 + decodedBytes), caches the binary on first sight,\n// and serves later fetches from that cache (recovering from the authoritative\n// transcript when evicted). This projector applies the same reduction one\n// boundary earlier: each unique image crosses stdout at most once per process\n// lifetime; every later occurrence becomes an image_reference the dashboard\n// resolves from its cache. Live events only — command responses\n// (get_messages, get_dashboard_snapshot) always keep full payloads, because\n// they are the authoritative source the dashboard's image recovery reads.\n// ---------------------------------------------------------------------------\n\nconst DASHBOARD_IMAGE_MIME_TYPES = new Set([\"image/png\", \"image/jpeg\", \"image/gif\", \"image/webp\"]);\n\nconst BASE64_PATTERN = /^[A-Za-z0-9+/]+={0,2}$/;\n\nconst JPEG_EOI = Buffer.from([0xff, 0xd9]);\n\ntype ImageReference = { type: \"image_reference\"; id: string; mimeType: string; size: number };\n\n/**\n * Raster-signature check mirroring the dashboard server's hasRasterSignature\n * (packages/dashboard/src/server/dashboard-images.ts). Keep in sync: the child\n * may only turn a block into a reference when the dashboard's strict decode\n * (decodeDashboardImage) will accept it, or the reference dangles (the cache\n * holds nothing and the authoritative recovery decodes the same bytes and\n * rejects them again).\n */\nfunction hasRasterSignature(mimeType: string, bytes: Uint8Array): boolean {\n\tconst buffer = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n\tswitch (mimeType) {\n\t\tcase \"image/png\": {\n\t\t\tconst signature =\n\t\t\t\tbytes.length >= 24 &&\n\t\t\t\t[0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a].every((byte, i) => bytes[i] === byte);\n\t\t\treturn (\n\t\t\t\tsignature &&\n\t\t\t\tbuffer.subarray(12, 16).toString(\"ascii\") === \"IHDR\" &&\n\t\t\t\tbuffer.readUInt32BE(16) > 0 &&\n\t\t\t\tbuffer.readUInt32BE(20) > 0 &&\n\t\t\t\tbuffer.indexOf(Buffer.from(\"IEND\"), 24) >= 0\n\t\t\t);\n\t\t}\n\t\tcase \"image/jpeg\": {\n\t\t\tif (bytes.length < 4 || bytes[0] !== 0xff || bytes[1] !== 0xd8 || bytes[2] !== 0xff) return false;\n\t\t\t// EOI does not have to be the final byte. Phone JPEGs commonly append\n\t\t\t// auxiliary gain-map, motion-photo, or vendor metadata after the\n\t\t\t// primary image. Browsers and Photon decode the JPEG through EOI and\n\t\t\t// preserve the trailing bytes when the exact original is requested.\n\t\t\treturn buffer.lastIndexOf(JPEG_EOI) >= 2;\n\t\t}\n\t\tcase \"image/gif\": {\n\t\t\tconst header = buffer.subarray(0, 6).toString(\"ascii\");\n\t\t\treturn (\n\t\t\t\tbytes.length >= 14 &&\n\t\t\t\t(header === \"GIF87a\" || header === \"GIF89a\") &&\n\t\t\t\tbuffer.readUInt16LE(6) > 0 &&\n\t\t\t\tbuffer.readUInt16LE(8) > 0 &&\n\t\t\t\tbytes[bytes.length - 1] === 0x3b\n\t\t\t);\n\t\t}\n\t\tcase \"image/webp\": {\n\t\t\tif (\n\t\t\t\tbytes.length < 20 ||\n\t\t\t\tbuffer.subarray(0, 4).toString(\"ascii\") !== \"RIFF\" ||\n\t\t\t\tbuffer.subarray(8, 12).toString(\"ascii\") !== \"WEBP\"\n\t\t\t) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tconst chunk = buffer.subarray(12, 16).toString(\"ascii\");\n\t\t\treturn (\n\t\t\t\tbuffer.readUInt32LE(4) + 8 <= bytes.length && (chunk === \"VP8 \" || chunk === \"VP8L\" || chunk === \"VP8X\")\n\t\t\t);\n\t\t}\n\t}\n\treturn false;\n}\n\n/**\n * Content identity of an inline image block, mirroring the dashboard server's\n * dashboardImageId (sha256 of mimeType + 0x00 + decoded bytes). The gate is as\n * strict as the dashboard's decodeDashboardImage — allowlisted mimeType,\n * canonical base64 (round trip), and a matching raster signature — so a block\n * the dashboard would reject never becomes a reference: it stays inline at\n * every occurrence and is dropped by the dashboard's strict decode, exactly as\n * before this projection existed (no dangling image_references).\n */\nfunction imageBlockIdentity(mimeType: string, data: string): { id: string; size: number } | undefined {\n\tif (!DASHBOARD_IMAGE_MIME_TYPES.has(mimeType)) return undefined;\n\tif (data.length === 0 || data.length % 4 !== 0 || !BASE64_PATTERN.test(data)) return undefined;\n\tconst bytes = Buffer.from(data, \"base64\");\n\tif (bytes.byteLength === 0) return undefined;\n\tif (bytes.toString(\"base64\") !== data) return undefined; // non-canonical encoding the dashboard rejects\n\tif (!hasRasterSignature(mimeType, bytes)) return undefined; // signature mismatch the dashboard rejects\n\tconst id = createHash(\"sha256\").update(mimeType).update(Uint8Array.of(0)).update(bytes).digest(\"hex\");\n\treturn { id, size: bytes.byteLength };\n}\n\n/**\n * Replace occurrences of already-seen image blocks with their stable\n * reference, keeping the first occurrence of each unique image inline.\n * Returns the input by reference when nothing changed, so events without\n * images keep sharing objects with other session subscribers.\n */\nfunction dedupeImages(node: unknown, seen: Map<string, ImageReference>): unknown {\n\tif (Array.isArray(node)) {\n\t\tlet changed = false;\n\t\tconst result: unknown[] = new Array(node.length);\n\t\tfor (let i = 0; i < node.length; i++) {\n\t\t\tconst original = node[i];\n\t\t\tconst next = dedupeImages(original, seen);\n\t\t\tif (next !== original) changed = true;\n\t\t\tresult[i] = next;\n\t\t}\n\t\treturn changed ? result : node;\n\t}\n\tif (isPlainObject(node)) {\n\t\tif (node.type === \"image\" && typeof node.mimeType === \"string\" && typeof node.data === \"string\") {\n\t\t\tconst identity = imageBlockIdentity(node.mimeType, node.data);\n\t\t\tif (identity) {\n\t\t\t\tconst reference = seen.get(identity.id);\n\t\t\t\tif (reference) return reference;\n\t\t\t\tconst created: ImageReference = {\n\t\t\t\t\ttype: \"image_reference\",\n\t\t\t\t\tid: identity.id,\n\t\t\t\t\tmimeType: node.mimeType,\n\t\t\t\t\tsize: identity.size,\n\t\t\t\t};\n\t\t\t\tseen.set(identity.id, created);\n\t\t\t\treturn node;\n\t\t\t}\n\t\t\treturn node;\n\t\t}\n\t\tlet changed = false;\n\t\tconst result: Record<string, unknown> = {};\n\t\tfor (const key of Object.keys(node)) {\n\t\t\tconst original = node[key];\n\t\t\tconst next = dedupeImages(original, seen);\n\t\t\tif (next !== original) changed = true;\n\t\t\tresult[key] = next;\n\t\t}\n\t\treturn changed ? result : node;\n\t}\n\treturn node;\n}\n\n/**\n * Create the dashboard-mode RPC event projector for one runRpcMode process.\n *\n * Composes the per-event field projection with process-lifetime image dedupe.\n * Dashboard-mode sessions only — generic RPC consumers keep the full protocol.\n */\nexport function createDashboardRpcEventProjector(): (event: Record<string, unknown>) => Record<string, unknown> {\n\tconst seenImageIds = new Map<string, ImageReference>();\n\treturn (event: Record<string, unknown>): Record<string, unknown> => {\n\t\tconst projected = projectDashboardRpcEvent(event);\n\t\treturn dedupeImages(projected, seenImageIds) as Record<string, unknown>;\n\t};\n}\n"]}
|
|
@@ -17,6 +17,7 @@
|
|
|
17
17
|
* (agent_end messages, tool_execution_update args, retry discardedPartial,
|
|
18
18
|
* images) remains the EventHub's browser-facing concern.
|
|
19
19
|
*/
|
|
20
|
+
import { createHash } from "node:crypto";
|
|
20
21
|
function omit(event, ...keys) {
|
|
21
22
|
const copy = { ...event };
|
|
22
23
|
for (const key of keys)
|
|
@@ -51,4 +52,164 @@ export function projectDashboardRpcEvent(event) {
|
|
|
51
52
|
return event;
|
|
52
53
|
}
|
|
53
54
|
}
|
|
55
|
+
// ---------------------------------------------------------------------------
|
|
56
|
+
// Image dedupe (dashboard mode)
|
|
57
|
+
//
|
|
58
|
+
// Inline image blocks cross the JSONL pipe multiple times per turn: prompt
|
|
59
|
+
// re-emission (message_start + message_end), each tool result
|
|
60
|
+
// (tool_execution_end + message_start + message_end), and the agent_end
|
|
61
|
+
// transcript. A turn with several multi-MiB images easily fills the child
|
|
62
|
+
// stdout queue while the dashboard is busy decoding, and the stdout guard
|
|
63
|
+
// kills the session (issue 495).
|
|
64
|
+
//
|
|
65
|
+
// The dashboard already treats images content-globally: its server projection
|
|
66
|
+
// replaces every inline image with an image_reference whose id is
|
|
67
|
+
// sha256(mimeType + 0x00 + decodedBytes), caches the binary on first sight,
|
|
68
|
+
// and serves later fetches from that cache (recovering from the authoritative
|
|
69
|
+
// transcript when evicted). This projector applies the same reduction one
|
|
70
|
+
// boundary earlier: each unique image crosses stdout at most once per process
|
|
71
|
+
// lifetime; every later occurrence becomes an image_reference the dashboard
|
|
72
|
+
// resolves from its cache. Live events only — command responses
|
|
73
|
+
// (get_messages, get_dashboard_snapshot) always keep full payloads, because
|
|
74
|
+
// they are the authoritative source the dashboard's image recovery reads.
|
|
75
|
+
// ---------------------------------------------------------------------------
|
|
76
|
+
const DASHBOARD_IMAGE_MIME_TYPES = new Set(["image/png", "image/jpeg", "image/gif", "image/webp"]);
|
|
77
|
+
const BASE64_PATTERN = /^[A-Za-z0-9+/]+={0,2}$/;
|
|
78
|
+
const JPEG_EOI = Buffer.from([0xff, 0xd9]);
|
|
79
|
+
/**
|
|
80
|
+
* Raster-signature check mirroring the dashboard server's hasRasterSignature
|
|
81
|
+
* (packages/dashboard/src/server/dashboard-images.ts). Keep in sync: the child
|
|
82
|
+
* may only turn a block into a reference when the dashboard's strict decode
|
|
83
|
+
* (decodeDashboardImage) will accept it, or the reference dangles (the cache
|
|
84
|
+
* holds nothing and the authoritative recovery decodes the same bytes and
|
|
85
|
+
* rejects them again).
|
|
86
|
+
*/
|
|
87
|
+
function hasRasterSignature(mimeType, bytes) {
|
|
88
|
+
const buffer = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
89
|
+
switch (mimeType) {
|
|
90
|
+
case "image/png": {
|
|
91
|
+
const signature = bytes.length >= 24 &&
|
|
92
|
+
[0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a].every((byte, i) => bytes[i] === byte);
|
|
93
|
+
return (signature &&
|
|
94
|
+
buffer.subarray(12, 16).toString("ascii") === "IHDR" &&
|
|
95
|
+
buffer.readUInt32BE(16) > 0 &&
|
|
96
|
+
buffer.readUInt32BE(20) > 0 &&
|
|
97
|
+
buffer.indexOf(Buffer.from("IEND"), 24) >= 0);
|
|
98
|
+
}
|
|
99
|
+
case "image/jpeg": {
|
|
100
|
+
if (bytes.length < 4 || bytes[0] !== 0xff || bytes[1] !== 0xd8 || bytes[2] !== 0xff)
|
|
101
|
+
return false;
|
|
102
|
+
// EOI does not have to be the final byte. Phone JPEGs commonly append
|
|
103
|
+
// auxiliary gain-map, motion-photo, or vendor metadata after the
|
|
104
|
+
// primary image. Browsers and Photon decode the JPEG through EOI and
|
|
105
|
+
// preserve the trailing bytes when the exact original is requested.
|
|
106
|
+
return buffer.lastIndexOf(JPEG_EOI) >= 2;
|
|
107
|
+
}
|
|
108
|
+
case "image/gif": {
|
|
109
|
+
const header = buffer.subarray(0, 6).toString("ascii");
|
|
110
|
+
return (bytes.length >= 14 &&
|
|
111
|
+
(header === "GIF87a" || header === "GIF89a") &&
|
|
112
|
+
buffer.readUInt16LE(6) > 0 &&
|
|
113
|
+
buffer.readUInt16LE(8) > 0 &&
|
|
114
|
+
bytes[bytes.length - 1] === 0x3b);
|
|
115
|
+
}
|
|
116
|
+
case "image/webp": {
|
|
117
|
+
if (bytes.length < 20 ||
|
|
118
|
+
buffer.subarray(0, 4).toString("ascii") !== "RIFF" ||
|
|
119
|
+
buffer.subarray(8, 12).toString("ascii") !== "WEBP") {
|
|
120
|
+
return false;
|
|
121
|
+
}
|
|
122
|
+
const chunk = buffer.subarray(12, 16).toString("ascii");
|
|
123
|
+
return (buffer.readUInt32LE(4) + 8 <= bytes.length && (chunk === "VP8 " || chunk === "VP8L" || chunk === "VP8X"));
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
return false;
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Content identity of an inline image block, mirroring the dashboard server's
|
|
130
|
+
* dashboardImageId (sha256 of mimeType + 0x00 + decoded bytes). The gate is as
|
|
131
|
+
* strict as the dashboard's decodeDashboardImage — allowlisted mimeType,
|
|
132
|
+
* canonical base64 (round trip), and a matching raster signature — so a block
|
|
133
|
+
* the dashboard would reject never becomes a reference: it stays inline at
|
|
134
|
+
* every occurrence and is dropped by the dashboard's strict decode, exactly as
|
|
135
|
+
* before this projection existed (no dangling image_references).
|
|
136
|
+
*/
|
|
137
|
+
function imageBlockIdentity(mimeType, data) {
|
|
138
|
+
if (!DASHBOARD_IMAGE_MIME_TYPES.has(mimeType))
|
|
139
|
+
return undefined;
|
|
140
|
+
if (data.length === 0 || data.length % 4 !== 0 || !BASE64_PATTERN.test(data))
|
|
141
|
+
return undefined;
|
|
142
|
+
const bytes = Buffer.from(data, "base64");
|
|
143
|
+
if (bytes.byteLength === 0)
|
|
144
|
+
return undefined;
|
|
145
|
+
if (bytes.toString("base64") !== data)
|
|
146
|
+
return undefined; // non-canonical encoding the dashboard rejects
|
|
147
|
+
if (!hasRasterSignature(mimeType, bytes))
|
|
148
|
+
return undefined; // signature mismatch the dashboard rejects
|
|
149
|
+
const id = createHash("sha256").update(mimeType).update(Uint8Array.of(0)).update(bytes).digest("hex");
|
|
150
|
+
return { id, size: bytes.byteLength };
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* Replace occurrences of already-seen image blocks with their stable
|
|
154
|
+
* reference, keeping the first occurrence of each unique image inline.
|
|
155
|
+
* Returns the input by reference when nothing changed, so events without
|
|
156
|
+
* images keep sharing objects with other session subscribers.
|
|
157
|
+
*/
|
|
158
|
+
function dedupeImages(node, seen) {
|
|
159
|
+
if (Array.isArray(node)) {
|
|
160
|
+
let changed = false;
|
|
161
|
+
const result = new Array(node.length);
|
|
162
|
+
for (let i = 0; i < node.length; i++) {
|
|
163
|
+
const original = node[i];
|
|
164
|
+
const next = dedupeImages(original, seen);
|
|
165
|
+
if (next !== original)
|
|
166
|
+
changed = true;
|
|
167
|
+
result[i] = next;
|
|
168
|
+
}
|
|
169
|
+
return changed ? result : node;
|
|
170
|
+
}
|
|
171
|
+
if (isPlainObject(node)) {
|
|
172
|
+
if (node.type === "image" && typeof node.mimeType === "string" && typeof node.data === "string") {
|
|
173
|
+
const identity = imageBlockIdentity(node.mimeType, node.data);
|
|
174
|
+
if (identity) {
|
|
175
|
+
const reference = seen.get(identity.id);
|
|
176
|
+
if (reference)
|
|
177
|
+
return reference;
|
|
178
|
+
const created = {
|
|
179
|
+
type: "image_reference",
|
|
180
|
+
id: identity.id,
|
|
181
|
+
mimeType: node.mimeType,
|
|
182
|
+
size: identity.size,
|
|
183
|
+
};
|
|
184
|
+
seen.set(identity.id, created);
|
|
185
|
+
return node;
|
|
186
|
+
}
|
|
187
|
+
return node;
|
|
188
|
+
}
|
|
189
|
+
let changed = false;
|
|
190
|
+
const result = {};
|
|
191
|
+
for (const key of Object.keys(node)) {
|
|
192
|
+
const original = node[key];
|
|
193
|
+
const next = dedupeImages(original, seen);
|
|
194
|
+
if (next !== original)
|
|
195
|
+
changed = true;
|
|
196
|
+
result[key] = next;
|
|
197
|
+
}
|
|
198
|
+
return changed ? result : node;
|
|
199
|
+
}
|
|
200
|
+
return node;
|
|
201
|
+
}
|
|
202
|
+
/**
|
|
203
|
+
* Create the dashboard-mode RPC event projector for one runRpcMode process.
|
|
204
|
+
*
|
|
205
|
+
* Composes the per-event field projection with process-lifetime image dedupe.
|
|
206
|
+
* Dashboard-mode sessions only — generic RPC consumers keep the full protocol.
|
|
207
|
+
*/
|
|
208
|
+
export function createDashboardRpcEventProjector() {
|
|
209
|
+
const seenImageIds = new Map();
|
|
210
|
+
return (event) => {
|
|
211
|
+
const projected = projectDashboardRpcEvent(event);
|
|
212
|
+
return dedupeImages(projected, seenImageIds);
|
|
213
|
+
};
|
|
214
|
+
}
|
|
54
215
|
//# sourceMappingURL=rpc-event-projection.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rpc-event-projection.js","sourceRoot":"","sources":["../../../src/modes/rpc/rpc-event-projection.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,SAAS,IAAI,CAAC,KAA8B,EAAE,GAAG,IAAc,EAA2B;IACzF,MAAM,IAAI,GAAG,EAAE,GAAG,KAAK,EAAE,CAAC;IAC1B,KAAK,MAAM,GAAG,IAAI,IAAI;QAAE,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC;IACzC,OAAO,IAAI,CAAC;AAAA,CACZ;AAED,SAAS,aAAa,CAAC,KAAc,EAAoC;IACxE,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAAA,CAC5E;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,wBAAwB,CAAC,KAA8B,EAA2B;IACjG,QAAQ,KAAK,CAAC,IAAI,EAAE,CAAC;QACpB,KAAK,gBAAgB,EAAE,CAAC;YACvB,MAAM,SAAS,GAAG,IAAI,CAAC,KAAK,EAAE,SAAS,CAAC,CAAC;YACzC,MAAM,WAAW,GAAG,KAAK,CAAC,qBAAqB,CAAC;YAChD,OAAO,aAAa,CAAC,WAAW,CAAC;gBAChC,CAAC,CAAC,EAAE,GAAG,SAAS,EAAE,qBAAqB,EAAE,IAAI,CAAC,WAAW,EAAE,SAAS,CAAC,EAAE;gBACvE,CAAC,CAAC,SAAS,CAAC;QACd,CAAC;QACD,KAAK,wBAAwB,EAAE,CAAC;YAC/B,MAAM,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC;YAC1B,OAAO,aAAa,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,GAAG,KAAK,EAAE,KAAK,EAAE,wBAAwB,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC;QAC5F,CAAC;QACD;YACC,OAAO,KAAK,CAAC;IACf,CAAC;AAAA,CACD","sourcesContent":["/**\n * Dashboard-mode RPC event projection.\n *\n * `message_update` events carry two cumulative copies of the growing assistant\n * message: the top-level `message` field and `assistantMessageEvent.partial`.\n * Serializing both for every token makes the child->parent JSONL pipe quadratic\n * in response length and floods the stdout queue (see issue 448).\n *\n * The dashboard never reads those fields: its browser reducer consumes only\n * the delta fields (`delta`, `content`, `toolCall`, `contentIndex`), and its\n * authoritative transcript comes from `message_end` plus `get_dashboard_snapshot`\n * RPC responses. The dashboard's own EventHub already strips the same fields at\n * the browser SSE boundary (projectDashboardEvent); this module applies the same\n * removal one boundary earlier, before JSONL serialization in runRpcMode.\n *\n * Only the quadratic `message_update` fields are removed here. Broader bounding\n * (agent_end messages, tool_execution_update args, retry discardedPartial,\n * images) remains the EventHub's browser-facing concern.\n */\n\nfunction omit(event: Record<string, unknown>, ...keys: string[]): Record<string, unknown> {\n\tconst copy = { ...event };\n\tfor (const key of keys) delete copy[key];\n\treturn copy;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Project a single agent session event for dashboard-mode RPC transport.\n *\n * Unknown event types are returned exactly as received (same reference) so\n * extensions and future event types remain forward-safe. Projected events are\n * shallow copies — the input event is never mutated, because other session\n * subscribers (and the session's own state) share the same object.\n */\nexport function projectDashboardRpcEvent(event: Record<string, unknown>): Record<string, unknown> {\n\tswitch (event.type) {\n\t\tcase \"message_update\": {\n\t\t\tconst projected = omit(event, \"message\");\n\t\t\tconst streamEvent = event.assistantMessageEvent;\n\t\t\treturn isPlainObject(streamEvent)\n\t\t\t\t? { ...projected, assistantMessageEvent: omit(streamEvent, \"partial\") }\n\t\t\t\t: projected;\n\t\t}\n\t\tcase \"background_agent_event\": {\n\t\t\tconst child = event.event;\n\t\t\treturn isPlainObject(child) ? { ...event, event: projectDashboardRpcEvent(child) } : event;\n\t\t}\n\t\tdefault:\n\t\t\treturn event;\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"rpc-event-projection.js","sourceRoot":"","sources":["../../../src/modes/rpc/rpc-event-projection.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC,SAAS,IAAI,CAAC,KAA8B,EAAE,GAAG,IAAc,EAA2B;IACzF,MAAM,IAAI,GAAG,EAAE,GAAG,KAAK,EAAE,CAAC;IAC1B,KAAK,MAAM,GAAG,IAAI,IAAI;QAAE,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC;IACzC,OAAO,IAAI,CAAC;AAA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IAAI,CAAC;YACb,CAAC;YACD,OAAO,IAAI,CAAC;QACb,CAAC;QACD,IAAI,OAAO,GAAG,KAAK,CAAC;QACpB,MAAM,MAAM,GAA4B,EAAE,CAAC;QAC3C,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;YACrC,MAAM,QAAQ,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC;YAC3B,MAAM,IAAI,GAAG,YAAY,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC;YAC1C,IAAI,IAAI,KAAK,QAAQ;gBAAE,OAAO,GAAG,IAAI,CAAC;YACtC,MAAM,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC;QACpB,CAAC;QACD,OAAO,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC;IAChC,CAAC;IACD,OAAO,IAAI,CAAC;AAAA,CACZ;AAED;;;;;GAKG;AACH,MAAM,UAAU,gCAAgC,GAAgE;IAC/G,MAAM,YAAY,GAAG,IAAI,GAAG,EAA0B,CAAC;IACvD,OAAO,CAAC,KAA8B,EAA2B,EAAE,CAAC;QACnE,MAAM,SAAS,GAAG,wBAAwB,CAAC,KAAK,CAAC,CAAC;QAClD,OAAO,YAAY,CAAC,SAAS,EAAE,YAAY,CAA4B,CAAC;IAAA,CACxE,CAAC;AAAA,CACF","sourcesContent":["/**\n * Dashboard-mode RPC event projection.\n *\n * `message_update` events carry two cumulative copies of the growing assistant\n * message: the top-level `message` field and `assistantMessageEvent.partial`.\n * Serializing both for every token makes the child->parent JSONL pipe quadratic\n * in response length and floods the stdout queue (see issue 448).\n *\n * The dashboard never reads those fields: its browser reducer consumes only\n * the delta fields (`delta`, `content`, `toolCall`, `contentIndex`), and its\n * authoritative transcript comes from `message_end` plus `get_dashboard_snapshot`\n * RPC responses. The dashboard's own EventHub already strips the same fields at\n * the browser SSE boundary (projectDashboardEvent); this module applies the same\n * removal one boundary earlier, before JSONL serialization in runRpcMode.\n *\n * Only the quadratic `message_update` fields are removed here. Broader bounding\n * (agent_end messages, tool_execution_update args, retry discardedPartial,\n * images) remains the EventHub's browser-facing concern.\n */\n\nimport { createHash } from \"node:crypto\";\n\nfunction omit(event: Record<string, unknown>, ...keys: string[]): Record<string, unknown> {\n\tconst copy = { ...event };\n\tfor (const key of keys) delete copy[key];\n\treturn copy;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Project a single agent session event for dashboard-mode RPC transport.\n *\n * Unknown event types are returned exactly as received (same reference) so\n * extensions and future event types remain forward-safe. Projected events are\n * shallow copies — the input event is never mutated, because other session\n * subscribers (and the session's own state) share the same object.\n */\nexport function projectDashboardRpcEvent(event: Record<string, unknown>): Record<string, unknown> {\n\tswitch (event.type) {\n\t\tcase \"message_update\": {\n\t\t\tconst projected = omit(event, \"message\");\n\t\t\tconst streamEvent = event.assistantMessageEvent;\n\t\t\treturn isPlainObject(streamEvent)\n\t\t\t\t? { ...projected, assistantMessageEvent: omit(streamEvent, \"partial\") }\n\t\t\t\t: projected;\n\t\t}\n\t\tcase \"background_agent_event\": {\n\t\t\tconst child = event.event;\n\t\t\treturn isPlainObject(child) ? { ...event, event: projectDashboardRpcEvent(child) } : event;\n\t\t}\n\t\tdefault:\n\t\t\treturn event;\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Image dedupe (dashboard mode)\n//\n// Inline image blocks cross the JSONL pipe multiple times per turn: prompt\n// re-emission (message_start + message_end), each tool result\n// (tool_execution_end + message_start + message_end), and the agent_end\n// transcript. A turn with several multi-MiB images easily fills the child\n// stdout queue while the dashboard is busy decoding, and the stdout guard\n// kills the session (issue 495).\n//\n// The dashboard already treats images content-globally: its server projection\n// replaces every inline image with an image_reference whose id is\n// sha256(mimeType + 0x00 + decodedBytes), caches the binary on first sight,\n// and serves later fetches from that cache (recovering from the authoritative\n// transcript when evicted). This projector applies the same reduction one\n// boundary earlier: each unique image crosses stdout at most once per process\n// lifetime; every later occurrence becomes an image_reference the dashboard\n// resolves from its cache. Live events only — command responses\n// (get_messages, get_dashboard_snapshot) always keep full payloads, because\n// they are the authoritative source the dashboard's image recovery reads.\n// ---------------------------------------------------------------------------\n\nconst DASHBOARD_IMAGE_MIME_TYPES = new Set([\"image/png\", \"image/jpeg\", \"image/gif\", \"image/webp\"]);\n\nconst BASE64_PATTERN = /^[A-Za-z0-9+/]+={0,2}$/;\n\nconst JPEG_EOI = Buffer.from([0xff, 0xd9]);\n\ntype ImageReference = { type: \"image_reference\"; id: string; mimeType: string; size: number };\n\n/**\n * Raster-signature check mirroring the dashboard server's hasRasterSignature\n * (packages/dashboard/src/server/dashboard-images.ts). Keep in sync: the child\n * may only turn a block into a reference when the dashboard's strict decode\n * (decodeDashboardImage) will accept it, or the reference dangles (the cache\n * holds nothing and the authoritative recovery decodes the same bytes and\n * rejects them again).\n */\nfunction hasRasterSignature(mimeType: string, bytes: Uint8Array): boolean {\n\tconst buffer = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n\tswitch (mimeType) {\n\t\tcase \"image/png\": {\n\t\t\tconst signature =\n\t\t\t\tbytes.length >= 24 &&\n\t\t\t\t[0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a].every((byte, i) => bytes[i] === byte);\n\t\t\treturn (\n\t\t\t\tsignature &&\n\t\t\t\tbuffer.subarray(12, 16).toString(\"ascii\") === \"IHDR\" &&\n\t\t\t\tbuffer.readUInt32BE(16) > 0 &&\n\t\t\t\tbuffer.readUInt32BE(20) > 0 &&\n\t\t\t\tbuffer.indexOf(Buffer.from(\"IEND\"), 24) >= 0\n\t\t\t);\n\t\t}\n\t\tcase \"image/jpeg\": {\n\t\t\tif (bytes.length < 4 || bytes[0] !== 0xff || bytes[1] !== 0xd8 || bytes[2] !== 0xff) return false;\n\t\t\t// EOI does not have to be the final byte. Phone JPEGs commonly append\n\t\t\t// auxiliary gain-map, motion-photo, or vendor metadata after the\n\t\t\t// primary image. Browsers and Photon decode the JPEG through EOI and\n\t\t\t// preserve the trailing bytes when the exact original is requested.\n\t\t\treturn buffer.lastIndexOf(JPEG_EOI) >= 2;\n\t\t}\n\t\tcase \"image/gif\": {\n\t\t\tconst header = buffer.subarray(0, 6).toString(\"ascii\");\n\t\t\treturn (\n\t\t\t\tbytes.length >= 14 &&\n\t\t\t\t(header === \"GIF87a\" || header === \"GIF89a\") &&\n\t\t\t\tbuffer.readUInt16LE(6) > 0 &&\n\t\t\t\tbuffer.readUInt16LE(8) > 0 &&\n\t\t\t\tbytes[bytes.length - 1] === 0x3b\n\t\t\t);\n\t\t}\n\t\tcase \"image/webp\": {\n\t\t\tif (\n\t\t\t\tbytes.length < 20 ||\n\t\t\t\tbuffer.subarray(0, 4).toString(\"ascii\") !== \"RIFF\" ||\n\t\t\t\tbuffer.subarray(8, 12).toString(\"ascii\") !== \"WEBP\"\n\t\t\t) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tconst chunk = buffer.subarray(12, 16).toString(\"ascii\");\n\t\t\treturn (\n\t\t\t\tbuffer.readUInt32LE(4) + 8 <= bytes.length && (chunk === \"VP8 \" || chunk === \"VP8L\" || chunk === \"VP8X\")\n\t\t\t);\n\t\t}\n\t}\n\treturn false;\n}\n\n/**\n * Content identity of an inline image block, mirroring the dashboard server's\n * dashboardImageId (sha256 of mimeType + 0x00 + decoded bytes). The gate is as\n * strict as the dashboard's decodeDashboardImage — allowlisted mimeType,\n * canonical base64 (round trip), and a matching raster signature — so a block\n * the dashboard would reject never becomes a reference: it stays inline at\n * every occurrence and is dropped by the dashboard's strict decode, exactly as\n * before this projection existed (no dangling image_references).\n */\nfunction imageBlockIdentity(mimeType: string, data: string): { id: string; size: number } | undefined {\n\tif (!DASHBOARD_IMAGE_MIME_TYPES.has(mimeType)) return undefined;\n\tif (data.length === 0 || data.length % 4 !== 0 || !BASE64_PATTERN.test(data)) return undefined;\n\tconst bytes = Buffer.from(data, \"base64\");\n\tif (bytes.byteLength === 0) return undefined;\n\tif (bytes.toString(\"base64\") !== data) return undefined; // non-canonical encoding the dashboard rejects\n\tif (!hasRasterSignature(mimeType, bytes)) return undefined; // signature mismatch the dashboard rejects\n\tconst id = createHash(\"sha256\").update(mimeType).update(Uint8Array.of(0)).update(bytes).digest(\"hex\");\n\treturn { id, size: bytes.byteLength };\n}\n\n/**\n * Replace occurrences of already-seen image blocks with their stable\n * reference, keeping the first occurrence of each unique image inline.\n * Returns the input by reference when nothing changed, so events without\n * images keep sharing objects with other session subscribers.\n */\nfunction dedupeImages(node: unknown, seen: Map<string, ImageReference>): unknown {\n\tif (Array.isArray(node)) {\n\t\tlet changed = false;\n\t\tconst result: unknown[] = new Array(node.length);\n\t\tfor (let i = 0; i < node.length; i++) {\n\t\t\tconst original = node[i];\n\t\t\tconst next = dedupeImages(original, seen);\n\t\t\tif (next !== original) changed = true;\n\t\t\tresult[i] = next;\n\t\t}\n\t\treturn changed ? result : node;\n\t}\n\tif (isPlainObject(node)) {\n\t\tif (node.type === \"image\" && typeof node.mimeType === \"string\" && typeof node.data === \"string\") {\n\t\t\tconst identity = imageBlockIdentity(node.mimeType, node.data);\n\t\t\tif (identity) {\n\t\t\t\tconst reference = seen.get(identity.id);\n\t\t\t\tif (reference) return reference;\n\t\t\t\tconst created: ImageReference = {\n\t\t\t\t\ttype: \"image_reference\",\n\t\t\t\t\tid: identity.id,\n\t\t\t\t\tmimeType: node.mimeType,\n\t\t\t\t\tsize: identity.size,\n\t\t\t\t};\n\t\t\t\tseen.set(identity.id, created);\n\t\t\t\treturn node;\n\t\t\t}\n\t\t\treturn node;\n\t\t}\n\t\tlet changed = false;\n\t\tconst result: Record<string, unknown> = {};\n\t\tfor (const key of Object.keys(node)) {\n\t\t\tconst original = node[key];\n\t\t\tconst next = dedupeImages(original, seen);\n\t\t\tif (next !== original) changed = true;\n\t\t\tresult[key] = next;\n\t\t}\n\t\treturn changed ? result : node;\n\t}\n\treturn node;\n}\n\n/**\n * Create the dashboard-mode RPC event projector for one runRpcMode process.\n *\n * Composes the per-event field projection with process-lifetime image dedupe.\n * Dashboard-mode sessions only — generic RPC consumers keep the full protocol.\n */\nexport function createDashboardRpcEventProjector(): (event: Record<string, unknown>) => Record<string, unknown> {\n\tconst seenImageIds = new Map<string, ImageReference>();\n\treturn (event: Record<string, unknown>): Record<string, unknown> => {\n\t\tconst projected = projectDashboardRpcEvent(event);\n\t\treturn dedupeImages(projected, seenImageIds) as Record<string, unknown>;\n\t};\n}\n"]}
|