@dreb/coding-agent 2.55.1 → 2.55.2

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 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, 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, dreb memory editor with exact-revision saves and automatic index cleanup on delete, 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. The Memories screen is dreb-only (`~/.dreb/memory` and populated active/on-disk-session project `.dreb/memory`; empty projects are omitted), shows complete indexes with a >200-line warning, opens local index links within the selected scope, replaces stale editor content with visible loading feedback, surfaces malformed entry frontmatter for repair, preserves drafts on conflicts, and does not create/rename entries or expose Claude paths. 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, a TUI-parity rolling TPS indicator with long-term delta, 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, dreb memory editor with exact-revision saves and automatic index cleanup on delete, 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. The Memories screen is dreb-only (`~/.dreb/memory` and populated active/on-disk-session project `.dreb/memory`; empty projects are omitted), shows complete indexes with a >200-line warning, opens local index links within the selected scope, replaces stale editor content with visible loading feedback, surfaces malformed entry frontmatter for repair, preserves drafts on conflicts, and does not create/rename entries or expose Claude paths. 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
 
@@ -21,6 +21,12 @@ export interface PerformanceDelta {
21
21
  baselineCount: number;
22
22
  recentCount: number;
23
23
  }
24
+ export interface ModelPerformanceSummary {
25
+ provider: string;
26
+ modelId: string;
27
+ rolling: RollingAverage;
28
+ delta: PerformanceDelta;
29
+ }
24
30
  export declare class PerformanceTracker {
25
31
  private static readonly PRUNE_INTERVAL_MS;
26
32
  private static readonly LOCK_TIMEOUT_MS;
@@ -35,13 +41,7 @@ export declare class PerformanceTracker {
35
41
  record(entry: PerformanceEntry): void;
36
42
  getRollingAverage(provider: string, modelId: string, count?: number): RollingAverage;
37
43
  getPerformanceDelta(provider: string, modelId: string, recentCount?: number, baselineCount?: number, stablePercent?: number): PerformanceDelta;
38
- getAllRollingAverages(windowMs?: number): Array<{
39
- provider: string;
40
- modelId: string;
41
- median: number;
42
- mean: number;
43
- count: number;
44
- }>;
44
+ getAllModelSummaries(): ModelPerformanceSummary[];
45
45
  prune(ageMs?: number): void;
46
46
  dispose(): void;
47
47
  private ensureDir;
@@ -1 +1 @@
1
- {"version":3,"file":"performance-tracker.d.ts","sourceRoot":"","sources":["../../src/core/performance-tracker.ts"],"names":[],"mappings":"AAcA,MAAM,WAAW,gBAAgB;IAChC,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;IAChB,YAAY,EAAE,MAAM,CAAC;IACrB,UAAU,EAAE,MAAM,CAAC;IACnB,GAAG,EAAE,MAAM,CAAC;CACZ;AAED,MAAM,WAAW,cAAc;IAC9B,MAAM,E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AAM,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,CAAC,CAyB3F;IAED,KAAK,CAAC,KAAK,SAA2B,GAAG,IAAI,CAsC5C;IAED,OAAO,IAAI,IAAI,CAMd;IAED,OAAO,CAAC,SAAS;IAWjB,OAAO,CAAC,aAAa;IAQrB,OAAO,CAAC,WAAW;IA+BnB,OAAO,CAAC,WAAW;IAcnB,OAAO,CAAC,WAAW;IAgBnB,OAAO,CAAC,eAAe;CAUvB","sourcesContent":["import {\n\tappendFileSync,\n\tcloseSync,\n\tmkdirSync,\n\topenSync,\n\treadFileSync,\n\trenameSync,\n\trmSync,\n\tstatSync,\n\twriteFileSync,\n} from \"fs\";\nimport { dirname, join } from \"path\";\nimport { getPerformanceLogPath } from \"../config.js\";\n\nexport interface PerformanceEntry {\n\ttimestamp: string;\n\tsessionId: string;\n\tprovider: string;\n\tmodelId: string;\n\toutputTokens: number;\n\tdurationMs: number;\n\ttps: number;\n}\n\nexport interface RollingAverage {\n\tmedian: number;\n\tmean: number;\n\tcount: number;\n}\n\nexport type PerformanceDeltaDirection = \"above\" | \"below\" | \"stable\";\n\nexport interface PerformanceDelta {\n\tbaselineMedian: number;\n\trecentMedian: number;\n\tpercentDelta: number;\n\tdirection: PerformanceDeltaDirection;\n\tbaselineCount: number;\n\trecentCount: number;\n}\n\nexport class PerformanceTracker {\n\tprivate static readonly PRUNE_INTERVAL_MS = 24 * 60 * 60 * 1000;\n\tprivate static readonly LOCK_TIMEOUT_MS = 1000;\n\tprivate static readonly PRUNE_LOCK_TIMEOUT_MS = 5000;\n\tprivate static readonly STALE_LOCK_MS = 5 * 60 * 1000;\n\n\tprivate logPath: string;\n\tprivate lockPath: string;\n\tprivate entries: PerformanceEntry[];\n\tprivate pruneTimer: ReturnType<typeof setInterval> | null = null;\n\tprivate disposed = false;\n\n\tconstructor(logPath?: string) {\n\t\tthis.logPath = logPath ?? getPerformanceLogPath();\n\t\tthis.lockPath = `${this.logPath}.lock`;\n\t\ttry {\n\t\t\tthis.entries = this.readEntries();\n\t\t} catch {\n\t\t\tthis.entries = [];\n\t\t}\n\t\tthis.ensureDir();\n\t\tthis.schedulePrune();\n\t}\n\n\trecord(entry: PerformanceEntry): void {\n\t\tif (this.disposed) return;\n\t\ttry {\n\t\t\tconst wrote = this.withLogLock(() => {\n\t\t\t\tappendFileSync(this.logPath, `${JSON.stringify(entry)}\\n`, \"utf8\");\n\t\t\t\treturn true;\n\t\t\t});\n\t\t\tif (!wrote) {\n\t\t\t\tconsole.warn(\"[PerformanceTracker] Failed to write performance entry: could not acquire log lock\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.entries.push(entry);\n\t\t} catch (error) {\n\t\t\tconsole.warn(`[PerformanceTracker] Failed to write performance entry: ${error}`);\n\t\t}\n\t}\n\n\tgetRollingAverage(provider: string, modelId: string, count = 100): RollingAverage {\n\t\tconst values = this.entries\n\t\t\t.filter((e) => e.provider === provider && e.modelId === modelId)\n\t\t\t.sort((a, b) => entryTime(b) - entryTime(a))\n\t\t\t.slice(0, count)\n\t\t\t.map((e) => e.tps);\n\n\t\tif (values.length === 0) {\n\t\t\treturn { median: 0, mean: 0, count: 0 };\n\t\t}\n\n\t\treturn {\n\t\t\tmedian: computeMedian(values),\n\t\t\tmean: computeMean(values),\n\t\t\tcount: values.length,\n\t\t};\n\t}\n\n\tgetPerformanceDelta(\n\t\tprovider: string,\n\t\tmodelId: string,\n\t\trecentCount = 10,\n\t\tbaselineCount = 10_000,\n\t\tstablePercent = 1,\n\t): PerformanceDelta {\n\t\tconst modelEntries = this.entries\n\t\t\t.filter((e) => e.provider === provider && e.modelId === modelId)\n\t\t\t.sort((a, b) => entryTime(b) - entryTime(a));\n\n\t\tconst baselineSlice = baselineCount > 0 ? baselineCount : modelEntries.length;\n\t\tconst baselineValues = modelEntries.slice(0, baselineSlice).map((e) => e.tps);\n\t\tconst recentValues = modelEntries.slice(0, recentCount).map((e) => e.tps);\n\n\t\tconst baselineMedian = computeMedian(baselineValues);\n\t\tconst recentMedian = computeMedian(recentValues);\n\t\tif (baselineValues.length < 3 || recentValues.length < 3 || baselineMedian <= 0) {\n\t\t\treturn {\n\t\t\t\tbaselineMedian,\n\t\t\t\trecentMedian,\n\t\t\t\tpercentDelta: 0,\n\t\t\t\tdirection: \"stable\",\n\t\t\t\tbaselineCount: baselineValues.length,\n\t\t\t\trecentCount: recentValues.length,\n\t\t\t};\n\t\t}\n\n\t\tconst percentDelta = ((recentMedian - baselineMedian) / baselineMedian) * 100;\n\t\tconst direction = Math.abs(percentDelta) < stablePercent ? \"stable\" : percentDelta > 0 ? \"above\" : \"below\";\n\n\t\treturn {\n\t\t\tbaselineMedian,\n\t\t\trecentMedian,\n\t\t\tpercentDelta,\n\t\t\tdirection,\n\t\t\tbaselineCount: baselineValues.length,\n\t\t\trecentCount: recentValues.length,\n\t\t};\n\t}\n\n\tgetAllRollingAverages(\n\t\twindowMs = 24 * 60 * 60 * 1000,\n\t): Array<{ provider: string; modelId: string; median: number; mean: number; count: number }> {\n\t\tconst cutoff = Date.now() - windowMs;\n\t\tconst filtered = this.entries.filter((e) => entryTime(e) >= cutoff);\n\n\t\tconst groups = new Map<string, number[]>();\n\t\tfor (const entry of filtered) {\n\t\t\tconst key = `${entry.provider}\\0${entry.modelId}`;\n\t\t\tconst arr = groups.get(key) ?? [];\n\t\t\tarr.push(entry.tps);\n\t\t\tgroups.set(key, arr);\n\t\t}\n\n\t\tconst results: Array<{ provider: string; modelId: string; median: number; mean: number; count: number }> = [];\n\t\tfor (const [key, values] of groups) {\n\t\t\tconst [provider, modelId] = key.split(\"\\0\");\n\t\t\tresults.push({\n\t\t\t\tprovider,\n\t\t\t\tmodelId,\n\t\t\t\tmedian: computeMedian(values),\n\t\t\t\tmean: computeMean(values),\n\t\t\t\tcount: values.length,\n\t\t\t});\n\t\t}\n\n\t\treturn results;\n\t}\n\n\tprune(ageMs = 30 * 24 * 60 * 60 * 1000): void {\n\t\tif (this.disposed) return;\n\t\tlet tempPath: string | undefined;\n\t\ttry {\n\t\t\tconst pruned = this.withLogLock(() => {\n\t\t\t\tconst cutoff = Date.now() - ageMs;\n\t\t\t\tconst sourceEntries = this.readEntries();\n\t\t\t\tconst kept: PerformanceEntry[] = [];\n\t\t\t\tconst lines: string[] = [];\n\n\t\t\t\tfor (const entry of sourceEntries) {\n\t\t\t\t\tif (entryTime(entry) >= cutoff) {\n\t\t\t\t\t\tkept.push(entry);\n\t\t\t\t\t\tlines.push(JSON.stringify(entry));\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\ttempPath = join(dirname(this.logPath), `.performance-prune-${process.pid}-${Date.now()}.jsonl`);\n\t\t\t\twriteFileSync(tempPath, lines.length > 0 ? `${lines.join(\"\\n\")}\\n` : \"\", \"utf8\");\n\t\t\t\trenameSync(tempPath, this.logPath);\n\t\t\t\ttempPath = undefined;\n\t\t\t\tthis.entries = kept;\n\t\t\t\treturn true;\n\t\t\t}, PerformanceTracker.PRUNE_LOCK_TIMEOUT_MS);\n\t\t\tif (!pruned) {\n\t\t\t\tconsole.warn(\"[PerformanceTracker] Failed to prune performance log: could not acquire log lock\");\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tconsole.warn(`[PerformanceTracker] Failed to prune performance log: ${error}`);\n\t\t} finally {\n\t\t\tif (tempPath) {\n\t\t\t\ttry {\n\t\t\t\t\trmSync(tempPath, { force: true });\n\t\t\t\t} catch {\n\t\t\t\t\t// Best-effort cleanup only\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tdispose(): void {\n\t\tthis.disposed = true;\n\t\tif (this.pruneTimer) {\n\t\t\tclearInterval(this.pruneTimer);\n\t\t\tthis.pruneTimer = null;\n\t\t}\n\t}\n\n\tprivate ensureDir(): void {\n\t\ttry {\n\t\t\tmkdirSync(dirname(this.logPath), { recursive: true });\n\t\t} catch (error) {\n\t\t\tif (isFileExistsError(error)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconsole.warn(`[PerformanceTracker] Failed to create log directory: ${error}`);\n\t\t}\n\t}\n\n\tprivate schedulePrune(): void {\n\t\tif (this.disposed) return;\n\t\tthis.pruneTimer = setInterval(() => {\n\t\t\tthis.prune();\n\t\t}, PerformanceTracker.PRUNE_INTERVAL_MS);\n\t\tthis.pruneTimer?.unref?.();\n\t}\n\n\tprivate readEntries(): PerformanceEntry[] {\n\t\ttry {\n\t\t\tconst content = readFileSync(this.logPath, \"utf8\");\n\t\t\tconst entries: PerformanceEntry[] = [];\n\t\t\tfor (const line of content.split(\"\\n\")) {\n\t\t\t\tif (!line.trim()) continue;\n\t\t\t\ttry {\n\t\t\t\t\tconst parsed = JSON.parse(line) as unknown;\n\t\t\t\t\tif (!isValidPerformanceEntry(parsed)) {\n\t\t\t\t\t\tconsole.warn(`[PerformanceTracker] Skipping invalid performance entry line: ${line}`);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tconst time = entryTime(parsed);\n\t\t\t\t\tif (!Number.isFinite(time)) {\n\t\t\t\t\t\tconsole.warn(`[PerformanceTracker] Skipping entry with invalid timestamp: ${line}`);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tentries.push(parsed);\n\t\t\t\t} catch {\n\t\t\t\t\t// Skip malformed lines\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn entries;\n\t\t} catch (error) {\n\t\t\tif (isENOENT(error)) {\n\t\t\t\treturn [];\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tprivate withLogLock<T>(operation: () => T, timeoutMs = PerformanceTracker.LOCK_TIMEOUT_MS): T | undefined {\n\t\tconst fd = this.acquireLock(timeoutMs);\n\t\tif (fd === undefined) return undefined;\n\t\ttry {\n\t\t\treturn operation();\n\t\t} finally {\n\t\t\ttry {\n\t\t\t\tcloseSync(fd);\n\t\t\t} finally {\n\t\t\t\trmSync(this.lockPath, { force: true });\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate acquireLock(timeoutMs: number): number | undefined {\n\t\tconst start = performance.now();\n\t\twhile (performance.now() - start <= timeoutMs) {\n\t\t\ttry {\n\t\t\t\treturn openSync(this.lockPath, \"wx\");\n\t\t\t} catch (error) {\n\t\t\t\tif (!isFileExistsError(error)) {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tthis.removeStaleLock();\n\t\t\t\tsleepSync(10);\n\t\t\t}\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tprivate removeStaleLock(): void {\n\t\ttry {\n\t\t\tconst lockAgeMs = Date.now() - statSync(this.lockPath).mtimeMs;\n\t\t\tif (lockAgeMs > PerformanceTracker.STALE_LOCK_MS) {\n\t\t\t\trmSync(this.lockPath, { force: true });\n\t\t\t}\n\t\t} catch {\n\t\t\t// Lock disappeared between open attempts\n\t\t}\n\t}\n}\n\nfunction entryTime(entry: PerformanceEntry): number {\n\tconst time = new Date(entry.timestamp).getTime();\n\treturn Number.isFinite(time) ? time : NaN;\n}\n\nfunction computeMedian(values: number[]): number {\n\tif (values.length === 0) return 0;\n\tconst sorted = [...values].sort((a, b) => a - b);\n\tconst mid = Math.floor(sorted.length / 2);\n\tif (sorted.length % 2 === 1) {\n\t\treturn sorted[mid];\n\t}\n\treturn (sorted[mid - 1] + sorted[mid]) / 2;\n}\n\nfunction computeMean(values: number[]): number {\n\tif (values.length === 0) return 0;\n\treturn values.reduce((a, b) => a + b, 0) / values.length;\n}\n\nfunction isFileExistsError(error: unknown): boolean {\n\treturn typeof error === \"object\" && error !== null && \"code\" in error && error.code === \"EEXIST\";\n}\n\nfunction isENOENT(error: unknown): boolean {\n\treturn typeof error === \"object\" && error !== null && \"code\" in error && error.code === \"ENOENT\";\n}\n\nfunction isValidPerformanceEntry(entry: unknown): entry is PerformanceEntry {\n\tif (typeof entry !== \"object\" || entry === null) return false;\n\tconst e = entry as Record<string, unknown>;\n\treturn (\n\t\ttypeof e.timestamp === \"string\" &&\n\t\ttypeof e.provider === \"string\" &&\n\t\ttypeof e.modelId === \"string\" &&\n\t\ttypeof e.outputTokens === \"number\" &&\n\t\tNumber.isFinite(e.outputTokens) &&\n\t\ttypeof e.durationMs === \"number\" &&\n\t\tNumber.isFinite(e.durationMs) &&\n\t\ttypeof e.tps === \"number\" &&\n\t\tNumber.isFinite(e.tps)\n\t);\n}\n\nfunction sleepSync(ms: number): void {\n\tAtomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);\n}\n"]}
1
+ {"version":3,"file":"performance-tracker.d.ts","sourceRoot":"","sources":["../../src/core/performance-tracker.ts"],"names":[],"mappings":"AAcA,MAAM,WAAW,gBAAgB;IAChC,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;IAChB,YAAY,EAAE,MAAM,CAAC;IACrB,UAAU,EAAE,MAAM,CAAC;IACnB,GAAG,EAAE,MAAM,CAAC;CACZ;AAED,MAAM,WAAW,cAAc;IAC9B,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;CACd;AAED,MAAM,MAAM,yBAAyB,GAAG,OAAO,GAAG,OAAO,GAAG,QAAQ,CAAC;AAErE,MAAM,WAAW,gBAAgB;IAChC,cAAc,EAAE,MAAM,CAAC;IACvB,YAAY,EAAE,MAAM,CAAC;IACrB,YAAY,EAAE,MAAM,CAAC;IACrB,SAAS,EAAE,yBAAyB,CAAC;IACrC,aAAa,EAAE,MAAM,CAAC;IACtB,WAAW,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,uBAAuB;IACvC,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,cAAc,CAAC;IACxB,KAAK,EAAE,gBAAgB,CAAC;CACxB;AAED,qBAAa,kBAAkB;IAC9B,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,iBAAiB,CAAuB;IAChE,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,eAAe,CAAQ;IAC/C,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,qBAAqB,CAAQ;IACrD,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,aAAa,CAAiB;IAEtD,OAAO,CAAC,OAAO,CAAS;IACxB,OAAO,CAAC,QAAQ,CAAS;IACzB,OAAO,CAAC,OAAO,CAAqB;IACpC,OAAO,CAAC,UAAU,CAA+C;IACjE,OAAO,CAAC,QAAQ,CAAS;IAEzB,YAAY,OAAO,CAAC,EAAE,MAAM,EAU3B;IAED,MAAM,CAAC,KAAK,EAAE,gBAAgB,GAAG,IAAI,CAepC;IAED,iBAAiB,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,SAAM,GAAG,cAAc,CAgBhF;IAED,mBAAmB,CAClB,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,MAAM,EACf,WAAW,SAAK,EAChB,aAAa,SAAS,EACtB,aAAa,SAAI,GACf,gBAAgB,CAiClB;IAED,oBAAoB,IAAI,uBAAuB,EAAE,CAehD;IAED,KAAK,CAAC,KAAK,SAA2B,GAAG,IAAI,CAsC5C;IAED,OAAO,IAAI,IAAI,CAMd;IAED,OAAO,CAAC,SAAS;IAWjB,OAAO,CAAC,aAAa;IAQrB,OAAO,CAAC,WAAW;IA+BnB,OAAO,CAAC,WAAW;IAcnB,OAAO,CAAC,WAAW;IAgBnB,OAAO,CAAC,eAAe;CAUvB","sourcesContent":["import {\n\tappendFileSync,\n\tcloseSync,\n\tmkdirSync,\n\topenSync,\n\treadFileSync,\n\trenameSync,\n\trmSync,\n\tstatSync,\n\twriteFileSync,\n} from \"fs\";\nimport { dirname, join } from \"path\";\nimport { getPerformanceLogPath } from \"../config.js\";\n\nexport interface PerformanceEntry {\n\ttimestamp: string;\n\tsessionId: string;\n\tprovider: string;\n\tmodelId: string;\n\toutputTokens: number;\n\tdurationMs: number;\n\ttps: number;\n}\n\nexport interface RollingAverage {\n\tmedian: number;\n\tmean: number;\n\tcount: number;\n}\n\nexport type PerformanceDeltaDirection = \"above\" | \"below\" | \"stable\";\n\nexport interface PerformanceDelta {\n\tbaselineMedian: number;\n\trecentMedian: number;\n\tpercentDelta: number;\n\tdirection: PerformanceDeltaDirection;\n\tbaselineCount: number;\n\trecentCount: number;\n}\n\nexport interface ModelPerformanceSummary {\n\tprovider: string;\n\tmodelId: string;\n\trolling: RollingAverage;\n\tdelta: PerformanceDelta;\n}\n\nexport class PerformanceTracker {\n\tprivate static readonly PRUNE_INTERVAL_MS = 24 * 60 * 60 * 1000;\n\tprivate static readonly LOCK_TIMEOUT_MS = 1000;\n\tprivate static readonly PRUNE_LOCK_TIMEOUT_MS = 5000;\n\tprivate static readonly STALE_LOCK_MS = 5 * 60 * 1000;\n\n\tprivate logPath: string;\n\tprivate lockPath: string;\n\tprivate entries: PerformanceEntry[];\n\tprivate pruneTimer: ReturnType<typeof setInterval> | null = null;\n\tprivate disposed = false;\n\n\tconstructor(logPath?: string) {\n\t\tthis.logPath = logPath ?? getPerformanceLogPath();\n\t\tthis.lockPath = `${this.logPath}.lock`;\n\t\ttry {\n\t\t\tthis.entries = this.readEntries();\n\t\t} catch {\n\t\t\tthis.entries = [];\n\t\t}\n\t\tthis.ensureDir();\n\t\tthis.schedulePrune();\n\t}\n\n\trecord(entry: PerformanceEntry): void {\n\t\tif (this.disposed) return;\n\t\ttry {\n\t\t\tconst wrote = this.withLogLock(() => {\n\t\t\t\tappendFileSync(this.logPath, `${JSON.stringify(entry)}\\n`, \"utf8\");\n\t\t\t\treturn true;\n\t\t\t});\n\t\t\tif (!wrote) {\n\t\t\t\tconsole.warn(\"[PerformanceTracker] Failed to write performance entry: could not acquire log lock\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.entries.push(entry);\n\t\t} catch (error) {\n\t\t\tconsole.warn(`[PerformanceTracker] Failed to write performance entry: ${error}`);\n\t\t}\n\t}\n\n\tgetRollingAverage(provider: string, modelId: string, count = 100): RollingAverage {\n\t\tconst values = this.entries\n\t\t\t.filter((e) => e.provider === provider && e.modelId === modelId)\n\t\t\t.sort((a, b) => entryTime(b) - entryTime(a))\n\t\t\t.slice(0, count)\n\t\t\t.map((e) => e.tps);\n\n\t\tif (values.length === 0) {\n\t\t\treturn { median: 0, mean: 0, count: 0 };\n\t\t}\n\n\t\treturn {\n\t\t\tmedian: computeMedian(values),\n\t\t\tmean: computeMean(values),\n\t\t\tcount: values.length,\n\t\t};\n\t}\n\n\tgetPerformanceDelta(\n\t\tprovider: string,\n\t\tmodelId: string,\n\t\trecentCount = 10,\n\t\tbaselineCount = 10_000,\n\t\tstablePercent = 1,\n\t): PerformanceDelta {\n\t\tconst modelEntries = this.entries\n\t\t\t.filter((e) => e.provider === provider && e.modelId === modelId)\n\t\t\t.sort((a, b) => entryTime(b) - entryTime(a));\n\n\t\tconst baselineSlice = baselineCount > 0 ? baselineCount : modelEntries.length;\n\t\tconst baselineValues = modelEntries.slice(0, baselineSlice).map((e) => e.tps);\n\t\tconst recentValues = modelEntries.slice(0, recentCount).map((e) => e.tps);\n\n\t\tconst baselineMedian = computeMedian(baselineValues);\n\t\tconst recentMedian = computeMedian(recentValues);\n\t\tif (baselineValues.length < 3 || recentValues.length < 3 || baselineMedian <= 0) {\n\t\t\treturn {\n\t\t\t\tbaselineMedian,\n\t\t\t\trecentMedian,\n\t\t\t\tpercentDelta: 0,\n\t\t\t\tdirection: \"stable\",\n\t\t\t\tbaselineCount: baselineValues.length,\n\t\t\t\trecentCount: recentValues.length,\n\t\t\t};\n\t\t}\n\n\t\tconst percentDelta = ((recentMedian - baselineMedian) / baselineMedian) * 100;\n\t\tconst direction = Math.abs(percentDelta) < stablePercent ? \"stable\" : percentDelta > 0 ? \"above\" : \"below\";\n\n\t\treturn {\n\t\t\tbaselineMedian,\n\t\t\trecentMedian,\n\t\t\tpercentDelta,\n\t\t\tdirection,\n\t\t\tbaselineCount: baselineValues.length,\n\t\t\trecentCount: recentValues.length,\n\t\t};\n\t}\n\n\tgetAllModelSummaries(): ModelPerformanceSummary[] {\n\t\tconst models = new Map<string, { provider: string; modelId: string }>();\n\t\tfor (const entry of this.entries) {\n\t\t\tconst key = `${entry.provider}\\0${entry.modelId}`;\n\t\t\tif (!models.has(key)) {\n\t\t\t\tmodels.set(key, { provider: entry.provider, modelId: entry.modelId });\n\t\t\t}\n\t\t}\n\n\t\treturn Array.from(models.values(), ({ provider, modelId }) => ({\n\t\t\tprovider,\n\t\t\tmodelId,\n\t\t\trolling: this.getRollingAverage(provider, modelId),\n\t\t\tdelta: this.getPerformanceDelta(provider, modelId),\n\t\t}));\n\t}\n\n\tprune(ageMs = 30 * 24 * 60 * 60 * 1000): void {\n\t\tif (this.disposed) return;\n\t\tlet tempPath: string | undefined;\n\t\ttry {\n\t\t\tconst pruned = this.withLogLock(() => {\n\t\t\t\tconst cutoff = Date.now() - ageMs;\n\t\t\t\tconst sourceEntries = this.readEntries();\n\t\t\t\tconst kept: PerformanceEntry[] = [];\n\t\t\t\tconst lines: string[] = [];\n\n\t\t\t\tfor (const entry of sourceEntries) {\n\t\t\t\t\tif (entryTime(entry) >= cutoff) {\n\t\t\t\t\t\tkept.push(entry);\n\t\t\t\t\t\tlines.push(JSON.stringify(entry));\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\ttempPath = join(dirname(this.logPath), `.performance-prune-${process.pid}-${Date.now()}.jsonl`);\n\t\t\t\twriteFileSync(tempPath, lines.length > 0 ? `${lines.join(\"\\n\")}\\n` : \"\", \"utf8\");\n\t\t\t\trenameSync(tempPath, this.logPath);\n\t\t\t\ttempPath = undefined;\n\t\t\t\tthis.entries = kept;\n\t\t\t\treturn true;\n\t\t\t}, PerformanceTracker.PRUNE_LOCK_TIMEOUT_MS);\n\t\t\tif (!pruned) {\n\t\t\t\tconsole.warn(\"[PerformanceTracker] Failed to prune performance log: could not acquire log lock\");\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tconsole.warn(`[PerformanceTracker] Failed to prune performance log: ${error}`);\n\t\t} finally {\n\t\t\tif (tempPath) {\n\t\t\t\ttry {\n\t\t\t\t\trmSync(tempPath, { force: true });\n\t\t\t\t} catch {\n\t\t\t\t\t// Best-effort cleanup only\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tdispose(): void {\n\t\tthis.disposed = true;\n\t\tif (this.pruneTimer) {\n\t\t\tclearInterval(this.pruneTimer);\n\t\t\tthis.pruneTimer = null;\n\t\t}\n\t}\n\n\tprivate ensureDir(): void {\n\t\ttry {\n\t\t\tmkdirSync(dirname(this.logPath), { recursive: true });\n\t\t} catch (error) {\n\t\t\tif (isFileExistsError(error)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconsole.warn(`[PerformanceTracker] Failed to create log directory: ${error}`);\n\t\t}\n\t}\n\n\tprivate schedulePrune(): void {\n\t\tif (this.disposed) return;\n\t\tthis.pruneTimer = setInterval(() => {\n\t\t\tthis.prune();\n\t\t}, PerformanceTracker.PRUNE_INTERVAL_MS);\n\t\tthis.pruneTimer?.unref?.();\n\t}\n\n\tprivate readEntries(): PerformanceEntry[] {\n\t\ttry {\n\t\t\tconst content = readFileSync(this.logPath, \"utf8\");\n\t\t\tconst entries: PerformanceEntry[] = [];\n\t\t\tfor (const line of content.split(\"\\n\")) {\n\t\t\t\tif (!line.trim()) continue;\n\t\t\t\ttry {\n\t\t\t\t\tconst parsed = JSON.parse(line) as unknown;\n\t\t\t\t\tif (!isValidPerformanceEntry(parsed)) {\n\t\t\t\t\t\tconsole.warn(`[PerformanceTracker] Skipping invalid performance entry line: ${line}`);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tconst time = entryTime(parsed);\n\t\t\t\t\tif (!Number.isFinite(time)) {\n\t\t\t\t\t\tconsole.warn(`[PerformanceTracker] Skipping entry with invalid timestamp: ${line}`);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tentries.push(parsed);\n\t\t\t\t} catch {\n\t\t\t\t\t// Skip malformed lines\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn entries;\n\t\t} catch (error) {\n\t\t\tif (isENOENT(error)) {\n\t\t\t\treturn [];\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tprivate withLogLock<T>(operation: () => T, timeoutMs = PerformanceTracker.LOCK_TIMEOUT_MS): T | undefined {\n\t\tconst fd = this.acquireLock(timeoutMs);\n\t\tif (fd === undefined) return undefined;\n\t\ttry {\n\t\t\treturn operation();\n\t\t} finally {\n\t\t\ttry {\n\t\t\t\tcloseSync(fd);\n\t\t\t} finally {\n\t\t\t\trmSync(this.lockPath, { force: true });\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate acquireLock(timeoutMs: number): number | undefined {\n\t\tconst start = performance.now();\n\t\twhile (performance.now() - start <= timeoutMs) {\n\t\t\ttry {\n\t\t\t\treturn openSync(this.lockPath, \"wx\");\n\t\t\t} catch (error) {\n\t\t\t\tif (!isFileExistsError(error)) {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tthis.removeStaleLock();\n\t\t\t\tsleepSync(10);\n\t\t\t}\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tprivate removeStaleLock(): void {\n\t\ttry {\n\t\t\tconst lockAgeMs = Date.now() - statSync(this.lockPath).mtimeMs;\n\t\t\tif (lockAgeMs > PerformanceTracker.STALE_LOCK_MS) {\n\t\t\t\trmSync(this.lockPath, { force: true });\n\t\t\t}\n\t\t} catch {\n\t\t\t// Lock disappeared between open attempts\n\t\t}\n\t}\n}\n\nfunction entryTime(entry: PerformanceEntry): number {\n\tconst time = new Date(entry.timestamp).getTime();\n\treturn Number.isFinite(time) ? time : NaN;\n}\n\nfunction computeMedian(values: number[]): number {\n\tif (values.length === 0) return 0;\n\tconst sorted = [...values].sort((a, b) => a - b);\n\tconst mid = Math.floor(sorted.length / 2);\n\tif (sorted.length % 2 === 1) {\n\t\treturn sorted[mid];\n\t}\n\treturn (sorted[mid - 1] + sorted[mid]) / 2;\n}\n\nfunction computeMean(values: number[]): number {\n\tif (values.length === 0) return 0;\n\treturn values.reduce((a, b) => a + b, 0) / values.length;\n}\n\nfunction isFileExistsError(error: unknown): boolean {\n\treturn typeof error === \"object\" && error !== null && \"code\" in error && error.code === \"EEXIST\";\n}\n\nfunction isENOENT(error: unknown): boolean {\n\treturn typeof error === \"object\" && error !== null && \"code\" in error && error.code === \"ENOENT\";\n}\n\nfunction isValidPerformanceEntry(entry: unknown): entry is PerformanceEntry {\n\tif (typeof entry !== \"object\" || entry === null) return false;\n\tconst e = entry as Record<string, unknown>;\n\treturn (\n\t\ttypeof e.timestamp === \"string\" &&\n\t\ttypeof e.provider === \"string\" &&\n\t\ttypeof e.modelId === \"string\" &&\n\t\ttypeof e.outputTokens === \"number\" &&\n\t\tNumber.isFinite(e.outputTokens) &&\n\t\ttypeof e.durationMs === \"number\" &&\n\t\tNumber.isFinite(e.durationMs) &&\n\t\ttypeof e.tps === \"number\" &&\n\t\tNumber.isFinite(e.tps)\n\t);\n}\n\nfunction sleepSync(ms: number): void {\n\tAtomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);\n}\n"]}
@@ -86,28 +86,20 @@ export class PerformanceTracker {
86
86
  recentCount: recentValues.length,
87
87
  };
88
88
  }
89
- getAllRollingAverages(windowMs = 24 * 60 * 60 * 1000) {
90
- const cutoff = Date.now() - windowMs;
91
- const filtered = this.entries.filter((e) => entryTime(e) >= cutoff);
92
- const groups = new Map();
93
- for (const entry of filtered) {
89
+ getAllModelSummaries() {
90
+ const models = new Map();
91
+ for (const entry of this.entries) {
94
92
  const key = `${entry.provider}\0${entry.modelId}`;
95
- const arr = groups.get(key) ?? [];
96
- arr.push(entry.tps);
97
- groups.set(key, arr);
98
- }
99
- const results = [];
100
- for (const [key, values] of groups) {
101
- const [provider, modelId] = key.split("\0");
102
- results.push({
103
- provider,
104
- modelId,
105
- median: computeMedian(values),
106
- mean: computeMean(values),
107
- count: values.length,
108
- });
93
+ if (!models.has(key)) {
94
+ models.set(key, { provider: entry.provider, modelId: entry.modelId });
95
+ }
109
96
  }
110
- return results;
97
+ return Array.from(models.values(), ({ provider, modelId }) => ({
98
+ provider,
99
+ modelId,
100
+ rolling: this.getRollingAverage(provider, modelId),
101
+ delta: this.getPerformanceDelta(provider, modelId),
102
+ }));
111
103
  }
112
104
  prune(ageMs = 30 * 24 * 60 * 60 * 1000) {
113
105
  if (this.disposed)
@@ -1 +1 @@
1
- {"version":3,"file":"performance-tracker.js","sourceRoot":"","sources":["../../src/core/performance-tracker.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,cAAc,EACd,SAAS,EACT,SAAS,EACT,QAAQ,EACR,YAAY,EACZ,UAAU,EACV,MAAM,EACN,QAAQ,EACR,aAAa,GACb,MAAM,IAAI,CAAC;AACZ,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AACrC,OAAO,EAAE,qBAAqB,EAAE,MAAM,cAAc,CAAC;AA6BrD,MAAM,OAAO,kBAAkB;IACtB,MAAM,CAAU,iBAAiB,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;IACxD,MAAM,CAAU,eAAe,GAAG,IAAI,CAAC;IACvC,MAAM,CAAU,qBAAqB,GAAG,IAAI,CAAC;IAC7C,MAAM,CAAU,aAAa,GAAG,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC;IAE9C,OAAO,CAAS;IAChB,QAAQ,CAAS;IACjB,OAAO,CAAqB;IAC5B,UAAU,GAA0C,IAAI,CAAC;IACzD,QAAQ,GAAG,KAAK,CAAC;IAEzB,YAAY,OAAgB,EAAE;QAC7B,IAAI,CAAC,OAAO,GAAG,OAAO,IAAI,qBAAqB,EAAE,CAAC;QAClD,IAAI,CAAC,QAAQ,GAAG,GAAG,IAAI,CAAC,OAAO,OAAO,C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,KAAK,QAAQ;QAC9B,OAAO,CAAC,CAAC,OAAO,KAAK,QAAQ;QAC7B,OAAO,CAAC,CAAC,YAAY,KAAK,QAAQ;QAClC,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,YAAY,CAAC;QAC/B,OAAO,CAAC,CAAC,UAAU,KAAK,QAAQ;QAChC,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,UAAU,CAAC;QAC7B,OAAO,CAAC,CAAC,GAAG,KAAK,QAAQ;QACzB,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,GAAG,CAAC,CACtB,CAAC;AAAA,CACF;AAED,SAAS,SAAS,CAAC,EAAU,EAAQ;IACpC,OAAO,CAAC,IAAI,CAAC,IAAI,UAAU,CAAC,IAAI,iBAAiB,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC;AAAA,CACjE","sourcesContent":["import {\n\tappendFileSync,\n\tcloseSync,\n\tmkdirSync,\n\topenSync,\n\treadFileSync,\n\trenameSync,\n\trmSync,\n\tstatSync,\n\twriteFileSync,\n} from \"fs\";\nimport { dirname, join } from \"path\";\nimport { getPerformanceLogPath } from \"../config.js\";\n\nexport interface PerformanceEntry {\n\ttimestamp: string;\n\tsessionId: string;\n\tprovider: string;\n\tmodelId: string;\n\toutputTokens: number;\n\tdurationMs: number;\n\ttps: number;\n}\n\nexport interface RollingAverage {\n\tmedian: number;\n\tmean: number;\n\tcount: number;\n}\n\nexport type PerformanceDeltaDirection = \"above\" | \"below\" | \"stable\";\n\nexport interface PerformanceDelta {\n\tbaselineMedian: number;\n\trecentMedian: number;\n\tpercentDelta: number;\n\tdirection: PerformanceDeltaDirection;\n\tbaselineCount: number;\n\trecentCount: number;\n}\n\nexport class PerformanceTracker {\n\tprivate static readonly PRUNE_INTERVAL_MS = 24 * 60 * 60 * 1000;\n\tprivate static readonly LOCK_TIMEOUT_MS = 1000;\n\tprivate static readonly PRUNE_LOCK_TIMEOUT_MS = 5000;\n\tprivate static readonly STALE_LOCK_MS = 5 * 60 * 1000;\n\n\tprivate logPath: string;\n\tprivate lockPath: string;\n\tprivate entries: PerformanceEntry[];\n\tprivate pruneTimer: ReturnType<typeof setInterval> | null = null;\n\tprivate disposed = false;\n\n\tconstructor(logPath?: string) {\n\t\tthis.logPath = logPath ?? getPerformanceLogPath();\n\t\tthis.lockPath = `${this.logPath}.lock`;\n\t\ttry {\n\t\t\tthis.entries = this.readEntries();\n\t\t} catch {\n\t\t\tthis.entries = [];\n\t\t}\n\t\tthis.ensureDir();\n\t\tthis.schedulePrune();\n\t}\n\n\trecord(entry: PerformanceEntry): void {\n\t\tif (this.disposed) return;\n\t\ttry {\n\t\t\tconst wrote = this.withLogLock(() => {\n\t\t\t\tappendFileSync(this.logPath, `${JSON.stringify(entry)}\\n`, \"utf8\");\n\t\t\t\treturn true;\n\t\t\t});\n\t\t\tif (!wrote) {\n\t\t\t\tconsole.warn(\"[PerformanceTracker] Failed to write performance entry: could not acquire log lock\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.entries.push(entry);\n\t\t} catch (error) {\n\t\t\tconsole.warn(`[PerformanceTracker] Failed to write performance entry: ${error}`);\n\t\t}\n\t}\n\n\tgetRollingAverage(provider: string, modelId: string, count = 100): RollingAverage {\n\t\tconst values = this.entries\n\t\t\t.filter((e) => e.provider === provider && e.modelId === modelId)\n\t\t\t.sort((a, b) => entryTime(b) - entryTime(a))\n\t\t\t.slice(0, count)\n\t\t\t.map((e) => e.tps);\n\n\t\tif (values.length === 0) {\n\t\t\treturn { median: 0, mean: 0, count: 0 };\n\t\t}\n\n\t\treturn {\n\t\t\tmedian: computeMedian(values),\n\t\t\tmean: computeMean(values),\n\t\t\tcount: values.length,\n\t\t};\n\t}\n\n\tgetPerformanceDelta(\n\t\tprovider: string,\n\t\tmodelId: string,\n\t\trecentCount = 10,\n\t\tbaselineCount = 10_000,\n\t\tstablePercent = 1,\n\t): PerformanceDelta {\n\t\tconst modelEntries = this.entries\n\t\t\t.filter((e) => e.provider === provider && e.modelId === modelId)\n\t\t\t.sort((a, b) => entryTime(b) - entryTime(a));\n\n\t\tconst baselineSlice = baselineCount > 0 ? baselineCount : modelEntries.length;\n\t\tconst baselineValues = modelEntries.slice(0, baselineSlice).map((e) => e.tps);\n\t\tconst recentValues = modelEntries.slice(0, recentCount).map((e) => e.tps);\n\n\t\tconst baselineMedian = computeMedian(baselineValues);\n\t\tconst recentMedian = computeMedian(recentValues);\n\t\tif (baselineValues.length < 3 || recentValues.length < 3 || baselineMedian <= 0) {\n\t\t\treturn {\n\t\t\t\tbaselineMedian,\n\t\t\t\trecentMedian,\n\t\t\t\tpercentDelta: 0,\n\t\t\t\tdirection: \"stable\",\n\t\t\t\tbaselineCount: baselineValues.length,\n\t\t\t\trecentCount: recentValues.length,\n\t\t\t};\n\t\t}\n\n\t\tconst percentDelta = ((recentMedian - baselineMedian) / baselineMedian) * 100;\n\t\tconst direction = Math.abs(percentDelta) < stablePercent ? \"stable\" : percentDelta > 0 ? \"above\" : \"below\";\n\n\t\treturn {\n\t\t\tbaselineMedian,\n\t\t\trecentMedian,\n\t\t\tpercentDelta,\n\t\t\tdirection,\n\t\t\tbaselineCount: baselineValues.length,\n\t\t\trecentCount: recentValues.length,\n\t\t};\n\t}\n\n\tgetAllRollingAverages(\n\t\twindowMs = 24 * 60 * 60 * 1000,\n\t): Array<{ provider: string; modelId: string; median: number; mean: number; count: number }> {\n\t\tconst cutoff = Date.now() - windowMs;\n\t\tconst filtered = this.entries.filter((e) => entryTime(e) >= cutoff);\n\n\t\tconst groups = new Map<string, number[]>();\n\t\tfor (const entry of filtered) {\n\t\t\tconst key = `${entry.provider}\\0${entry.modelId}`;\n\t\t\tconst arr = groups.get(key) ?? [];\n\t\t\tarr.push(entry.tps);\n\t\t\tgroups.set(key, arr);\n\t\t}\n\n\t\tconst results: Array<{ provider: string; modelId: string; median: number; mean: number; count: number }> = [];\n\t\tfor (const [key, values] of groups) {\n\t\t\tconst [provider, modelId] = key.split(\"\\0\");\n\t\t\tresults.push({\n\t\t\t\tprovider,\n\t\t\t\tmodelId,\n\t\t\t\tmedian: computeMedian(values),\n\t\t\t\tmean: computeMean(values),\n\t\t\t\tcount: values.length,\n\t\t\t});\n\t\t}\n\n\t\treturn results;\n\t}\n\n\tprune(ageMs = 30 * 24 * 60 * 60 * 1000): void {\n\t\tif (this.disposed) return;\n\t\tlet tempPath: string | undefined;\n\t\ttry {\n\t\t\tconst pruned = this.withLogLock(() => {\n\t\t\t\tconst cutoff = Date.now() - ageMs;\n\t\t\t\tconst sourceEntries = this.readEntries();\n\t\t\t\tconst kept: PerformanceEntry[] = [];\n\t\t\t\tconst lines: string[] = [];\n\n\t\t\t\tfor (const entry of sourceEntries) {\n\t\t\t\t\tif (entryTime(entry) >= cutoff) {\n\t\t\t\t\t\tkept.push(entry);\n\t\t\t\t\t\tlines.push(JSON.stringify(entry));\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\ttempPath = join(dirname(this.logPath), `.performance-prune-${process.pid}-${Date.now()}.jsonl`);\n\t\t\t\twriteFileSync(tempPath, lines.length > 0 ? `${lines.join(\"\\n\")}\\n` : \"\", \"utf8\");\n\t\t\t\trenameSync(tempPath, this.logPath);\n\t\t\t\ttempPath = undefined;\n\t\t\t\tthis.entries = kept;\n\t\t\t\treturn true;\n\t\t\t}, PerformanceTracker.PRUNE_LOCK_TIMEOUT_MS);\n\t\t\tif (!pruned) {\n\t\t\t\tconsole.warn(\"[PerformanceTracker] Failed to prune performance log: could not acquire log lock\");\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tconsole.warn(`[PerformanceTracker] Failed to prune performance log: ${error}`);\n\t\t} finally {\n\t\t\tif (tempPath) {\n\t\t\t\ttry {\n\t\t\t\t\trmSync(tempPath, { force: true });\n\t\t\t\t} catch {\n\t\t\t\t\t// Best-effort cleanup only\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tdispose(): void {\n\t\tthis.disposed = true;\n\t\tif (this.pruneTimer) {\n\t\t\tclearInterval(this.pruneTimer);\n\t\t\tthis.pruneTimer = null;\n\t\t}\n\t}\n\n\tprivate ensureDir(): void {\n\t\ttry {\n\t\t\tmkdirSync(dirname(this.logPath), { recursive: true });\n\t\t} catch (error) {\n\t\t\tif (isFileExistsError(error)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconsole.warn(`[PerformanceTracker] Failed to create log directory: ${error}`);\n\t\t}\n\t}\n\n\tprivate schedulePrune(): void {\n\t\tif (this.disposed) return;\n\t\tthis.pruneTimer = setInterval(() => {\n\t\t\tthis.prune();\n\t\t}, PerformanceTracker.PRUNE_INTERVAL_MS);\n\t\tthis.pruneTimer?.unref?.();\n\t}\n\n\tprivate readEntries(): PerformanceEntry[] {\n\t\ttry {\n\t\t\tconst content = readFileSync(this.logPath, \"utf8\");\n\t\t\tconst entries: PerformanceEntry[] = [];\n\t\t\tfor (const line of content.split(\"\\n\")) {\n\t\t\t\tif (!line.trim()) continue;\n\t\t\t\ttry {\n\t\t\t\t\tconst parsed = JSON.parse(line) as unknown;\n\t\t\t\t\tif (!isValidPerformanceEntry(parsed)) {\n\t\t\t\t\t\tconsole.warn(`[PerformanceTracker] Skipping invalid performance entry line: ${line}`);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tconst time = entryTime(parsed);\n\t\t\t\t\tif (!Number.isFinite(time)) {\n\t\t\t\t\t\tconsole.warn(`[PerformanceTracker] Skipping entry with invalid timestamp: ${line}`);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tentries.push(parsed);\n\t\t\t\t} catch {\n\t\t\t\t\t// Skip malformed lines\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn entries;\n\t\t} catch (error) {\n\t\t\tif (isENOENT(error)) {\n\t\t\t\treturn [];\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tprivate withLogLock<T>(operation: () => T, timeoutMs = PerformanceTracker.LOCK_TIMEOUT_MS): T | undefined {\n\t\tconst fd = this.acquireLock(timeoutMs);\n\t\tif (fd === undefined) return undefined;\n\t\ttry {\n\t\t\treturn operation();\n\t\t} finally {\n\t\t\ttry {\n\t\t\t\tcloseSync(fd);\n\t\t\t} finally {\n\t\t\t\trmSync(this.lockPath, { force: true });\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate acquireLock(timeoutMs: number): number | undefined {\n\t\tconst start = performance.now();\n\t\twhile (performance.now() - start <= timeoutMs) {\n\t\t\ttry {\n\t\t\t\treturn openSync(this.lockPath, \"wx\");\n\t\t\t} catch (error) {\n\t\t\t\tif (!isFileExistsError(error)) {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tthis.removeStaleLock();\n\t\t\t\tsleepSync(10);\n\t\t\t}\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tprivate removeStaleLock(): void {\n\t\ttry {\n\t\t\tconst lockAgeMs = Date.now() - statSync(this.lockPath).mtimeMs;\n\t\t\tif (lockAgeMs > PerformanceTracker.STALE_LOCK_MS) {\n\t\t\t\trmSync(this.lockPath, { force: true });\n\t\t\t}\n\t\t} catch {\n\t\t\t// Lock disappeared between open attempts\n\t\t}\n\t}\n}\n\nfunction entryTime(entry: PerformanceEntry): number {\n\tconst time = new Date(entry.timestamp).getTime();\n\treturn Number.isFinite(time) ? time : NaN;\n}\n\nfunction computeMedian(values: number[]): number {\n\tif (values.length === 0) return 0;\n\tconst sorted = [...values].sort((a, b) => a - b);\n\tconst mid = Math.floor(sorted.length / 2);\n\tif (sorted.length % 2 === 1) {\n\t\treturn sorted[mid];\n\t}\n\treturn (sorted[mid - 1] + sorted[mid]) / 2;\n}\n\nfunction computeMean(values: number[]): number {\n\tif (values.length === 0) return 0;\n\treturn values.reduce((a, b) => a + b, 0) / values.length;\n}\n\nfunction isFileExistsError(error: unknown): boolean {\n\treturn typeof error === \"object\" && error !== null && \"code\" in error && error.code === \"EEXIST\";\n}\n\nfunction isENOENT(error: unknown): boolean {\n\treturn typeof error === \"object\" && error !== null && \"code\" in error && error.code === \"ENOENT\";\n}\n\nfunction isValidPerformanceEntry(entry: unknown): entry is PerformanceEntry {\n\tif (typeof entry !== \"object\" || entry === null) return false;\n\tconst e = entry as Record<string, unknown>;\n\treturn (\n\t\ttypeof e.timestamp === \"string\" &&\n\t\ttypeof e.provider === \"string\" &&\n\t\ttypeof e.modelId === \"string\" &&\n\t\ttypeof e.outputTokens === \"number\" &&\n\t\tNumber.isFinite(e.outputTokens) &&\n\t\ttypeof e.durationMs === \"number\" &&\n\t\tNumber.isFinite(e.durationMs) &&\n\t\ttypeof e.tps === \"number\" &&\n\t\tNumber.isFinite(e.tps)\n\t);\n}\n\nfunction sleepSync(ms: number): void {\n\tAtomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);\n}\n"]}
1
+ {"version":3,"file":"performance-tracker.js","sourceRoot":"","sources":["../../src/core/performance-tracker.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,cAAc,EACd,SAAS,EACT,SAAS,EACT,QAAQ,EACR,YAAY,EACZ,UAAU,EACV,MAAM,EACN,QAAQ,EACR,aAAa,GACb,MAAM,IAAI,CAAC;AACZ,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AACrC,OAAO,EAAE,qBAAqB,EAAE,MAAM,cAAc,CAAC;AAoCrD,MAAM,OAAO,kBAAkB;IACtB,MAAM,CAAU,iBAAiB,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;IACxD,MAAM,CAAU,eAAe,GAAG,IAAI,CAAC;IACvC,MAAM,CAAU,qBAAqB,GAAG,IAAI,CAAC;IAC7C,MAAM,CAAU,aAAa,GAAG,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC;IAE9C,OAAO,CAAS;IAChB,QAAQ,CAAS;IACjB,OAAO,CAAqB;IAC5B,UAAU,GAA0C,IAAI,CAAC;IACzD,QAAQ,GAAG,K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QAChC,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,UAAU,CAAC;QAC7B,OAAO,CAAC,CAAC,GAAG,KAAK,QAAQ;QACzB,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,GAAG,CAAC,CACtB,CAAC;AAAA,CACF;AAED,SAAS,SAAS,CAAC,EAAU,EAAQ;IACpC,OAAO,CAAC,IAAI,CAAC,IAAI,UAAU,CAAC,IAAI,iBAAiB,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC;AAAA,CACjE","sourcesContent":["import {\n\tappendFileSync,\n\tcloseSync,\n\tmkdirSync,\n\topenSync,\n\treadFileSync,\n\trenameSync,\n\trmSync,\n\tstatSync,\n\twriteFileSync,\n} from \"fs\";\nimport { dirname, join } from \"path\";\nimport { getPerformanceLogPath } from \"../config.js\";\n\nexport interface PerformanceEntry {\n\ttimestamp: string;\n\tsessionId: string;\n\tprovider: string;\n\tmodelId: string;\n\toutputTokens: number;\n\tdurationMs: number;\n\ttps: number;\n}\n\nexport interface RollingAverage {\n\tmedian: number;\n\tmean: number;\n\tcount: number;\n}\n\nexport type PerformanceDeltaDirection = \"above\" | \"below\" | \"stable\";\n\nexport interface PerformanceDelta {\n\tbaselineMedian: number;\n\trecentMedian: number;\n\tpercentDelta: number;\n\tdirection: PerformanceDeltaDirection;\n\tbaselineCount: number;\n\trecentCount: number;\n}\n\nexport interface ModelPerformanceSummary {\n\tprovider: string;\n\tmodelId: string;\n\trolling: RollingAverage;\n\tdelta: PerformanceDelta;\n}\n\nexport class PerformanceTracker {\n\tprivate static readonly PRUNE_INTERVAL_MS = 24 * 60 * 60 * 1000;\n\tprivate static readonly LOCK_TIMEOUT_MS = 1000;\n\tprivate static readonly PRUNE_LOCK_TIMEOUT_MS = 5000;\n\tprivate static readonly STALE_LOCK_MS = 5 * 60 * 1000;\n\n\tprivate logPath: string;\n\tprivate lockPath: string;\n\tprivate entries: PerformanceEntry[];\n\tprivate pruneTimer: ReturnType<typeof setInterval> | null = null;\n\tprivate disposed = false;\n\n\tconstructor(logPath?: string) {\n\t\tthis.logPath = logPath ?? getPerformanceLogPath();\n\t\tthis.lockPath = `${this.logPath}.lock`;\n\t\ttry {\n\t\t\tthis.entries = this.readEntries();\n\t\t} catch {\n\t\t\tthis.entries = [];\n\t\t}\n\t\tthis.ensureDir();\n\t\tthis.schedulePrune();\n\t}\n\n\trecord(entry: PerformanceEntry): void {\n\t\tif (this.disposed) return;\n\t\ttry {\n\t\t\tconst wrote = this.withLogLock(() => {\n\t\t\t\tappendFileSync(this.logPath, `${JSON.stringify(entry)}\\n`, \"utf8\");\n\t\t\t\treturn true;\n\t\t\t});\n\t\t\tif (!wrote) {\n\t\t\t\tconsole.warn(\"[PerformanceTracker] Failed to write performance entry: could not acquire log lock\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.entries.push(entry);\n\t\t} catch (error) {\n\t\t\tconsole.warn(`[PerformanceTracker] Failed to write performance entry: ${error}`);\n\t\t}\n\t}\n\n\tgetRollingAverage(provider: string, modelId: string, count = 100): RollingAverage {\n\t\tconst values = this.entries\n\t\t\t.filter((e) => e.provider === provider && e.modelId === modelId)\n\t\t\t.sort((a, b) => entryTime(b) - entryTime(a))\n\t\t\t.slice(0, count)\n\t\t\t.map((e) => e.tps);\n\n\t\tif (values.length === 0) {\n\t\t\treturn { median: 0, mean: 0, count: 0 };\n\t\t}\n\n\t\treturn {\n\t\t\tmedian: computeMedian(values),\n\t\t\tmean: computeMean(values),\n\t\t\tcount: values.length,\n\t\t};\n\t}\n\n\tgetPerformanceDelta(\n\t\tprovider: string,\n\t\tmodelId: string,\n\t\trecentCount = 10,\n\t\tbaselineCount = 10_000,\n\t\tstablePercent = 1,\n\t): PerformanceDelta {\n\t\tconst modelEntries = this.entries\n\t\t\t.filter((e) => e.provider === provider && e.modelId === modelId)\n\t\t\t.sort((a, b) => entryTime(b) - entryTime(a));\n\n\t\tconst baselineSlice = baselineCount > 0 ? baselineCount : modelEntries.length;\n\t\tconst baselineValues = modelEntries.slice(0, baselineSlice).map((e) => e.tps);\n\t\tconst recentValues = modelEntries.slice(0, recentCount).map((e) => e.tps);\n\n\t\tconst baselineMedian = computeMedian(baselineValues);\n\t\tconst recentMedian = computeMedian(recentValues);\n\t\tif (baselineValues.length < 3 || recentValues.length < 3 || baselineMedian <= 0) {\n\t\t\treturn {\n\t\t\t\tbaselineMedian,\n\t\t\t\trecentMedian,\n\t\t\t\tpercentDelta: 0,\n\t\t\t\tdirection: \"stable\",\n\t\t\t\tbaselineCount: baselineValues.length,\n\t\t\t\trecentCount: recentValues.length,\n\t\t\t};\n\t\t}\n\n\t\tconst percentDelta = ((recentMedian - baselineMedian) / baselineMedian) * 100;\n\t\tconst direction = Math.abs(percentDelta) < stablePercent ? \"stable\" : percentDelta > 0 ? \"above\" : \"below\";\n\n\t\treturn {\n\t\t\tbaselineMedian,\n\t\t\trecentMedian,\n\t\t\tpercentDelta,\n\t\t\tdirection,\n\t\t\tbaselineCount: baselineValues.length,\n\t\t\trecentCount: recentValues.length,\n\t\t};\n\t}\n\n\tgetAllModelSummaries(): ModelPerformanceSummary[] {\n\t\tconst models = new Map<string, { provider: string; modelId: string }>();\n\t\tfor (const entry of this.entries) {\n\t\t\tconst key = `${entry.provider}\\0${entry.modelId}`;\n\t\t\tif (!models.has(key)) {\n\t\t\t\tmodels.set(key, { provider: entry.provider, modelId: entry.modelId });\n\t\t\t}\n\t\t}\n\n\t\treturn Array.from(models.values(), ({ provider, modelId }) => ({\n\t\t\tprovider,\n\t\t\tmodelId,\n\t\t\trolling: this.getRollingAverage(provider, modelId),\n\t\t\tdelta: this.getPerformanceDelta(provider, modelId),\n\t\t}));\n\t}\n\n\tprune(ageMs = 30 * 24 * 60 * 60 * 1000): void {\n\t\tif (this.disposed) return;\n\t\tlet tempPath: string | undefined;\n\t\ttry {\n\t\t\tconst pruned = this.withLogLock(() => {\n\t\t\t\tconst cutoff = Date.now() - ageMs;\n\t\t\t\tconst sourceEntries = this.readEntries();\n\t\t\t\tconst kept: PerformanceEntry[] = [];\n\t\t\t\tconst lines: string[] = [];\n\n\t\t\t\tfor (const entry of sourceEntries) {\n\t\t\t\t\tif (entryTime(entry) >= cutoff) {\n\t\t\t\t\t\tkept.push(entry);\n\t\t\t\t\t\tlines.push(JSON.stringify(entry));\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\ttempPath = join(dirname(this.logPath), `.performance-prune-${process.pid}-${Date.now()}.jsonl`);\n\t\t\t\twriteFileSync(tempPath, lines.length > 0 ? `${lines.join(\"\\n\")}\\n` : \"\", \"utf8\");\n\t\t\t\trenameSync(tempPath, this.logPath);\n\t\t\t\ttempPath = undefined;\n\t\t\t\tthis.entries = kept;\n\t\t\t\treturn true;\n\t\t\t}, PerformanceTracker.PRUNE_LOCK_TIMEOUT_MS);\n\t\t\tif (!pruned) {\n\t\t\t\tconsole.warn(\"[PerformanceTracker] Failed to prune performance log: could not acquire log lock\");\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tconsole.warn(`[PerformanceTracker] Failed to prune performance log: ${error}`);\n\t\t} finally {\n\t\t\tif (tempPath) {\n\t\t\t\ttry {\n\t\t\t\t\trmSync(tempPath, { force: true });\n\t\t\t\t} catch {\n\t\t\t\t\t// Best-effort cleanup only\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tdispose(): void {\n\t\tthis.disposed = true;\n\t\tif (this.pruneTimer) {\n\t\t\tclearInterval(this.pruneTimer);\n\t\t\tthis.pruneTimer = null;\n\t\t}\n\t}\n\n\tprivate ensureDir(): void {\n\t\ttry {\n\t\t\tmkdirSync(dirname(this.logPath), { recursive: true });\n\t\t} catch (error) {\n\t\t\tif (isFileExistsError(error)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconsole.warn(`[PerformanceTracker] Failed to create log directory: ${error}`);\n\t\t}\n\t}\n\n\tprivate schedulePrune(): void {\n\t\tif (this.disposed) return;\n\t\tthis.pruneTimer = setInterval(() => {\n\t\t\tthis.prune();\n\t\t}, PerformanceTracker.PRUNE_INTERVAL_MS);\n\t\tthis.pruneTimer?.unref?.();\n\t}\n\n\tprivate readEntries(): PerformanceEntry[] {\n\t\ttry {\n\t\t\tconst content = readFileSync(this.logPath, \"utf8\");\n\t\t\tconst entries: PerformanceEntry[] = [];\n\t\t\tfor (const line of content.split(\"\\n\")) {\n\t\t\t\tif (!line.trim()) continue;\n\t\t\t\ttry {\n\t\t\t\t\tconst parsed = JSON.parse(line) as unknown;\n\t\t\t\t\tif (!isValidPerformanceEntry(parsed)) {\n\t\t\t\t\t\tconsole.warn(`[PerformanceTracker] Skipping invalid performance entry line: ${line}`);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tconst time = entryTime(parsed);\n\t\t\t\t\tif (!Number.isFinite(time)) {\n\t\t\t\t\t\tconsole.warn(`[PerformanceTracker] Skipping entry with invalid timestamp: ${line}`);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tentries.push(parsed);\n\t\t\t\t} catch {\n\t\t\t\t\t// Skip malformed lines\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn entries;\n\t\t} catch (error) {\n\t\t\tif (isENOENT(error)) {\n\t\t\t\treturn [];\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tprivate withLogLock<T>(operation: () => T, timeoutMs = PerformanceTracker.LOCK_TIMEOUT_MS): T | undefined {\n\t\tconst fd = this.acquireLock(timeoutMs);\n\t\tif (fd === undefined) return undefined;\n\t\ttry {\n\t\t\treturn operation();\n\t\t} finally {\n\t\t\ttry {\n\t\t\t\tcloseSync(fd);\n\t\t\t} finally {\n\t\t\t\trmSync(this.lockPath, { force: true });\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate acquireLock(timeoutMs: number): number | undefined {\n\t\tconst start = performance.now();\n\t\twhile (performance.now() - start <= timeoutMs) {\n\t\t\ttry {\n\t\t\t\treturn openSync(this.lockPath, \"wx\");\n\t\t\t} catch (error) {\n\t\t\t\tif (!isFileExistsError(error)) {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tthis.removeStaleLock();\n\t\t\t\tsleepSync(10);\n\t\t\t}\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tprivate removeStaleLock(): void {\n\t\ttry {\n\t\t\tconst lockAgeMs = Date.now() - statSync(this.lockPath).mtimeMs;\n\t\t\tif (lockAgeMs > PerformanceTracker.STALE_LOCK_MS) {\n\t\t\t\trmSync(this.lockPath, { force: true });\n\t\t\t}\n\t\t} catch {\n\t\t\t// Lock disappeared between open attempts\n\t\t}\n\t}\n}\n\nfunction entryTime(entry: PerformanceEntry): number {\n\tconst time = new Date(entry.timestamp).getTime();\n\treturn Number.isFinite(time) ? time : NaN;\n}\n\nfunction computeMedian(values: number[]): number {\n\tif (values.length === 0) return 0;\n\tconst sorted = [...values].sort((a, b) => a - b);\n\tconst mid = Math.floor(sorted.length / 2);\n\tif (sorted.length % 2 === 1) {\n\t\treturn sorted[mid];\n\t}\n\treturn (sorted[mid - 1] + sorted[mid]) / 2;\n}\n\nfunction computeMean(values: number[]): number {\n\tif (values.length === 0) return 0;\n\treturn values.reduce((a, b) => a + b, 0) / values.length;\n}\n\nfunction isFileExistsError(error: unknown): boolean {\n\treturn typeof error === \"object\" && error !== null && \"code\" in error && error.code === \"EEXIST\";\n}\n\nfunction isENOENT(error: unknown): boolean {\n\treturn typeof error === \"object\" && error !== null && \"code\" in error && error.code === \"ENOENT\";\n}\n\nfunction isValidPerformanceEntry(entry: unknown): entry is PerformanceEntry {\n\tif (typeof entry !== \"object\" || entry === null) return false;\n\tconst e = entry as Record<string, unknown>;\n\treturn (\n\t\ttypeof e.timestamp === \"string\" &&\n\t\ttypeof e.provider === \"string\" &&\n\t\ttypeof e.modelId === \"string\" &&\n\t\ttypeof e.outputTokens === \"number\" &&\n\t\tNumber.isFinite(e.outputTokens) &&\n\t\ttypeof e.durationMs === \"number\" &&\n\t\tNumber.isFinite(e.durationMs) &&\n\t\ttypeof e.tps === \"number\" &&\n\t\tNumber.isFinite(e.tps)\n\t);\n}\n\nfunction sleepSync(ms: number): void {\n\tAtomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);\n}\n"]}
@@ -6,5 +6,5 @@
6
6
  */
7
7
  export type { ModelInfo, RpcClientOptions, RpcEventListener, RpcExitInfo, RpcExitListener } from "./rpc-client.js";
8
8
  export { RpcClient } from "./rpc-client.js";
9
- export type { RpcAgentTypeInfo, RpcBackgroundAgentInfo, RpcCommand, RpcCommandType, RpcContextTrustEvaluation, RpcContextTrustMutationResult, RpcDashboardSnapshot, RpcDashboardSnapshotBarrierEvent, RpcEvent, RpcExtensionUIRequest, RpcExtensionUIResponse, RpcPendingMessages, RpcQueuedMessage, RpcResources, RpcResponse, RpcScopedModel, RpcSessionInfo, RpcSessionState, RpcSessionTask, RpcSettingsSetResult, RpcSettingsSnapshot, RpcSettingsUpdate, RpcSlashCommand, RpcTreeNode, RpcTrustedFolderRemovalResult, } from "./rpc-types.js";
9
+ export type { RpcAgentTypeInfo, RpcBackgroundAgentInfo, RpcCommand, RpcCommandType, RpcContextTrustEvaluation, RpcContextTrustMutationResult, RpcDashboardSnapshot, RpcDashboardSnapshotBarrierEvent, RpcEvent, RpcExtensionUIRequest, RpcExtensionUIResponse, RpcPendingMessages, RpcPerformanceStats, RpcQueuedMessage, RpcResources, RpcResponse, RpcScopedModel, RpcSessionInfo, RpcSessionState, RpcSessionTask, RpcSettingsSetResult, RpcSettingsSnapshot, RpcSettingsUpdate, RpcSlashCommand, RpcTreeNode, RpcTrustedFolderRemovalResult, } from "./rpc-types.js";
10
10
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/modes/rpc/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,YAAY,EAAE,SAAS,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AACnH,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAC5C,YAAY,EACX,gBAAgB,EAChB,sBAAsB,EACtB,UAAU,EACV,cAAc,EACd,yBAAyB,EACzB,6BAA6B,EAC7B,oBAAoB,EACpB,gCAAgC,EAChC,QAAQ,EACR,qBAAqB,EACrB,sBAAsB,EACtB,kBAAkB,EAClB,gBAAgB,EAChB,YAAY,EACZ,WAAW,EACX,cAAc,EACd,cAAc,EACd,eAAe,EACf,cAAc,EACd,oBAAoB,EACpB,mBAAmB,EACnB,iBAAiB,EACjB,eAAe,EACf,WAAW,EACX,6BAA6B,GAC7B,MAAM,gBAAgB,CAAC","sourcesContent":["/**\n * RPC client and types for programmatic access to the coding agent.\n *\n * Usage:\n * import { RpcClient } from \"@dreb/coding-agent/rpc\";\n */\n\nexport type { ModelInfo, RpcClientOptions, RpcEventListener, RpcExitInfo, RpcExitListener } from \"./rpc-client.js\";\nexport { RpcClient } from \"./rpc-client.js\";\nexport type {\n\tRpcAgentTypeInfo,\n\tRpcBackgroundAgentInfo,\n\tRpcCommand,\n\tRpcCommandType,\n\tRpcContextTrustEvaluation,\n\tRpcContextTrustMutationResult,\n\tRpcDashboardSnapshot,\n\tRpcDashboardSnapshotBarrierEvent,\n\tRpcEvent,\n\tRpcExtensionUIRequest,\n\tRpcExtensionUIResponse,\n\tRpcPendingMessages,\n\tRpcQueuedMessage,\n\tRpcResources,\n\tRpcResponse,\n\tRpcScopedModel,\n\tRpcSessionInfo,\n\tRpcSessionState,\n\tRpcSessionTask,\n\tRpcSettingsSetResult,\n\tRpcSettingsSnapshot,\n\tRpcSettingsUpdate,\n\tRpcSlashCommand,\n\tRpcTreeNode,\n\tRpcTrustedFolderRemovalResult,\n} from \"./rpc-types.js\";\n"]}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/modes/rpc/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,YAAY,EAAE,SAAS,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AACnH,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAC5C,YAAY,EACX,gBAAgB,EAChB,sBAAsB,EACtB,UAAU,EACV,cAAc,EACd,yBAAyB,EACzB,6BAA6B,EAC7B,oBAAoB,EACpB,gCAAgC,EAChC,QAAQ,EACR,qBAAqB,EACrB,sBAAsB,EACtB,kBAAkB,EAClB,mBAAmB,EACnB,gBAAgB,EAChB,YAAY,EACZ,WAAW,EACX,cAAc,EACd,cAAc,EACd,eAAe,EACf,cAAc,EACd,oBAAoB,EACpB,mBAAmB,EACnB,iBAAiB,EACjB,eAAe,EACf,WAAW,EACX,6BAA6B,GAC7B,MAAM,gBAAgB,CAAC","sourcesContent":["/**\n * RPC client and types for programmatic access to the coding agent.\n *\n * Usage:\n * import { RpcClient } from \"@dreb/coding-agent/rpc\";\n */\n\nexport type { ModelInfo, RpcClientOptions, RpcEventListener, RpcExitInfo, RpcExitListener } from \"./rpc-client.js\";\nexport { RpcClient } from \"./rpc-client.js\";\nexport type {\n\tRpcAgentTypeInfo,\n\tRpcBackgroundAgentInfo,\n\tRpcCommand,\n\tRpcCommandType,\n\tRpcContextTrustEvaluation,\n\tRpcContextTrustMutationResult,\n\tRpcDashboardSnapshot,\n\tRpcDashboardSnapshotBarrierEvent,\n\tRpcEvent,\n\tRpcExtensionUIRequest,\n\tRpcExtensionUIResponse,\n\tRpcPendingMessages,\n\tRpcPerformanceStats,\n\tRpcQueuedMessage,\n\tRpcResources,\n\tRpcResponse,\n\tRpcScopedModel,\n\tRpcSessionInfo,\n\tRpcSessionState,\n\tRpcSessionTask,\n\tRpcSettingsSetResult,\n\tRpcSettingsSnapshot,\n\tRpcSettingsUpdate,\n\tRpcSlashCommand,\n\tRpcTreeNode,\n\tRpcTrustedFolderRemovalResult,\n} from \"./rpc-types.js\";\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/modes/rpc/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC","sourcesContent":["/**\n * RPC client and types for programmatic access to the coding agent.\n *\n * Usage:\n * import { RpcClient } from \"@dreb/coding-agent/rpc\";\n */\n\nexport type { ModelInfo, RpcClientOptions, RpcEventListener, RpcExitInfo, RpcExitListener } from \"./rpc-client.js\";\nexport { RpcClient } from \"./rpc-client.js\";\nexport type {\n\tRpcAgentTypeInfo,\n\tRpcBackgroundAgentInfo,\n\tRpcCommand,\n\tRpcCommandType,\n\tRpcContextTrustEvaluation,\n\tRpcContextTrustMutationResult,\n\tRpcDashboardSnapshot,\n\tRpcDashboardSnapshotBarrierEvent,\n\tRpcEvent,\n\tRpcExtensionUIRequest,\n\tRpcExtensionUIResponse,\n\tRpcPendingMessages,\n\tRpcQueuedMessage,\n\tRpcResources,\n\tRpcResponse,\n\tRpcScopedModel,\n\tRpcSessionInfo,\n\tRpcSessionState,\n\tRpcSessionTask,\n\tRpcSettingsSetResult,\n\tRpcSettingsSnapshot,\n\tRpcSettingsUpdate,\n\tRpcSlashCommand,\n\tRpcTreeNode,\n\tRpcTrustedFolderRemovalResult,\n} from \"./rpc-types.js\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/modes/rpc/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC","sourcesContent":["/**\n * RPC client and types for programmatic access to the coding agent.\n *\n * Usage:\n * import { RpcClient } from \"@dreb/coding-agent/rpc\";\n */\n\nexport type { ModelInfo, RpcClientOptions, RpcEventListener, RpcExitInfo, RpcExitListener } from \"./rpc-client.js\";\nexport { RpcClient } from \"./rpc-client.js\";\nexport type {\n\tRpcAgentTypeInfo,\n\tRpcBackgroundAgentInfo,\n\tRpcCommand,\n\tRpcCommandType,\n\tRpcContextTrustEvaluation,\n\tRpcContextTrustMutationResult,\n\tRpcDashboardSnapshot,\n\tRpcDashboardSnapshotBarrierEvent,\n\tRpcEvent,\n\tRpcExtensionUIRequest,\n\tRpcExtensionUIResponse,\n\tRpcPendingMessages,\n\tRpcPerformanceStats,\n\tRpcQueuedMessage,\n\tRpcResources,\n\tRpcResponse,\n\tRpcScopedModel,\n\tRpcSessionInfo,\n\tRpcSessionState,\n\tRpcSessionTask,\n\tRpcSettingsSetResult,\n\tRpcSettingsSnapshot,\n\tRpcSettingsUpdate,\n\tRpcSlashCommand,\n\tRpcTreeNode,\n\tRpcTrustedFolderRemovalResult,\n} from \"./rpc-types.js\";\n"]}
@@ -8,7 +8,7 @@ import type { ImageContent } from "@dreb/ai";
8
8
  import type { SessionStats } from "../../core/agent-session.js";
9
9
  import type { BashResult } from "../../core/bash-executor.js";
10
10
  import type { CompactionResult } from "../../core/compaction/index.js";
11
- import type { RpcAgentTypeInfo, RpcBackgroundAgentInfo, RpcContextTrustEvaluation, RpcContextTrustMutationResult, RpcDashboardSnapshot, RpcEvent, RpcExtensionUIResponse, RpcPendingMessages, RpcResources, RpcSessionInfo, RpcSessionState, RpcSettingsSetResult, RpcSettingsSnapshot, RpcSettingsUpdate, RpcSlashCommand, RpcTreeNode, RpcTrustedFolderRemovalResult } from "./rpc-types.js";
11
+ import type { RpcAgentTypeInfo, RpcBackgroundAgentInfo, RpcContextTrustEvaluation, RpcContextTrustMutationResult, RpcDashboardSnapshot, RpcEvent, RpcExtensionUIResponse, RpcPendingMessages, RpcPerformanceStats, RpcResources, RpcSessionInfo, RpcSessionState, RpcSettingsSetResult, RpcSettingsSnapshot, RpcSettingsUpdate, RpcSlashCommand, RpcTreeNode, RpcTrustedFolderRemovalResult } from "./rpc-types.js";
12
12
  export interface RpcClientOptions {
13
13
  /** Path to the CLI entry point (default: searches for dist/cli.js) */
14
14
  cliPath?: string;
@@ -247,15 +247,7 @@ export declare class RpcClient {
247
247
  /**
248
248
  * Get performance statistics.
249
249
  */
250
- getPerformanceStats(): Promise<{
251
- models: Array<{
252
- provider: string;
253
- modelId: string;
254
- median: number;
255
- mean: number;
256
- count: number;
257
- }>;
258
- }>;
250
+ getPerformanceStats(): Promise<RpcPerformanceStats>;
259
251
  /**
260
252
  * Export session to HTML.
261
253
  */
@@ -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,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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AM,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"]}
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,mBAAmB,EACnB,YAAY,EAEZ,cAAc,EACd,eAAe,EACf,oBAAoB,EACpB,mBAAmB,EACnB,iBAAiB,EACjB,eAAe,EACf,WAAW,EACX,6BAA6B,EAC7B,MAAM,gBAAgB,CAAC;AAkBxB,MAAM,WA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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\tRpcPerformanceStats,\n\tRpcResources,\n\tRpcResponse,\n\tRpcSessionInfo,\n\tRpcSessionState,\n\tRpcSettingsSetResult,\n\tRpcSettingsSnapshot,\n\tRpcSettingsUpdate,\n\tRpcSlashCommand,\n\tRpcTreeNode,\n\tRpcTrustedFolderRemovalResult,\n} from \"./rpc-types.js\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Grace period (ms) start() waits for the child to initialize before treating\n * it as alive. An 'error'/'exit' event during this window rejects start() early.\n */\nconst INIT_GRACE_MS = 100;\n\n/** Distributive Omit that works with union types */\ntype DistributiveOmit<T, K extends keyof T> = T extends unknown ? Omit<T, K> : never;\n\n/** RpcCommand without the id field (for internal send) */\ntype RpcCommandBody = DistributiveOmit<RpcCommand, \"id\">;\n\nexport interface RpcClientOptions {\n\t/** Path to the CLI entry point (default: searches for dist/cli.js) */\n\tcliPath?: string;\n\t/** Working directory for the agent */\n\tcwd?: string;\n\t/** Environment variables */\n\tenv?: Record<string, string>;\n\t/** Provider to use */\n\tprovider?: string;\n\t/** Model ID to use */\n\tmodel?: string;\n\t/** Additional CLI arguments */\n\targs?: string[];\n\t/**\n\t * Run the agent child process under this OS user id.\n\t * Forwarded directly to `child_process.spawn`. The parent process must hold\n\t * `CAP_SETUID` (typically by running as root) for this to succeed; otherwise\n\t * the spawn fails and `start()` rejects. Omitted when unset (default behavior).\n\t */\n\tuid?: number;\n\t/**\n\t * Run the agent child process under this OS group id.\n\t * Forwarded directly to `child_process.spawn`. The parent process must hold\n\t * `CAP_SETGID` (typically by running as root) for this to succeed; otherwise\n\t * the spawn fails and `start()` rejects. Omitted when unset (default behavior).\n\t */\n\tgid?: number;\n}\n\nexport interface ModelInfo {\n\tprovider: string;\n\tid: string;\n\tcontextWindow: number;\n\treasoning: boolean;\n}\n\n/**\n * Listener for non-response messages streamed by the RPC server. The wire carries\n * the full {@link RpcEvent} union: session events, extension UI requests, and\n * RPC-specific ordering markers such as `dashboard_snapshot_barrier`.\n */\nexport type RpcEventListener = (event: RpcEvent) => void;\n\nexport type RpcExitInfo =\n\t| { code: number | null; signal: NodeJS.Signals | null; error?: undefined }\n\t| { code?: undefined; signal?: undefined; error: Error };\n\nexport type RpcExitListener = (info: RpcExitInfo) => void;\n\ntype JsonRecord = Record<string, unknown>;\n\nfunction isJsonRecord(value: unknown): value is JsonRecord {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isRpcResponseMessage(value: unknown): value is RpcResponse {\n\treturn isJsonRecord(value) && value.type === \"response\";\n}\n\nfunction isRpcDashboardSnapshotBarrierEvent(value: unknown): value is RpcDashboardSnapshotBarrierEvent {\n\treturn isJsonRecord(value) && value.type === \"dashboard_snapshot_barrier\" && typeof value.snapshotId === \"string\";\n}\n\nfunction isRpcExtensionUIRequestMessage(value: unknown): value is RpcExtensionUIRequest {\n\treturn (\n\t\tisJsonRecord(value) &&\n\t\tvalue.type === \"extension_ui_request\" &&\n\t\ttypeof value.id === \"string\" &&\n\t\ttypeof value.method === \"string\"\n\t);\n}\n\nfunction isRpcEvent(value: unknown): value is RpcEvent {\n\tif (!isJsonRecord(value) || typeof value.type !== \"string\" || value.type === \"response\") {\n\t\treturn false;\n\t}\n\tif (value.type === \"dashboard_snapshot_barrier\") {\n\t\treturn isRpcDashboardSnapshotBarrierEvent(value);\n\t}\n\tif (value.type === \"extension_ui_request\") {\n\t\treturn isRpcExtensionUIRequestMessage(value);\n\t}\n\treturn true;\n}\n\n// ============================================================================\n// RPC Client\n// ============================================================================\n\nexport class RpcClient {\n\tprivate process: ChildProcess | null = null;\n\tprivate stopReadingStdout: (() => void) | null = null;\n\tprivate eventListeners: RpcEventListener[] = [];\n\tprivate exitListeners = new Set<RpcExitListener>();\n\tprivate pendingRequests: Map<string, { resolve: (response: RpcResponse) => void; reject: (error: Error) => void }> =\n\t\tnew Map();\n\tprivate requestId = 0;\n\tprivate stderr = \"\";\n\tprivate _dead = false;\n\tprivate spawnError: Error | null = null;\n\n\tconstructor(private options: RpcClientOptions = {}) {}\n\n\t/**\n\t * Start the RPC agent process.\n\t */\n\tasync start(): Promise<void> {\n\t\tif (this.process) {\n\t\t\tthrow new Error(\"Client already started\");\n\t\t}\n\n\t\tconst cliPath = this.options.cliPath ?? \"dist/cli.js\";\n\t\tconst args = [\"--mode\", \"rpc\"];\n\n\t\tif (this.options.provider) {\n\t\t\targs.push(\"--provider\", this.options.provider);\n\t\t}\n\t\tif (this.options.model) {\n\t\t\targs.push(\"--model\", this.options.model);\n\t\t}\n\t\tif (this.options.args) {\n\t\t\targs.push(...this.options.args);\n\t\t}\n\n\t\tthis.process = spawn(\"node\", [cliPath, ...args], {\n\t\t\tcwd: this.options.cwd,\n\t\t\tenv: { ...process.env, ...this.options.env },\n\t\t\tstdio: [\"pipe\", \"pipe\", \"pipe\"],\n\t\t\t...(this.options.uid != null ? { uid: this.options.uid } : {}),\n\t\t\t...(this.options.gid != null ? { gid: this.options.gid } : {}),\n\t\t});\n\n\t\tthis._dead = false;\n\t\tthis.spawnError = null;\n\n\t\t// Collect stderr for debugging\n\t\tthis.process.stderr?.on(\"data\", (data) => {\n\t\t\tthis.stderr += data.toString();\n\t\t});\n\n\t\t// Detect process exit and spawn failures for the whole session lifecycle —\n\t\t// reject pending requests so callers don't hang. Capture the process\n\t\t// reference so stale handlers from a previous process don't clobber state\n\t\t// after a stop()/start() cycle.\n\t\tconst procRef = this.process;\n\t\tprocRef.on(\"exit\", (code, signal) => {\n\t\t\t// Guard: skip if this handler belongs to an old, already-stopped process\n\t\t\tif (this.process !== procRef) return;\n\t\t\tthis.failPendingRequests(`RPC process exited with code ${code}, signal ${signal}`);\n\t\t\tthis.notifyExitListeners({ code, signal });\n\t\t});\n\n\t\t// Spawn failures surface asynchronously as an 'error' event rather than a\n\t\t// thrown exception (e.g. EPERM when dropping to a uid/gid the parent lacks\n\t\t// CAP_SETUID/CAP_SETGID for, or unsupported on Windows). Without a listener\n\t\t// an 'error' event would crash the process; record the cause so start() can\n\t\t// fail loudly and a later send() can report the real reason instead of a\n\t\t// generic \"not running\".\n\t\tprocRef.on(\"error\", (err) => {\n\t\t\t// Guard: skip if this handler belongs to an old, already-stopped process\n\t\t\tif (this.process !== procRef) return;\n\t\t\tthis.spawnError = err;\n\t\t\tthis.failPendingRequests(`RPC process failed to spawn: ${err.message}`);\n\t\t\tthis.notifyExitListeners({ error: err });\n\t\t});\n\n\t\t// Set up strict JSONL reader for stdout.\n\t\tthis.stopReadingStdout = attachJsonlLineReader(this.process.stdout!, (line) => {\n\t\t\tthis.handleLine(line);\n\t\t});\n\n\t\t// Give the process a moment to initialize, but settle as soon as an\n\t\t// 'error' or 'exit' event arrives. Racing the grace period against those\n\t\t// events (instead of a blind fixed sleep) guarantees that a failed\n\t\t// privilege drop (uid/gid EPERM) rejects start() loudly no matter when\n\t\t// libuv delivers the event — a fixed sleep could expire first and let\n\t\t// start() resolve despite the child never running.\n\t\tawait new Promise<void>((resolve, reject) => {\n\t\t\tconst onError = (err: Error) => {\n\t\t\t\tcleanup();\n\t\t\t\treject(new Error(`Agent process failed to spawn: ${err.message}. Stderr: ${this.stderr}`));\n\t\t\t};\n\t\t\tconst onExit = (code: number | null, signal: NodeJS.Signals | null) => {\n\t\t\t\tcleanup();\n\t\t\t\treject(\n\t\t\t\t\tnew Error(\n\t\t\t\t\t\t`Agent process exited immediately with code ${code}, signal ${signal}. Stderr: ${this.stderr}`,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t};\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tcleanup();\n\t\t\t\tresolve();\n\t\t\t}, INIT_GRACE_MS);\n\t\t\tconst cleanup = () => {\n\t\t\t\tclearTimeout(timer);\n\t\t\t\tprocRef.off(\"error\", onError);\n\t\t\t\tprocRef.off(\"exit\", onExit);\n\t\t\t};\n\t\t\tprocRef.once(\"error\", onError);\n\t\t\tprocRef.once(\"exit\", onExit);\n\t\t});\n\n\t\t// Belt-and-suspenders: a process that exited exactly as the grace timer\n\t\t// fired (so the race resolved instead of rejecting) still surfaces loudly.\n\t\tif (this.process.exitCode !== null) {\n\t\t\tthrow new Error(`Agent process exited immediately with code ${this.process.exitCode}. Stderr: ${this.stderr}`);\n\t\t}\n\t}\n\n\t/**\n\t * Stop the RPC agent process.\n\t */\n\tasync stop(): Promise<void> {\n\t\tif (!this.process) return;\n\n\t\tthis.stopReadingStdout?.();\n\t\tthis.stopReadingStdout = null;\n\t\tthis.process.kill(\"SIGTERM\");\n\n\t\t// Wait for process to exit\n\t\tawait new Promise<void>((resolve) => {\n\t\t\tconst timeout = setTimeout(() => {\n\t\t\t\tthis.process?.kill(\"SIGKILL\");\n\t\t\t\tresolve();\n\t\t\t}, 1000);\n\n\t\t\tthis.process?.on(\"exit\", () => {\n\t\t\t\tclearTimeout(timeout);\n\t\t\t\tresolve();\n\t\t\t});\n\t\t});\n\n\t\tthis.process = null;\n\t\tthis._dead = true;\n\t\tthis.pendingRequests.clear();\n\t}\n\n\t/**\n\t * Subscribe to agent events.\n\t */\n\tonEvent(listener: RpcEventListener): () => void {\n\t\tthis.eventListeners.push(listener);\n\t\treturn () => {\n\t\t\tconst index = this.eventListeners.indexOf(listener);\n\t\t\tif (index !== -1) {\n\t\t\t\tthis.eventListeners.splice(index, 1);\n\t\t\t}\n\t\t};\n\t}\n\n\t/**\n\t * Subscribe to child process death/spawn-failure notifications.\n\t */\n\tonExit(listener: RpcExitListener): () => void {\n\t\tthis.exitListeners.add(listener);\n\t\treturn () => {\n\t\t\tthis.exitListeners.delete(listener);\n\t\t};\n\t}\n\n\t/**\n\t * Get collected stderr output (useful for debugging).\n\t */\n\tgetStderr(): string {\n\t\treturn this.stderr;\n\t}\n\n\t// =========================================================================\n\t// Command Methods\n\t// =========================================================================\n\n\t/**\n\t * Send a prompt to the agent.\n\t * Returns immediately after sending; use onEvent() to receive streaming events.\n\t * Use waitForIdle() to wait for completion.\n\t */\n\tasync prompt(message: string, images?: ImageContent[]): Promise<void> {\n\t\tawait this.send({ type: \"prompt\", message, images });\n\t}\n\n\t/**\n\t * Queue a steering message to interrupt the agent mid-run.\n\t */\n\tasync steer(message: string, images?: ImageContent[]): Promise<void> {\n\t\tawait this.send({ type: \"steer\", message, images });\n\t}\n\n\t/**\n\t * Queue a follow-up message to be processed after the agent finishes.\n\t */\n\tasync followUp(message: string, images?: ImageContent[]): Promise<void> {\n\t\tawait this.send({ type: \"follow_up\", message, images });\n\t}\n\n\t/**\n\t * Abort current operation.\n\t */\n\tasync abort(): Promise<void> {\n\t\tawait this.send({ type: \"abort\" });\n\t}\n\n\t/**\n\t * Start a new session, optionally with parent tracking.\n\t * @param parentSession - Optional parent session path for lineage tracking\n\t * @returns Object with `cancelled: true` if an extension cancelled the new session\n\t */\n\tasync newSession(parentSession?: string): Promise<{ cancelled: boolean }> {\n\t\tconst response = await this.send({ type: \"new_session\", parentSession });\n\t\treturn this.getData(response);\n\t}\n\n\t/** Reload extensions, skills, prompts, themes, and other session resources. */\n\tasync reload(): Promise<void> {\n\t\tawait this.send({ type: \"reload\" });\n\t}\n\n\t/** Run `/dream` or one of its backup-path forms. */\n\tasync dream(args?: string): Promise<{ message: string }> {\n\t\tconst response = await this.send({ type: \"dream\", args });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Get current session state.\n\t */\n\tasync getState(): Promise<RpcSessionState> {\n\t\tconst response = await this.send({ type: \"get_state\" });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Capture a dashboard recovery snapshot. The RPC stream emits a matching\n\t * `dashboard_snapshot_barrier` immediately before this response; consumers\n\t * need that event's EventHub sequence before applying the snapshot.\n\t */\n\tasync getDashboardSnapshot(): Promise<RpcDashboardSnapshot> {\n\t\tconst response = await this.send({ type: \"get_dashboard_snapshot\" });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Get loaded context/resources metadata (paths/names only, no file contents).\n\t */\n\tasync getResources(): Promise<RpcResources> {\n\t\tconst response = await this.send({ type: \"get_resources\" });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Get current git branch for the agent cwd.\n\t */\n\tasync getGitBranch(): Promise<string | null> {\n\t\tconst response = await this.send({ type: \"get_git_branch\" });\n\t\treturn this.getData<{ branch: string | null }>(response).branch;\n\t}\n\n\t/**\n\t * Get cached same-day cost across all sessions, primed by the server on first call.\n\t */\n\tasync getDailyCost(): Promise<number> {\n\t\tconst response = await this.send({ type: \"get_daily_cost\" });\n\t\treturn this.getData<{ cost: number }>(response).cost;\n\t}\n\n\t/**\n\t * Set model by provider and ID.\n\t */\n\tasync setModel(provider: string, modelId: string): Promise<{ provider: string; id: string }> {\n\t\tconst response = await this.send({ type: \"set_model\", provider, modelId });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Cycle to next model.\n\t */\n\tasync cycleModel(): Promise<{\n\t\tmodel: { provider: string; id: string };\n\t\tthinkingLevel: ThinkingLevel;\n\t\tisScoped: boolean;\n\t} | null> {\n\t\tconst response = await this.send({ type: \"cycle_model\" });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Get list of available models.\n\t */\n\tasync getAvailableModels(): Promise<ModelInfo[]> {\n\t\tconst response = await this.send({ type: \"get_available_models\" });\n\t\treturn this.getData<{ models: ModelInfo[] }>(response).models;\n\t}\n\n\t/**\n\t * Resolve a model pattern using the same logic as CLI/TUI.\n\t * Runs server-side so API keys never leave the process.\n\t * Returns null if no match found.\n\t */\n\tasync resolveModel(pattern: string): Promise<{ model: ModelInfo; warning?: string } | null> {\n\t\tconst response = await this.send({ type: \"resolve_model\", pattern });\n\t\treturn this.getData<{ model: ModelInfo; warning?: string } | null>(response);\n\t}\n\n\t/**\n\t * Hatch a new buddy companion. Runs inside the agent process\n\t * so API keys never leave the process boundary.\n\t */\n\tasync buddyHatch(): Promise<import(\"../../core/buddy/buddy-types.js\").BuddyState> {\n\t\tconst response = await this.send({ type: \"buddy_hatch\" });\n\t\treturn this.getData<{ state: import(\"../../core/buddy/buddy-types.js\").BuddyState }>(response).state;\n\t}\n\n\t/**\n\t * Reroll the buddy companion. Runs inside the agent process\n\t * so API keys never leave the process boundary.\n\t */\n\tasync buddyReroll(): Promise<import(\"../../core/buddy/buddy-types.js\").BuddyState> {\n\t\tconst response = await this.send({ type: \"buddy_reroll\" });\n\t\treturn this.getData<{ state: import(\"../../core/buddy/buddy-types.js\").BuddyState }>(response).state;\n\t}\n\n\t/**\n\t * Set thinking level.\n\t */\n\tasync setThinkingLevel(level: ThinkingLevel): Promise<void> {\n\t\tawait this.send({ type: \"set_thinking_level\", level });\n\t}\n\n\t/**\n\t * Cycle thinking level.\n\t */\n\tasync cycleThinkingLevel(): Promise<{ level: ThinkingLevel } | null> {\n\t\tconst response = await this.send({ type: \"cycle_thinking_level\" });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Set steering mode.\n\t */\n\tasync setSteeringMode(mode: \"all\" | \"one-at-a-time\"): Promise<void> {\n\t\tawait this.send({ type: \"set_steering_mode\", mode });\n\t}\n\n\t/**\n\t * Set follow-up mode.\n\t */\n\tasync setFollowUpMode(mode: \"all\" | \"one-at-a-time\"): Promise<void> {\n\t\tawait this.send({ type: \"set_follow_up_mode\", mode });\n\t}\n\n\t/**\n\t * Get pending steering and follow-up messages without clearing them.\n\t */\n\tasync getPendingMessages(): Promise<RpcPendingMessages> {\n\t\tconst response = await this.send({ type: \"get_pending_messages\" });\n\t\treturn this.getData<RpcPendingMessages>(response);\n\t}\n\n\t/**\n\t * Clear pending steering and follow-up messages, returning the cleared text.\n\t */\n\tasync clearPendingMessages(): Promise<RpcPendingMessages> {\n\t\tconst response = await this.send({ type: \"clear_pending_messages\" });\n\t\treturn this.getData<RpcPendingMessages>(response);\n\t}\n\n\t/**\n\t * Compact session context.\n\t */\n\tasync compact(customInstructions?: string): Promise<CompactionResult> {\n\t\tconst response = await this.send({ type: \"compact\", customInstructions });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Set auto-compaction enabled/disabled.\n\t */\n\tasync setAutoCompaction(enabled: boolean): Promise<void> {\n\t\tawait this.send({ type: \"set_auto_compaction\", enabled });\n\t}\n\n\t/**\n\t * Abort in-progress compaction.\n\t */\n\tasync abortCompaction(): Promise<void> {\n\t\tawait this.send({ type: \"abort_compaction\" });\n\t}\n\n\t/**\n\t * Set auto-retry enabled/disabled.\n\t */\n\tasync setAutoRetry(enabled: boolean): Promise<void> {\n\t\tawait this.send({ type: \"set_auto_retry\", enabled });\n\t}\n\n\t/**\n\t * Abort in-progress retry.\n\t */\n\tasync abortRetry(): Promise<void> {\n\t\tawait this.send({ type: \"abort_retry\" });\n\t}\n\n\t/**\n\t * Execute a bash command.\n\t */\n\tasync bash(command: string): Promise<BashResult> {\n\t\tconst response = await this.send({ type: \"bash\", command });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Abort running bash command.\n\t */\n\tasync abortBash(): Promise<void> {\n\t\tawait this.send({ type: \"abort_bash\" });\n\t}\n\n\t/**\n\t * Get session statistics.\n\t */\n\tasync getSessionStats(): Promise<SessionStats> {\n\t\tconst response = await this.send({ type: \"get_session_stats\" });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Get performance statistics.\n\t */\n\tasync getPerformanceStats(): Promise<RpcPerformanceStats> {\n\t\tconst response = await this.send({ type: \"get_performance_stats\" });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Export session to HTML.\n\t */\n\tasync exportHtml(outputPath?: string): Promise<{ path: string }> {\n\t\tconst response = await this.send({ type: \"export_html\", outputPath });\n\t\treturn this.getData(response);\n\t}\n\n\t/** Import a JSONL file into the current runtime. */\n\tasync importJsonl(inputPath: string): Promise<{ cancelled: boolean }> {\n\t\tconst response = await this.send({ type: \"import_jsonl\", inputPath });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Switch to a different session file.\n\t * @returns Object with `cancelled: true` if an extension cancelled the switch\n\t */\n\tasync switchSession(sessionPath: string): Promise<{ cancelled: boolean }> {\n\t\tconst response = await this.send({ type: \"switch_session\", sessionPath });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Delete a session file, trying trash first and falling back to unlink.\n\t * Throws on failure, including when attempting to delete the active session.\n\t */\n\tasync deleteSession(sessionPath: string): Promise<{ method: \"trash\" | \"unlink\" }> {\n\t\tconst response = await this.send({ type: \"delete_session\", sessionPath });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Fork from a specific message.\n\t * @returns Object with `text` (the message text) and `cancelled` (if extension cancelled)\n\t */\n\tasync fork(entryId: string): Promise<{ text: string; cancelled: boolean }> {\n\t\tconst response = await this.send({ type: \"fork\", entryId });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Get messages available for forking.\n\t */\n\tasync getForkMessages(): Promise<Array<{ entryId: string; text: string }>> {\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"]}