@dreb/coding-agent 2.52.0 → 2.53.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.
- package/README.md +1 -1
- package/dist/core/slash-commands.d.ts +14 -0
- package/dist/core/slash-commands.d.ts.map +1 -1
- package/dist/core/slash-commands.js +28 -3
- package/dist/core/slash-commands.js.map +1 -1
- package/dist/modes/rpc/rpc-client.d.ts +11 -1
- package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-client.js +15 -1
- package/dist/modes/rpc/rpc-client.js.map +1 -1
- package/dist/modes/rpc/rpc-mode.d.ts +3 -1
- package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-mode.js +130 -27
- package/dist/modes/rpc/rpc-mode.js.map +1 -1
- package/dist/modes/rpc/rpc-types.d.ts +48 -4
- package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-types.js.map +1 -1
- package/docs/dashboard.md +1 -3
- package/docs/extensions.md +4 -4
- package/docs/rpc.md +58 -17
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -81,7 +81,7 @@ Or use a custom provider (corporate proxy, Bedrock, etc.) — see [Custom provid
|
|
|
81
81
|
|
|
82
82
|
Then just talk to dreb. All 13 standard built-in tools are enabled by default: `read`, `write`, `edit`, `bash`, `grep`, `find`, `ls`, `web_search`, `web_fetch`, `subagent`, `wait`, `watch_github_ci`, and `ask_user`. Use `--tools` to restrict to a subset (e.g., `--tools read,grep,find,ls` for read-only). Three additional tools — `search`, `skill`, and `tasks_update` — are always active regardless of `--tools`. `suggest_next` is active by default but excluded when `--tools` is specified. The model uses these to fulfill your requests. Add capabilities via [skills](#skills), [prompt templates](#prompt-templates), [extensions](#extensions), or [packages](#packages).
|
|
83
83
|
|
|
84
|
-
**Also available:** [`@dreb/telegram`](https://www.npmjs.com/package/@dreb/telegram) — run dreb as a Telegram bot with live tool status and visible results for user-facing tools (`npm install -g @dreb/telegram`). [`@dreb/dashboard`](https://www.npmjs.com/package/@dreb/dashboard) — run `dreb dashboard` for a browser UI with fleet overview, full chat steering, inline provider/API failures with partial output preserved, sanitized raster tool images plus sent user uploads retained as bounded transcript previews by default, a bounded all-agent subagent panel with drill-in, host file browser, curated appearance themes (per-browser light/dark), and Tailscale/rotating-code pairing (`npm install -g @dreb/dashboard`; see [docs/dashboard.md](docs/dashboard.md)). Tool images cross browser-facing transport as content-addressed references; browser-local Settings offers placeholders, bounded previews, or informed-opt-in originals, with size disclosure and confirmation above 1 MiB. Full-resolution HTML export remains self-contained. Compact SSE snapshots update live fleet cards without repeatedly fetching the cross-project inventory, and session drill-in hydrates state, messages, and background agents through one ordered snapshot request. Terminal provider failures show their reason on fleet cards, while transient failures clear terminal state when automatic retry begins and remain recorded inline on the failed attempt. Its top bar and persistent session header indicators report connecting, connected, retrying, resyncing, disconnected, or auth failed; bounded SSE replay plus an explicit snapshot barrier restores session state, tasks, and image references after a reload, restart, gap, backpressure disconnect, or stalled stream, while authenticated image routes recover bytes separately from authoritative transcripts.
|
|
84
|
+
**Also available:** [`@dreb/telegram`](https://www.npmjs.com/package/@dreb/telegram) — run dreb as a Telegram bot with live tool status and visible results for user-facing tools (`npm install -g @dreb/telegram`). [`@dreb/dashboard`](https://www.npmjs.com/package/@dreb/dashboard) — run `dreb dashboard` for a browser UI with fleet overview, full chat steering, generic fail-closed built-in slash-command discovery and execution, inline provider/API failures with partial output preserved, sanitized raster tool images plus sent user uploads retained as bounded transcript previews by default, a bounded all-agent subagent panel with drill-in, host file browser, curated appearance themes (per-browser light/dark), and Tailscale/rotating-code pairing (`npm install -g @dreb/dashboard`; see [docs/dashboard.md](docs/dashboard.md)). Tool images cross browser-facing transport as content-addressed references; browser-local Settings offers placeholders, bounded previews, or informed-opt-in originals, with size disclosure and confirmation above 1 MiB. Full-resolution HTML export remains self-contained. Compact SSE snapshots update live fleet cards without repeatedly fetching the cross-project inventory, and session drill-in hydrates state, messages, and background agents through one ordered snapshot request. Terminal provider failures show their reason on fleet cards, while transient failures clear terminal state when automatic retry begins and remain recorded inline on the failed attempt. Its top bar and persistent session header indicators report connecting, connected, retrying, resyncing, disconnected, or auth failed; bounded SSE replay plus an explicit snapshot barrier restores session state, tasks, and image references after a reload, restart, gap, backpressure disconnect, or stalled stream, while authenticated image routes recover bytes separately from authoritative transcripts.
|
|
85
85
|
|
|
86
86
|
**Platform notes:** [Windows](docs/windows.md) | [Termux (Android)](docs/termux.md) | [tmux](docs/tmux.md) | [Terminal setup](docs/terminal-setup.md) | [Shell aliases](docs/shell-aliases.md)
|
|
87
87
|
|
|
@@ -9,6 +9,20 @@ export interface SlashCommandInfo {
|
|
|
9
9
|
export interface BuiltinSlashCommand {
|
|
10
10
|
name: string;
|
|
11
11
|
description: string;
|
|
12
|
+
/** Whether the command is offered in dashboard autocomplete. Typed built-ins are always intercepted. */
|
|
13
|
+
dashboard?: false;
|
|
12
14
|
}
|
|
13
15
|
export declare const BUILTIN_SLASH_COMMANDS: ReadonlyArray<BuiltinSlashCommand>;
|
|
16
|
+
/**
|
|
17
|
+
* Parse a registered built-in from the first slash token.
|
|
18
|
+
*
|
|
19
|
+
* `/fork` and `/fork anything` match while `/forklift` and unknown slash
|
|
20
|
+
* commands do not. Leading/trailing whitespace follows interactive-mode submit
|
|
21
|
+
* behavior. Hidden development commands are intentionally absent from the
|
|
22
|
+
* registry and therefore never match.
|
|
23
|
+
*/
|
|
24
|
+
export declare function parseBuiltinSlashCommand(text: string): {
|
|
25
|
+
command: BuiltinSlashCommand;
|
|
26
|
+
args: string;
|
|
27
|
+
} | undefined;
|
|
14
28
|
//# sourceMappingURL=slash-commands.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"slash-commands.d.ts","sourceRoot":"","sources":["../../src/core/slash-commands.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAEnD,MAAM,MAAM,kBAAkB,GAAG,WAAW,GAAG,QAAQ,GAAG,OAAO,CAAC;AAElE,MAAM,WAAW,gBAAgB;IAChC,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,MAAM,EAAE,kBAAkB,CAAC;IAC3B,UAAU,EAAE,UAAU,CAAC;CACvB;AAED,MAAM,WAAW,mBAAmB;IACnC,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;
|
|
1
|
+
{"version":3,"file":"slash-commands.d.ts","sourceRoot":"","sources":["../../src/core/slash-commands.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAEnD,MAAM,MAAM,kBAAkB,GAAG,WAAW,GAAG,QAAQ,GAAG,OAAO,CAAC;AAElE,MAAM,WAAW,gBAAgB;IAChC,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,MAAM,EAAE,kBAAkB,CAAC;IAC3B,UAAU,EAAE,UAAU,CAAC;CACvB;AAED,MAAM,WAAW,mBAAmB;IACnC,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,wGAAwG;IACxG,SAAS,CAAC,EAAE,KAAK,CAAC;CAClB;AAED,eAAO,MAAM,sBAAsB,EAAE,aAAa,CAAC,mBAAmB,CAyBrE,CAAC;AAIF;;;;;;;GAOG;AACH,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,MAAM,GAAG;IAAE,OAAO,EAAE,mBAAmB,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,GAAG,SAAS,CAQjH","sourcesContent":["import type { SourceInfo } from \"./source-info.js\";\n\nexport type SlashCommandSource = \"extension\" | \"prompt\" | \"skill\";\n\nexport interface SlashCommandInfo {\n\tname: string;\n\tdescription?: string;\n\tsource: SlashCommandSource;\n\tsourceInfo: SourceInfo;\n}\n\nexport interface BuiltinSlashCommand {\n\tname: string;\n\tdescription: string;\n\t/** Whether the command is offered in dashboard autocomplete. Typed built-ins are always intercepted. */\n\tdashboard?: false;\n}\n\nexport const BUILTIN_SLASH_COMMANDS: ReadonlyArray<BuiltinSlashCommand> = [\n\t{ name: \"settings\", description: \"Open settings menu\" },\n\t{ name: \"model\", description: \"Select model (opens selector UI)\" },\n\t{ name: \"scoped-models\", description: \"Enable/disable models for Ctrl+P cycling\" },\n\t{ name: \"export\", description: \"Export session (HTML default, or specify path: .html/.jsonl)\" },\n\t{ name: \"import\", description: \"Import and resume a session from a JSONL file\" },\n\t{ name: \"copy\", description: \"Copy last agent message to clipboard\", dashboard: false },\n\t{ name: \"name\", description: \"Set session display name\" },\n\t{ name: \"session\", description: \"Show session info and stats\" },\n\t{ name: \"hotkeys\", description: \"Show all keyboard shortcuts\", dashboard: false },\n\t{ name: \"fork\", description: \"Create a new fork from a previous message\" },\n\t{ name: \"tree\", description: \"Navigate session tree (switch branches)\" },\n\t{ name: \"login\", description: \"Login with OAuth provider\" },\n\t{ name: \"logout\", description: \"Logout from OAuth provider\" },\n\t{ name: \"new\", description: \"Start a new session\" },\n\t{ name: \"compact\", description: \"Manually compact the session context\" },\n\t{ name: \"dream\", description: \"Consolidate and prune memories (backup, merge, scan sessions)\" },\n\t{ name: \"resume\", description: \"Resume a different session\" },\n\t{ name: \"reload\", description: \"Reload keybindings, extensions, skills, prompts, and themes\" },\n\t{\n\t\tname: \"buddy\",\n\t\tdescription: \"Hatch or manage your terminal companion (pet, reroll, off)\",\n\t\tdashboard: false,\n\t},\n\t{ name: \"quit\", description: \"Quit dreb\" },\n];\n\nconst BUILTIN_BY_NAME = new Map(BUILTIN_SLASH_COMMANDS.map((command) => [command.name, command]));\n\n/**\n * Parse a registered built-in from the first slash token.\n *\n * `/fork` and `/fork anything` match while `/forklift` and unknown slash\n * commands do not. Leading/trailing whitespace follows interactive-mode submit\n * behavior. Hidden development commands are intentionally absent from the\n * registry and therefore never match.\n */\nexport function parseBuiltinSlashCommand(text: string): { command: BuiltinSlashCommand; args: string } | undefined {\n\tconst trimmed = text.trim();\n\tif (!trimmed.startsWith(\"/\")) return undefined;\n\tconst match = /^\\/([^\\s]+)(?:\\s+([\\s\\S]*))?$/.exec(trimmed);\n\tif (!match) return undefined;\n\tconst command = BUILTIN_BY_NAME.get(match[1]);\n\tif (!command) return undefined;\n\treturn { command, args: (match[2] ?? \"\").trim() };\n}\n"]}
|
|
@@ -4,10 +4,10 @@ export const BUILTIN_SLASH_COMMANDS = [
|
|
|
4
4
|
{ name: "scoped-models", description: "Enable/disable models for Ctrl+P cycling" },
|
|
5
5
|
{ name: "export", description: "Export session (HTML default, or specify path: .html/.jsonl)" },
|
|
6
6
|
{ name: "import", description: "Import and resume a session from a JSONL file" },
|
|
7
|
-
{ name: "copy", description: "Copy last agent message to clipboard" },
|
|
7
|
+
{ name: "copy", description: "Copy last agent message to clipboard", dashboard: false },
|
|
8
8
|
{ name: "name", description: "Set session display name" },
|
|
9
9
|
{ name: "session", description: "Show session info and stats" },
|
|
10
|
-
{ name: "hotkeys", description: "Show all keyboard shortcuts" },
|
|
10
|
+
{ name: "hotkeys", description: "Show all keyboard shortcuts", dashboard: false },
|
|
11
11
|
{ name: "fork", description: "Create a new fork from a previous message" },
|
|
12
12
|
{ name: "tree", description: "Navigate session tree (switch branches)" },
|
|
13
13
|
{ name: "login", description: "Login with OAuth provider" },
|
|
@@ -17,7 +17,32 @@ export const BUILTIN_SLASH_COMMANDS = [
|
|
|
17
17
|
{ name: "dream", description: "Consolidate and prune memories (backup, merge, scan sessions)" },
|
|
18
18
|
{ name: "resume", description: "Resume a different session" },
|
|
19
19
|
{ name: "reload", description: "Reload keybindings, extensions, skills, prompts, and themes" },
|
|
20
|
-
{
|
|
20
|
+
{
|
|
21
|
+
name: "buddy",
|
|
22
|
+
description: "Hatch or manage your terminal companion (pet, reroll, off)",
|
|
23
|
+
dashboard: false,
|
|
24
|
+
},
|
|
21
25
|
{ name: "quit", description: "Quit dreb" },
|
|
22
26
|
];
|
|
27
|
+
const BUILTIN_BY_NAME = new Map(BUILTIN_SLASH_COMMANDS.map((command) => [command.name, command]));
|
|
28
|
+
/**
|
|
29
|
+
* Parse a registered built-in from the first slash token.
|
|
30
|
+
*
|
|
31
|
+
* `/fork` and `/fork anything` match while `/forklift` and unknown slash
|
|
32
|
+
* commands do not. Leading/trailing whitespace follows interactive-mode submit
|
|
33
|
+
* behavior. Hidden development commands are intentionally absent from the
|
|
34
|
+
* registry and therefore never match.
|
|
35
|
+
*/
|
|
36
|
+
export function parseBuiltinSlashCommand(text) {
|
|
37
|
+
const trimmed = text.trim();
|
|
38
|
+
if (!trimmed.startsWith("/"))
|
|
39
|
+
return undefined;
|
|
40
|
+
const match = /^\/([^\s]+)(?:\s+([\s\S]*))?$/.exec(trimmed);
|
|
41
|
+
if (!match)
|
|
42
|
+
return undefined;
|
|
43
|
+
const command = BUILTIN_BY_NAME.get(match[1]);
|
|
44
|
+
if (!command)
|
|
45
|
+
return undefined;
|
|
46
|
+
return { command, args: (match[2] ?? "").trim() };
|
|
47
|
+
}
|
|
23
48
|
//# sourceMappingURL=slash-commands.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"slash-commands.js","sourceRoot":"","sources":["../../src/core/slash-commands.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"slash-commands.js","sourceRoot":"","sources":["../../src/core/slash-commands.ts"],"names":[],"mappings":"AAkBA,MAAM,CAAC,MAAM,sBAAsB,GAAuC;IACzE,EAAE,IAAI,EAAE,UAAU,EAAE,WAAW,EAAE,oBAAoB,EAAE;IACvD,EAAE,IAAI,EAAE,OAAO,EAAE,WAAW,EAAE,kCAAkC,EAAE;IAClE,EAAE,IAAI,EAAE,eAAe,EAAE,WAAW,EAAE,0CAA0C,EAAE;IAClF,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,8DAA8D,EAAE;IAC/F,EAAE,IAAI,EAAE,QAAQ,E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;GAOG;AACH,MAAM,UAAU,wBAAwB,CAAC,IAAY,EAA8D;IAClH,MAAM,OAAO,GAAG,IAAI,CAAC,IAAI,EAAE,CAAC;IAC5B,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,GAAG,CAAC;QAAE,OAAO,SAAS,CAAC;IAC/C,MAAM,KAAK,GAAG,+BAA+B,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IAC5D,IAAI,CAAC,KAAK;QAAE,OAAO,SAAS,CAAC;IAC7B,MAAM,OAAO,GAAG,eAAe,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;IAC9C,IAAI,CAAC,OAAO;QAAE,OAAO,SAAS,CAAC;IAC/B,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC;AAAA,CAClD","sourcesContent":["import type { SourceInfo } from \"./source-info.js\";\n\nexport type SlashCommandSource = \"extension\" | \"prompt\" | \"skill\";\n\nexport interface SlashCommandInfo {\n\tname: string;\n\tdescription?: string;\n\tsource: SlashCommandSource;\n\tsourceInfo: SourceInfo;\n}\n\nexport interface BuiltinSlashCommand {\n\tname: string;\n\tdescription: string;\n\t/** Whether the command is offered in dashboard autocomplete. Typed built-ins are always intercepted. */\n\tdashboard?: false;\n}\n\nexport const BUILTIN_SLASH_COMMANDS: ReadonlyArray<BuiltinSlashCommand> = [\n\t{ name: \"settings\", description: \"Open settings menu\" },\n\t{ name: \"model\", description: \"Select model (opens selector UI)\" },\n\t{ name: \"scoped-models\", description: \"Enable/disable models for Ctrl+P cycling\" },\n\t{ name: \"export\", description: \"Export session (HTML default, or specify path: .html/.jsonl)\" },\n\t{ name: \"import\", description: \"Import and resume a session from a JSONL file\" },\n\t{ name: \"copy\", description: \"Copy last agent message to clipboard\", dashboard: false },\n\t{ name: \"name\", description: \"Set session display name\" },\n\t{ name: \"session\", description: \"Show session info and stats\" },\n\t{ name: \"hotkeys\", description: \"Show all keyboard shortcuts\", dashboard: false },\n\t{ name: \"fork\", description: \"Create a new fork from a previous message\" },\n\t{ name: \"tree\", description: \"Navigate session tree (switch branches)\" },\n\t{ name: \"login\", description: \"Login with OAuth provider\" },\n\t{ name: \"logout\", description: \"Logout from OAuth provider\" },\n\t{ name: \"new\", description: \"Start a new session\" },\n\t{ name: \"compact\", description: \"Manually compact the session context\" },\n\t{ name: \"dream\", description: \"Consolidate and prune memories (backup, merge, scan sessions)\" },\n\t{ name: \"resume\", description: \"Resume a different session\" },\n\t{ name: \"reload\", description: \"Reload keybindings, extensions, skills, prompts, and themes\" },\n\t{\n\t\tname: \"buddy\",\n\t\tdescription: \"Hatch or manage your terminal companion (pet, reroll, off)\",\n\t\tdashboard: false,\n\t},\n\t{ name: \"quit\", description: \"Quit dreb\" },\n];\n\nconst BUILTIN_BY_NAME = new Map(BUILTIN_SLASH_COMMANDS.map((command) => [command.name, command]));\n\n/**\n * Parse a registered built-in from the first slash token.\n *\n * `/fork` and `/fork anything` match while `/forklift` and unknown slash\n * commands do not. Leading/trailing whitespace follows interactive-mode submit\n * behavior. Hidden development commands are intentionally absent from the\n * registry and therefore never match.\n */\nexport function parseBuiltinSlashCommand(text: string): { command: BuiltinSlashCommand; args: string } | undefined {\n\tconst trimmed = text.trim();\n\tif (!trimmed.startsWith(\"/\")) return undefined;\n\tconst match = /^\\/([^\\s]+)(?:\\s+([\\s\\S]*))?$/.exec(trimmed);\n\tif (!match) return undefined;\n\tconst command = BUILTIN_BY_NAME.get(match[1]);\n\tif (!command) return undefined;\n\treturn { command, args: (match[2] ?? \"\").trim() };\n}\n"]}
|
|
@@ -117,6 +117,12 @@ export declare class RpcClient {
|
|
|
117
117
|
newSession(parentSession?: string): Promise<{
|
|
118
118
|
cancelled: boolean;
|
|
119
119
|
}>;
|
|
120
|
+
/** Reload extensions, skills, prompts, themes, and other session resources. */
|
|
121
|
+
reload(): Promise<void>;
|
|
122
|
+
/** Run `/dream` or one of its backup-path forms. */
|
|
123
|
+
dream(args?: string): Promise<{
|
|
124
|
+
message: string;
|
|
125
|
+
}>;
|
|
120
126
|
/**
|
|
121
127
|
* Get current session state.
|
|
122
128
|
*/
|
|
@@ -256,6 +262,10 @@ export declare class RpcClient {
|
|
|
256
262
|
exportHtml(outputPath?: string): Promise<{
|
|
257
263
|
path: string;
|
|
258
264
|
}>;
|
|
265
|
+
/** Import a JSONL file into the current runtime. */
|
|
266
|
+
importJsonl(inputPath: string): Promise<{
|
|
267
|
+
cancelled: boolean;
|
|
268
|
+
}>;
|
|
259
269
|
/**
|
|
260
270
|
* Switch to a different session file.
|
|
261
271
|
* @returns Object with `cancelled: true` if an extension cancelled the switch
|
|
@@ -321,7 +331,7 @@ export declare class RpcClient {
|
|
|
321
331
|
*/
|
|
322
332
|
getMessages(): Promise<AgentMessage[]>;
|
|
323
333
|
/**
|
|
324
|
-
* Get
|
|
334
|
+
* Get discoverable commands, including built-ins that require client-side handling.
|
|
325
335
|
*/
|
|
326
336
|
getCommands(): Promise<RpcSlashCommand[]>;
|
|
327
337
|
/**
|
|
@@ -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,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAChE,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,oBAAoB,EAEpB,QAAQ,EAER,sBAAsB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AI,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"]}
|
|
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,EAAE,MAAM,6BAA6B,CAAC;AAChE,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,oBAAoB,EAEpB,QAAQ,EAER,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;IA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AAO,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/** Reload extensions, skills, prompts, themes, and other session resources. */\n\tasync reload(): Promise<void> {\n\t\tawait this.send({ type: \"reload\" });\n\t}\n\n\t/** Run `/dream` or one of its backup-path forms. */\n\tasync dream(args?: string): Promise<{ message: string }> {\n\t\tconst response = await this.send({ type: \"dream\", args });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Get current session state.\n\t */\n\tasync getState(): Promise<RpcSessionState> {\n\t\tconst response = await this.send({ type: \"get_state\" });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Capture a dashboard recovery snapshot. The RPC stream emits a matching\n\t * `dashboard_snapshot_barrier` immediately before this response; consumers\n\t * need that event's EventHub sequence before applying the snapshot.\n\t */\n\tasync getDashboardSnapshot(): Promise<RpcDashboardSnapshot> {\n\t\tconst response = await this.send({ type: \"get_dashboard_snapshot\" });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Get loaded context/resources metadata (paths/names only, no file contents).\n\t */\n\tasync getResources(): Promise<RpcResources> {\n\t\tconst response = await this.send({ type: \"get_resources\" });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Get current git branch for the agent cwd.\n\t */\n\tasync getGitBranch(): Promise<string | null> {\n\t\tconst response = await this.send({ type: \"get_git_branch\" });\n\t\treturn this.getData<{ branch: string | null }>(response).branch;\n\t}\n\n\t/**\n\t * Get cached same-day cost across all sessions, primed by the server on first call.\n\t */\n\tasync getDailyCost(): Promise<number> {\n\t\tconst response = await this.send({ type: \"get_daily_cost\" });\n\t\treturn this.getData<{ cost: number }>(response).cost;\n\t}\n\n\t/**\n\t * Set model by provider and ID.\n\t */\n\tasync setModel(provider: string, modelId: string): Promise<{ provider: string; id: string }> {\n\t\tconst response = await this.send({ type: \"set_model\", provider, modelId });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Cycle to next model.\n\t */\n\tasync cycleModel(): Promise<{\n\t\tmodel: { provider: string; id: string };\n\t\tthinkingLevel: ThinkingLevel;\n\t\tisScoped: boolean;\n\t} | null> {\n\t\tconst response = await this.send({ type: \"cycle_model\" });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Get list of available models.\n\t */\n\tasync getAvailableModels(): Promise<ModelInfo[]> {\n\t\tconst response = await this.send({ type: \"get_available_models\" });\n\t\treturn this.getData<{ models: ModelInfo[] }>(response).models;\n\t}\n\n\t/**\n\t * Resolve a model pattern using the same logic as CLI/TUI.\n\t * Runs server-side so API keys never leave the process.\n\t * Returns null if no match found.\n\t */\n\tasync resolveModel(pattern: string): Promise<{ model: ModelInfo; warning?: string } | null> {\n\t\tconst response = await this.send({ type: \"resolve_model\", pattern });\n\t\treturn this.getData<{ model: ModelInfo; warning?: string } | null>(response);\n\t}\n\n\t/**\n\t * Hatch a new buddy companion. Runs inside the agent process\n\t * so API keys never leave the process boundary.\n\t */\n\tasync buddyHatch(): Promise<import(\"../../core/buddy/buddy-types.js\").BuddyState> {\n\t\tconst response = await this.send({ type: \"buddy_hatch\" });\n\t\treturn this.getData<{ state: import(\"../../core/buddy/buddy-types.js\").BuddyState }>(response).state;\n\t}\n\n\t/**\n\t * Reroll the buddy companion. Runs inside the agent process\n\t * so API keys never leave the process boundary.\n\t */\n\tasync buddyReroll(): Promise<import(\"../../core/buddy/buddy-types.js\").BuddyState> {\n\t\tconst response = await this.send({ type: \"buddy_reroll\" });\n\t\treturn this.getData<{ state: import(\"../../core/buddy/buddy-types.js\").BuddyState }>(response).state;\n\t}\n\n\t/**\n\t * Set thinking level.\n\t */\n\tasync setThinkingLevel(level: ThinkingLevel): Promise<void> {\n\t\tawait this.send({ type: \"set_thinking_level\", level });\n\t}\n\n\t/**\n\t * Cycle thinking level.\n\t */\n\tasync cycleThinkingLevel(): Promise<{ level: ThinkingLevel } | null> {\n\t\tconst response = await this.send({ type: \"cycle_thinking_level\" });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Set steering mode.\n\t */\n\tasync setSteeringMode(mode: \"all\" | \"one-at-a-time\"): Promise<void> {\n\t\tawait this.send({ type: \"set_steering_mode\", mode });\n\t}\n\n\t/**\n\t * Set follow-up mode.\n\t */\n\tasync setFollowUpMode(mode: \"all\" | \"one-at-a-time\"): Promise<void> {\n\t\tawait this.send({ type: \"set_follow_up_mode\", mode });\n\t}\n\n\t/**\n\t * Get pending steering and follow-up messages without clearing them.\n\t */\n\tasync getPendingMessages(): Promise<RpcPendingMessages> {\n\t\tconst response = await this.send({ type: \"get_pending_messages\" });\n\t\treturn this.getData<RpcPendingMessages>(response);\n\t}\n\n\t/**\n\t * Clear pending steering and follow-up messages, returning the cleared text.\n\t */\n\tasync clearPendingMessages(): Promise<RpcPendingMessages> {\n\t\tconst response = await this.send({ type: \"clear_pending_messages\" });\n\t\treturn this.getData<RpcPendingMessages>(response);\n\t}\n\n\t/**\n\t * Compact session context.\n\t */\n\tasync compact(customInstructions?: string): Promise<CompactionResult> {\n\t\tconst response = await this.send({ type: \"compact\", customInstructions });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Set auto-compaction enabled/disabled.\n\t */\n\tasync setAutoCompaction(enabled: boolean): Promise<void> {\n\t\tawait this.send({ type: \"set_auto_compaction\", enabled });\n\t}\n\n\t/**\n\t * Abort in-progress compaction.\n\t */\n\tasync abortCompaction(): Promise<void> {\n\t\tawait this.send({ type: \"abort_compaction\" });\n\t}\n\n\t/**\n\t * Set auto-retry enabled/disabled.\n\t */\n\tasync setAutoRetry(enabled: boolean): Promise<void> {\n\t\tawait this.send({ type: \"set_auto_retry\", enabled });\n\t}\n\n\t/**\n\t * Abort in-progress retry.\n\t */\n\tasync abortRetry(): Promise<void> {\n\t\tawait this.send({ type: \"abort_retry\" });\n\t}\n\n\t/**\n\t * Execute a bash command.\n\t */\n\tasync bash(command: string): Promise<BashResult> {\n\t\tconst response = await this.send({ type: \"bash\", command });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Abort running bash command.\n\t */\n\tasync abortBash(): Promise<void> {\n\t\tawait this.send({ type: \"abort_bash\" });\n\t}\n\n\t/**\n\t * Get session statistics.\n\t */\n\tasync getSessionStats(): Promise<SessionStats> {\n\t\tconst response = await this.send({ type: \"get_session_stats\" });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Get performance statistics.\n\t */\n\tasync getPerformanceStats(): Promise<{\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/** Import a JSONL file into the current runtime. */\n\tasync importJsonl(inputPath: string): Promise<{ cancelled: boolean }> {\n\t\tconst response = await this.send({ type: \"import_jsonl\", inputPath });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Switch to a different session file.\n\t * @returns Object with `cancelled: true` if an extension cancelled the switch\n\t */\n\tasync switchSession(sessionPath: string): Promise<{ cancelled: boolean }> {\n\t\tconst response = await this.send({ type: \"switch_session\", sessionPath });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Delete a session file, trying trash first and falling back to unlink.\n\t * Throws on failure, including when attempting to delete the active session.\n\t */\n\tasync deleteSession(sessionPath: string): Promise<{ method: \"trash\" | \"unlink\" }> {\n\t\tconst response = await this.send({ type: \"delete_session\", sessionPath });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Fork from a specific message.\n\t * @returns Object with `text` (the message text) and `cancelled` (if extension cancelled)\n\t */\n\tasync fork(entryId: string): Promise<{ text: string; cancelled: boolean }> {\n\t\tconst response = await this.send({ type: \"fork\", entryId });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Get messages available for forking.\n\t */\n\tasync getForkMessages(): Promise<Array<{ entryId: string; text: string }>> {\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 discoverable commands, including built-ins that require client-side handling.\n\t */\n\tasync getCommands(): Promise<RpcSlashCommand[]> {\n\t\tconst response = await this.send({ type: \"get_commands\" });\n\t\treturn this.getData<{ commands: RpcSlashCommand[] }>(response).commands;\n\t}\n\n\t/**\n\t * List sessions for the current working directory.\n\t * Returns sessions sorted by most recently modified first.\n\t */\n\tasync listSessions(): Promise<RpcSessionInfo[]> {\n\t\tconst response = await this.send({ type: \"list_sessions\" });\n\t\treturn this.getData<{ sessions: RpcSessionInfo[] }>(response).sessions;\n\t}\n\n\t/**\n\t * List sessions across all projects.\n\t * Returns sessions sorted by most recently modified first. May be slow with many sessions.\n\t */\n\tasync listAllSessions(): Promise<RpcSessionInfo[]> {\n\t\tconst response = await this.send({ type: \"list_all_sessions\" });\n\t\treturn this.getData<{ sessions: RpcSessionInfo[] }>(response).sessions;\n\t}\n\n\t/**\n\t * List background subagents tracked by the server's registry (running and\n\t * recently completed), including session dir/file paths where known.\n\t */\n\tasync listBackgroundAgents(): Promise<RpcBackgroundAgentInfo[]> {\n\t\tconst response = await this.send({ type: \"list_background_agents\" });\n\t\treturn this.getData<{ agents: RpcBackgroundAgentInfo[] }>(response).agents;\n\t}\n\n\t/**\n\t * List discoverable subagent types for the server's current working directory.\n\t */\n\tasync listAgentTypes(): Promise<RpcAgentTypeInfo[]> {\n\t\tconst response = await this.send({ type: \"list_agent_types\" });\n\t\treturn this.getData<{ agentTypes: RpcAgentTypeInfo[] }>(response).agentTypes;\n\t}\n\n\t/**\n\t * Answer an extension UI request (select/confirm/input/editor) previously\n\t * received as an `extension_ui_request` event. Fire-and-forget: the server\n\t * does not send a response to this message.\n\t */\n\tsendExtensionUIResponse(response: RpcExtensionUIResponse): void {\n\t\tif (this._dead || !this.process?.stdin) {\n\t\t\tconst cause = this.spawnError ? ` Spawn error: ${this.spawnError.message}.` : \"\";\n\t\t\tthrow new Error(`RPC process is not running.${cause} Stderr: ${this.stderr}`);\n\t\t}\n\t\tthis.process.stdin.write(serializeJsonLine(response));\n\t}\n\n\t/**\n\t * Get the dreb version.\n\t */\n\tasync getVersion(): Promise<string> {\n\t\tconst response = await this.send({ type: \"get_version\" });\n\t\treturn this.getData<{ version: string }>(response).version;\n\t}\n\n\t/**\n\t * Get the persistent default settings (SettingsManager-backed).\n\t * These seed fresh runtimes — for live session state use getState().\n\t */\n\tasync getSettings(): Promise<RpcSettingsSnapshot> {\n\t\tconst response = await this.send({ type: \"get_settings\" });\n\t\treturn this.getData<RpcSettingsSnapshot>(response);\n\t}\n\n\t/**\n\t * Update persistent default settings. Validates the whole payload before applying\n\t * anything (atomic: on any invalid field, nothing changes). Does NOT touch live\n\t * session state — use setModel/setThinkingLevel/etc. for that.\n\t * Returns the full settings snapshot after the write, plus any loud warnings\n\t * (for example project-level agent model overrides shadowing global writes).\n\t */\n\tasync setSettings(settings: RpcSettingsUpdate): Promise<RpcSettingsSetResult> {\n\t\tconst response = await this.send({ type: \"set_settings\", settings });\n\t\treturn this.getData<RpcSettingsSetResult>(response);\n\t}\n\n\t/** Evaluate an existing directory against the server's global context-trust policy. */\n\tasync evaluateContextTrust(path: string): Promise<RpcContextTrustEvaluation> {\n\t\tconst response = await this.send({ type: \"evaluate_context_trust\", path });\n\t\treturn this.getData<RpcContextTrustEvaluation>(response);\n\t}\n\n\t/** Add an existing directory as a canonical global trusted context root. */\n\tasync trustContextFolder(path: string): Promise<RpcContextTrustMutationResult> {\n\t\tconst response = await this.send({ type: \"trust_context_folder\", path });\n\t\treturn this.getData<RpcContextTrustMutationResult>(response);\n\t}\n\n\t/** Remove the root that currently grants the directory context trust. */\n\tasync untrustContextFolder(path: string): Promise<RpcContextTrustMutationResult> {\n\t\tconst response = await this.send({ type: \"untrust_context_folder\", path });\n\t\treturn this.getData<RpcContextTrustMutationResult>(response);\n\t}\n\n\t/** Remove a configured trusted-folder string exactly as stored. */\n\tasync removeTrustedContextFolder(path: string): Promise<RpcTrustedFolderRemovalResult> {\n\t\tconst response = await this.send({ type: \"remove_trusted_context_folder\", path });\n\t\treturn this.getData<RpcTrustedFolderRemovalResult>(response);\n\t}\n\n\t// =========================================================================\n\t// Helpers\n\t// =========================================================================\n\n\t/**\n\t * Wait for agent to become idle (no streaming).\n\t * Resolves when agent_end event is received.\n\t */\n\twaitForIdle(timeout = 60000): Promise<void> {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tunsubscribe();\n\t\t\t\treject(new Error(`Timeout waiting for agent to become idle. Stderr: ${this.stderr}`));\n\t\t\t}, timeout);\n\n\t\t\tconst unsubscribe = this.onEvent((event) => {\n\t\t\t\tif (event.type === \"agent_end\") {\n\t\t\t\t\tclearTimeout(timer);\n\t\t\t\t\tunsubscribe();\n\t\t\t\t\tresolve();\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t}\n\n\t/**\n\t * Collect events until agent becomes idle.\n\t */\n\tcollectEvents(timeout = 60000): Promise<RpcEvent[]> {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst events: RpcEvent[] = [];\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tunsubscribe();\n\t\t\t\treject(new Error(`Timeout collecting events. Stderr: ${this.stderr}`));\n\t\t\t}, timeout);\n\n\t\t\tconst unsubscribe = this.onEvent((event) => {\n\t\t\t\tevents.push(event);\n\t\t\t\tif (event.type === \"agent_end\") {\n\t\t\t\t\tclearTimeout(timer);\n\t\t\t\t\tunsubscribe();\n\t\t\t\t\tresolve(events);\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t}\n\n\t/**\n\t * Send prompt and wait for completion, returning all events.\n\t */\n\tasync promptAndWait(message: string, images?: ImageContent[], timeout = 60000): Promise<RpcEvent[]> {\n\t\tconst eventsPromise = this.collectEvents(timeout);\n\t\tawait this.prompt(message, images);\n\t\treturn eventsPromise;\n\t}\n\n\t// =========================================================================\n\t// Internal\n\t// =========================================================================\n\n\t/**\n\t * Mark the client dead and reject every in-flight request with `message`.\n\t * Shared by the 'exit' and 'error' handlers so both failure paths surface\n\t * loudly and consistently instead of leaving callers hanging.\n\t */\n\tprivate failPendingRequests(message: string): void {\n\t\tthis._dead = true;\n\t\tfor (const pending of this.pendingRequests.values()) {\n\t\t\tpending.reject(new Error(message));\n\t\t}\n\t\tthis.pendingRequests.clear();\n\t}\n\n\tprivate notifyExitListeners(info: RpcExitInfo): void {\n\t\tfor (const listener of this.exitListeners) {\n\t\t\tlistener(info);\n\t\t}\n\t}\n\n\tprivate handleLine(line: string): void {\n\t\ttry {\n\t\t\tconst data: unknown = JSON.parse(line);\n\n\t\t\t// Check if it's a response to a pending request. Unknown/unsolicited\n\t\t\t// response frames are not events and should not be forwarded to listeners.\n\t\t\tif (isRpcResponseMessage(data)) {\n\t\t\t\tif (typeof data.id === \"string\" && this.pendingRequests.has(data.id)) {\n\t\t\t\t\tconst pending = this.pendingRequests.get(data.id)!;\n\t\t\t\t\tthis.pendingRequests.delete(data.id);\n\t\t\t\t\tpending.resolve(data);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (!isRpcEvent(data)) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tfor (const listener of this.eventListeners) {\n\t\t\t\tlistener(data);\n\t\t\t}\n\t\t} catch {\n\t\t\t// Ignore non-JSON lines\n\t\t}\n\t}\n\n\tprivate async send(command: RpcCommandBody, timeoutMs = 30000): Promise<RpcResponse> {\n\t\tif (this._dead || !this.process?.stdin) {\n\t\t\t// Surface the real spawn cause (e.g. uid/gid EPERM) if one was captured,\n\t\t\t// rather than a generic message that hides why the process is gone.\n\t\t\tthrow new Error(\n\t\t\t\tthis.spawnError ? `RPC process not running: ${this.spawnError.message}` : \"RPC process not running\",\n\t\t\t);\n\t\t}\n\n\t\tconst id = `req_${++this.requestId}`;\n\t\tconst fullCommand = { ...command, id } as RpcCommand;\n\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst timeout = setTimeout(() => {\n\t\t\t\tthis.pendingRequests.delete(id);\n\t\t\t\treject(new Error(`Timeout waiting for response to ${command.type}. Stderr: ${this.stderr}`));\n\t\t\t}, timeoutMs);\n\n\t\t\tthis.pendingRequests.set(id, {\n\t\t\t\tresolve: (response) => {\n\t\t\t\t\tclearTimeout(timeout);\n\t\t\t\t\tresolve(response);\n\t\t\t\t},\n\t\t\t\treject: (error) => {\n\t\t\t\t\tclearTimeout(timeout);\n\t\t\t\t\treject(error);\n\t\t\t\t},\n\t\t\t});\n\n\t\t\tthis.process!.stdin!.write(serializeJsonLine(fullCommand));\n\t\t});\n\t}\n\n\tprivate getData<T>(response: RpcResponse): T {\n\t\tif (!response.success) {\n\t\t\tconst errorResponse = response as Extract<RpcResponse, { success: false }>;\n\t\t\tthrow new Error(errorResponse.error);\n\t\t}\n\t\t// Type assertion: we trust response.data matches T based on the command sent.\n\t\t// This is safe because each public method specifies the correct T for its command.\n\t\tconst successResponse = response as Extract<RpcResponse, { success: true; data: unknown }>;\n\t\treturn successResponse.data as T;\n\t}\n}\n"]}
|
|
@@ -240,6 +240,15 @@ export class RpcClient {
|
|
|
240
240
|
const response = await this.send({ type: "new_session", parentSession });
|
|
241
241
|
return this.getData(response);
|
|
242
242
|
}
|
|
243
|
+
/** Reload extensions, skills, prompts, themes, and other session resources. */
|
|
244
|
+
async reload() {
|
|
245
|
+
await this.send({ type: "reload" });
|
|
246
|
+
}
|
|
247
|
+
/** Run `/dream` or one of its backup-path forms. */
|
|
248
|
+
async dream(args) {
|
|
249
|
+
const response = await this.send({ type: "dream", args });
|
|
250
|
+
return this.getData(response);
|
|
251
|
+
}
|
|
243
252
|
/**
|
|
244
253
|
* Get current session state.
|
|
245
254
|
*/
|
|
@@ -427,6 +436,11 @@ export class RpcClient {
|
|
|
427
436
|
const response = await this.send({ type: "export_html", outputPath });
|
|
428
437
|
return this.getData(response);
|
|
429
438
|
}
|
|
439
|
+
/** Import a JSONL file into the current runtime. */
|
|
440
|
+
async importJsonl(inputPath) {
|
|
441
|
+
const response = await this.send({ type: "import_jsonl", inputPath });
|
|
442
|
+
return this.getData(response);
|
|
443
|
+
}
|
|
430
444
|
/**
|
|
431
445
|
* Switch to a different session file.
|
|
432
446
|
* @returns Object with `cancelled: true` if an extension cancelled the switch
|
|
@@ -497,7 +511,7 @@ export class RpcClient {
|
|
|
497
511
|
return this.getData(response).messages;
|
|
498
512
|
}
|
|
499
513
|
/**
|
|
500
|
-
* Get
|
|
514
|
+
* Get discoverable commands, including built-ins that require client-side handling.
|
|
501
515
|
*/
|
|
502
516
|
async getCommands() {
|
|
503
517
|
const response = await this.send({ type: "get_commands" });
|