@dreb/coding-agent 2.41.0 → 2.43.0

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.
@@ -1 +1 @@
1
- {"version":3,"file":"rpc-client.d.ts","sourceRoot":"","sources":["../../../src/modes/rpc/rpc-client.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAGH,OAAO,KAAK,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AACpE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AAC7C,OAAO,KAAK,EAAE,iBAAiB,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AACnF,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,6BAA6B,CAAC;AAC9D,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,gCAAgC,CAAC;AAEvE,OAAO,KAAK,EACX,gBAAgB,EAChB,sBAAsB,EAEtB,yBAAyB,EACzB,6BAA6B,EAC7B,sBAAsB,EACtB,kBAAkB,EAClB,YAAY,EAEZ,cAAc,EACd,eAAe,EACf,oBAAoB,EACpB,mBAAmB,EACnB,iBAAiB,EACjB,eAAe,EACf,WAAW,EACX,6BAA6B,EAC7B,MAAM,gBAAgB,CAAC;AAkBxB,MAAM,WAAW,gBAAgB;IAChC,sEAAsE;IACtE,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,sCAAsC;IACtC,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,4BAA4B;IAC5B,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC7B,sBAAsB;IACtB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,sBAAsB;IACtB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,+BAA+B;IAC/B,IAAI,CAAC,EAAE,MAAM,EAAE,CAAC;IAChB;;;;;OAKG;IACH,GAAG,CAAC,EAAE,MAAM,CAAC;IACb;;;;;OAKG;IACH,G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,OAAO,CAAC,mBAAmB,CAAC,CAGhD;IAED;;;;;;OAMG;IACG,WAAW,CAAC,QAAQ,EAAE,iBAAiB,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAG5E;IAED,uFAAuF;IACjF,oBAAoB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,yBAAyB,CAAC,CAG3E;IAED,4EAA4E;IACtE,kBAAkB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,6BAA6B,CAAC,CAG7E;IAED,yEAAyE;IACnE,oBAAoB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,6BAA6B,CAAC,CAG/E;IAED,mEAAmE;IAC7D,0BAA0B,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,6BAA6B,CAAC,CAGrF;IAMD;;;OAGG;IACH,WAAW,CAAC,OAAO,SAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAe1C;IAED;;OAEG;IACH,aAAa,CAAC,OAAO,SAAQ,GAAG,OAAO,CAAC,iBAAiB,EAAE,CAAC,CAiB3D;IAED;;OAEG;IACG,aAAa,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,YAAY,EAAE,EAAE,OAAO,SAAQ,GAAG,OAAO,CAAC,iBAAiB,EAAE,CAAC,CAI3G;IAMD;;;;OAIG;IACH,OAAO,CAAC,mBAAmB;IAQ3B,OAAO,CAAC,mBAAmB;IAM3B,OAAO,CAAC,UAAU;YAqBJ,IAAI;IAiClB,OAAO,CAAC,OAAO;CAUf","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 { AgentSessionEvent, 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\tRpcExtensionUIResponse,\n\tRpcPendingMessages,\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 events streamed by the RPC server. The wire carries the full\n * {@link AgentSessionEvent} union (core AgentEvents plus session-level events like\n * background_agent_start/end/event, tasks_update, suggest_next).\n */\nexport type RpcEventListener = (event: AgentSessionEvent) => 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\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/**\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/**\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 * 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<{\n\t\tmodels: Array<{ provider: string; modelId: string; median: number; mean: number; count: number }>;\n\t}> {\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/**\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 }>> {\n\t\tconst response = await this.send({ type: \"get_fork_messages\" });\n\t\treturn this.getData<{ messages: Array<{ entryId: string; text: string }> }>(response).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 available commands (extension commands, prompt templates, skills).\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<AgentSessionEvent[]> {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst events: AgentSessionEvent[] = [];\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<AgentSessionEvent[]> {\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 = JSON.parse(line);\n\n\t\t\t// Check if it's a response to a pending request\n\t\t\tif (data.type === \"response\" && data.id && this.pendingRequests.has(data.id)) {\n\t\t\t\tconst pending = this.pendingRequests.get(data.id)!;\n\t\t\t\tthis.pendingRequests.delete(data.id);\n\t\t\t\tpending.resolve(data as RpcResponse);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Otherwise it's an event\n\t\t\tfor (const listener of this.eventListeners) {\n\t\t\t\tlistener(data as AgentSessionEvent);\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.d.ts","sourceRoot":"","sources":["../../../src/modes/rpc/rpc-client.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAGH,OAAO,KAAK,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AACpE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AAC7C,OAAO,KAAK,EAAE,YAAY,E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AAC,CAG7E;IAED,yEAAyE;IACnE,oBAAoB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,6BAA6B,CAAC,CAG/E;IAED,mEAAmE;IAC7D,0BAA0B,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,6BAA6B,CAAC,CAGrF;IAMD;;;OAGG;IACH,WAAW,CAAC,OAAO,SAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAe1C;IAED;;OAEG;IACH,aAAa,CAAC,OAAO,SAAQ,GAAG,OAAO,CAAC,QAAQ,EAAE,CAAC,CAiBlD;IAED;;OAEG;IACG,aAAa,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,YAAY,EAAE,EAAE,OAAO,SAAQ,GAAG,OAAO,CAAC,QAAQ,EAAE,CAAC,CAIlG;IAMD;;;;OAIG;IACH,OAAO,CAAC,mBAAmB;IAQ3B,OAAO,CAAC,mBAAmB;IAM3B,OAAO,CAAC,UAAU;YA2BJ,IAAI;IAiClB,OAAO,CAAC,OAAO;CAUf","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\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/**\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/**\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<{\n\t\tmodels: Array<{ provider: string; modelId: string; median: number; mean: number; count: number }>;\n\t}> {\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/**\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 }>> {\n\t\tconst response = await this.send({ type: \"get_fork_messages\" });\n\t\treturn this.getData<{ messages: Array<{ entryId: string; text: string }> }>(response).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 available commands (extension commands, prompt templates, skills).\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"]}
@@ -13,6 +13,33 @@ import { attachJsonlLineReader, serializeJsonLine } from "./jsonl.js";
13
13
  * it as alive. An 'error'/'exit' event during this window rejects start() early.
14
14
  */
15
15
  const INIT_GRACE_MS = 100;
16
+ function isJsonRecord(value) {
17
+ return typeof value === "object" && value !== null && !Array.isArray(value);
18
+ }
19
+ function isRpcResponseMessage(value) {
20
+ return isJsonRecord(value) && value.type === "response";
21
+ }
22
+ function isRpcDashboardSnapshotBarrierEvent(value) {
23
+ return isJsonRecord(value) && value.type === "dashboard_snapshot_barrier" && typeof value.snapshotId === "string";
24
+ }
25
+ function isRpcExtensionUIRequestMessage(value) {
26
+ return (isJsonRecord(value) &&
27
+ value.type === "extension_ui_request" &&
28
+ typeof value.id === "string" &&
29
+ typeof value.method === "string");
30
+ }
31
+ function isRpcEvent(value) {
32
+ if (!isJsonRecord(value) || typeof value.type !== "string" || value.type === "response") {
33
+ return false;
34
+ }
35
+ if (value.type === "dashboard_snapshot_barrier") {
36
+ return isRpcDashboardSnapshotBarrierEvent(value);
37
+ }
38
+ if (value.type === "extension_ui_request") {
39
+ return isRpcExtensionUIRequestMessage(value);
40
+ }
41
+ return true;
42
+ }
16
43
  // ============================================================================
17
44
  // RPC Client
18
45
  // ============================================================================
@@ -220,6 +247,15 @@ export class RpcClient {
220
247
  const response = await this.send({ type: "get_state" });
221
248
  return this.getData(response);
222
249
  }
250
+ /**
251
+ * Capture a dashboard recovery snapshot. The RPC stream emits a matching
252
+ * `dashboard_snapshot_barrier` immediately before this response; consumers
253
+ * need that event's EventHub sequence before applying the snapshot.
254
+ */
255
+ async getDashboardSnapshot() {
256
+ const response = await this.send({ type: "get_dashboard_snapshot" });
257
+ return this.getData(response);
258
+ }
223
259
  /**
224
260
  * Get loaded context/resources metadata (paths/names only, no file contents).
225
261
  */
@@ -629,14 +665,19 @@ export class RpcClient {
629
665
  handleLine(line) {
630
666
  try {
631
667
  const data = JSON.parse(line);
632
- // Check if it's a response to a pending request
633
- if (data.type === "response" && data.id && this.pendingRequests.has(data.id)) {
634
- const pending = this.pendingRequests.get(data.id);
635
- this.pendingRequests.delete(data.id);
636
- pending.resolve(data);
668
+ // Check if it's a response to a pending request. Unknown/unsolicited
669
+ // response frames are not events and should not be forwarded to listeners.
670
+ if (isRpcResponseMessage(data)) {
671
+ if (typeof data.id === "string" && this.pendingRequests.has(data.id)) {
672
+ const pending = this.pendingRequests.get(data.id);
673
+ this.pendingRequests.delete(data.id);
674
+ pending.resolve(data);
675
+ }
676
+ return;
677
+ }
678
+ if (!isRpcEvent(data)) {
637
679
  return;
638
680
  }
639
- // Otherwise it's an event
640
681
  for (const listener of this.eventListeners) {
641
682
  listener(data);
642
683
  }
@@ -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,M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ent":["/**\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 { AgentSessionEvent, 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\tRpcExtensionUIResponse,\n\tRpcPendingMessages,\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 events streamed by the RPC server. The wire carries the full\n * {@link AgentSessionEvent} union (core AgentEvents plus session-level events like\n * background_agent_start/end/event, tasks_update, suggest_next).\n */\nexport type RpcEventListener = (event: AgentSessionEvent) => 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\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/**\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/**\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 * 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<{\n\t\tmodels: Array<{ provider: string; modelId: string; median: number; mean: number; count: number }>;\n\t}> {\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/**\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 }>> {\n\t\tconst response = await this.send({ type: \"get_fork_messages\" });\n\t\treturn this.getData<{ messages: Array<{ entryId: string; text: string }> }>(response).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 available commands (extension commands, prompt templates, skills).\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<AgentSessionEvent[]> {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst events: AgentSessionEvent[] = [];\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<AgentSessionEvent[]> {\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 = JSON.parse(line);\n\n\t\t\t// Check if it's a response to a pending request\n\t\t\tif (data.type === \"response\" && data.id && this.pendingRequests.has(data.id)) {\n\t\t\t\tconst pending = this.pendingRequests.get(data.id)!;\n\t\t\t\tthis.pendingRequests.delete(data.id);\n\t\t\t\tpending.resolve(data as RpcResponse);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Otherwise it's an event\n\t\t\tfor (const listener of this.eventListeners) {\n\t\t\t\tlistener(data as AgentSessionEvent);\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\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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\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/**\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/**\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<{\n\t\tmodels: Array<{ provider: string; modelId: string; median: number; mean: number; count: number }>;\n\t}> {\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/**\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 }>> {\n\t\tconst response = await this.send({ type: \"get_fork_messages\" });\n\t\treturn this.getData<{ messages: Array<{ entryId: string; text: string }> }>(response).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 available commands (extension commands, prompt templates, skills).\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"]}
@@ -7,7 +7,7 @@
7
7
  * Protocol:
8
8
  * - Commands: JSON objects with `type` field, optional `id` for correlation
9
9
  * - Responses: JSON objects with `type: "response"`, `command`, `success`, and optional `data`/`error`
10
- * - Events: AgentSessionEvent objects streamed as they occur
10
+ * - Events: RpcEvent objects streamed as they occur
11
11
  * - Extension UI: Extension UI requests are emitted, client responds with extension_ui_response
12
12
  */
13
13
  import type { AgentSession } from "../../core/agent-session.js";
@@ -17,7 +17,7 @@ import { SessionManager } from "../../core/session-manager.js";
17
17
  import type { SettingsManager } from "../../core/settings-manager.js";
18
18
  import { type BackgroundAgentInfo } from "../../core/tools/subagent.js";
19
19
  import type { RpcAgentTypeInfo, RpcBackgroundAgentInfo, RpcContextTrustEvaluation, RpcContextTrustMutationResult, RpcPendingMessages, RpcResources, RpcScopedModel, RpcSessionInfo, RpcSessionState, RpcSettingsSnapshot, RpcSettingsUpdate, RpcTreeNode, RpcTrustedFolderRemovalResult } from "./rpc-types.js";
20
- export type { RpcCommand, RpcExtensionUIRequest, RpcExtensionUIResponse, RpcResponse, RpcSessionState, } from "./rpc-types.js";
20
+ export type { RpcCommand, RpcDashboardSnapshot, RpcDashboardSnapshotBarrierEvent, RpcEvent, RpcExtensionUIRequest, RpcExtensionUIResponse, RpcResponse, RpcSessionState, } from "./rpc-types.js";
21
21
  /**
22
22
  * Map a core {@link SessionInfo} to the RPC DTO, converting Date fields to ISO strings.
23
23
  * Shared by the `list_sessions` and `list_all_sessions` handlers so their shapes cannot drift.
@@ -63,7 +63,8 @@ export declare function toRpcBackgroundAgentInfo(a: Readonly<BackgroundAgentInfo
63
63
  export declare function listAgentTypesForRpc(cwd: string): RpcAgentTypeInfo[];
64
64
  /** The slice of SettingsManager the settings RPC handlers need. */
65
65
  type SettingsReader = Pick<SettingsManager, "getDefaultProvider" | "getDefaultModel" | "getDefaultThinkingLevel" | "getSteeringMode" | "getFollowUpMode" | "getCompactionEnabled" | "getRetryEnabled" | "getImageAutoResize" | "getBlockImages" | "getEnableSkillCommands" | "getGlobalContextTrustPolicy" | "getConfiguredTrustedContextFolders" | "getTransport" | "getHideThinkingBlock" | "getAgentModels">;
66
- type SettingsWriter = SettingsReader & Pick<SettingsManager, "setDefaultModelAndProvider" | "setDefaultThinkingLevel" | "setSteeringMode" | "setFollowUpMode" | "setCompactionEnabled" | "setRetryEnabled" | "setImageAutoResize" | "setBlockImages" | "setEnableSkillCommands" | "setAutoLoadNestedContext" | "setTrustedContextFolders" | "removeTrustedContextFolder" | "setContextTrust" | "setTransport" | "setHideThinkingBlock" | "setAgentModelsForAgent" | "removeAgentModelsForAgent" | "hasProjectAgentModelOverride" | "hasGlobalSettingsLoadError" | "reload" | "flush" | "drainErrors">;
66
+ type SettingsRefresher = SettingsReader & Pick<SettingsManager, "reload" | "flush" | "drainErrors" | "hasGlobalSettingsLoadError" | "hasProjectSettingsLoadError">;
67
+ type SettingsWriter = SettingsRefresher & Pick<SettingsManager, "setDefaultModelAndProvider" | "setDefaultThinkingLevel" | "setSteeringMode" | "setFollowUpMode" | "setCompactionEnabled" | "setRetryEnabled" | "setImageAutoResize" | "setBlockImages" | "setEnableSkillCommands" | "setAutoLoadNestedContext" | "setTrustedContextFolders" | "removeTrustedContextFolder" | "setContextTrust" | "setTransport" | "setHideThinkingBlock" | "setAgentModelsForAgent" | "removeAgentModelsForAgent" | "hasProjectAgentModelOverride">;
67
68
  /**
68
69
  * Handle the `get_settings` RPC command: snapshot the persistent default settings.
69
70
  *
@@ -73,6 +74,22 @@ type SettingsWriter = SettingsReader & Pick<SettingsManager, "setDefaultModelAnd
73
74
  * (like {@link deleteSessionForRpc}) so it is unit-testable without a live RPC session.
74
75
  */
75
76
  export declare function getSettingsForRpc(settingsManager: SettingsReader): RpcSettingsSnapshot;
77
+ /**
78
+ * Reload durable global and project settings before serving `get_settings`.
79
+ *
80
+ * The shared settings-operation lock prevents a refresh from discarding another RPC
81
+ * settings operation's queued modifications. A failed queued write is returned before
82
+ * reload so its in-memory changes remain intact rather than being replaced by stale disk
83
+ * content. Reload failures leave SettingsManager's previous values in memory, therefore
84
+ * they must be surfaced as an RPC error instead of producing a stale snapshot.
85
+ */
86
+ export declare function getFreshSettingsForRpc(settingsManager: SettingsRefresher): Promise<{
87
+ ok: true;
88
+ settings: RpcSettingsSnapshot;
89
+ } | {
90
+ ok: false;
91
+ error: string;
92
+ }>;
76
93
  /** Evaluate a strictly canonical, absolute directory through the core trust matcher. */
77
94
  export declare function evaluateContextTrustForRpc(settingsManager: Pick<SettingsManager, "getGlobalContextTrustPolicy">, path: unknown): {
78
95
  ok: true;