zidane-gui 0.0.1 → 7.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/out/main/index.js CHANGED
@@ -1,20 +1,25 @@
1
- import { resolve, dirname, join, delimiter, basename } from "node:path";
1
+ import { resolve, join, dirname, delimiter, basename } from "node:path";
2
2
  import { config } from "dotenv";
3
3
  import { app, shell, BrowserWindow, ipcMain, dialog, nativeImage } from "electron";
4
4
  import { randomUUID } from "node:crypto";
5
- import { keybindingsPath, stripJsonComments, ensureKeybindingsFile, readProjects, writeProjects, credentialsPath, applyApiKeyEnv, BUILTIN_PROVIDERS, readCredentials, detectAuth, supportsOAuth, runOAuthLogin, setProviderCredential, compactSummaryEvent, extractEditPayload, pendingInteractionsFromTurns, buildResumedToolResultsTurn, suggestSafelistEntries, addToSafelist, getSafelist, isOnSafelist, previewLine, formatDuration, DEFAULT_SETTINGS, resolveConfig, mcpsWritePath, upsertMcpServer, discoverProjectMcps, removeMcpServer, loadMcpToolsCache, subscribeMcpToolsCache, refreshMcpToolsCatalog, createFileMcpCredentialStore, effectiveContextWindow, getContextWindow, OUTPUT_RESERVE_TOKENS, enabledModelOptions, restoreModelOptions, chatAutoCompactBehavior, buildRunModel, selectActiveTodos, DEFAULT_AGENT_ID, buildSkillsConfig, defaultSkillScanPaths, buildMcpServers, restoreChainFallbacks, createInteractionTools, isTodoTool, discoverAgentsMd, buildPlanSystem, buildBuildSystem, toolCallPreview, parseEditOutcomesFromResult, mergeApprovalAndBodyOutcomes, buildEditOutcomesAnnotation, stripEditOutcomesAnnotation, rewriteMultiEditHeader, toolResultText, formatTaskSummary, previewEditPayload, resolveApprovalForPayload, searchSessionHistory, searchableTurnText, deriveSessionTitle, PRESENT_PLAN_TOOL, ASK_USER_TOOL, filterChainFallbacks, buildModelCatalog, modelsForDescriptor, modelSupportsReasoning, truncateTurnsAt, deleteTurnSafely, generateSessionTitle, writeSessionExport, sumRunCosts, lastContextSizeFromTurns, fmtTokens, listProjectFiles, discoverProjectSkills, readProviderCredential, removeProviderCredential, hasClaudeCodeSetup, countClaudeSessionFiles, importFromClaudeCode, findGitRoot, modelOptionsFor, eventsFromTurns } from "zidane/chat";
6
- import { spawn, execFileSync } from "node:child_process";
7
- import { mkdirSync, readFileSync, writeFileSync, existsSync, copyFileSync, readdirSync, rmSync } from "node:fs";
5
+ import { parseEditorCommand, keybindingsPath, stripJsonComments, ensureKeybindingsFile, readProjects, writeProjects, credentialsPath, applyApiKeyEnv, BUILTIN_PROVIDERS, readCredentials, detectAuth, supportsOAuth, runOAuthLogin, setProviderCredential, scopeCwd, resolveConfig, DEFAULT_SETTINGS, enforceSettingsInvariants, mcpsWritePath, upsertMcpServer, discoverProjectMcps, removeMcpServer, loadMcpToolsCache, subscribeMcpToolsCache, refreshMcpToolsCatalog, createFileMcpCredentialStore, createChatHost, toTodosSnapshot, searchSessionHistory, searchableTurnText, deriveSessionTitle, toolCallPreview, modelChainMetadata, sessionModelFallbacks, enabledModelOptions, buildModelCatalog, modelsForDescriptor, modelSupportsReasoning, getContextWindow, truncateTurnsAt, deleteTurnSafely, generateSessionTitle, writeSessionExport, toolResultText, sumRunCosts, resolveSessionCwd, effectiveContextWindow, lastContextSizeFromTurns, fmtTokens, selectActiveTodos, setTodosForRun, sanitizeTodoItems, DEFAULT_MAX_TODO_ITEMS, fetchAllProviderUsage, fetchProviderUsage, listProjectFiles, discoverProjectSkills, discoverProjectPlugins, readProviderCredential, removeProviderCredential, setPreferredCredential, hasClaudeCodeSetup, countClaudeSessionFiles, importFromClaudeCode, isMainSession, findGitRoot, restoreModelOptions, modelOptionsFor, eventsFromTurns } from "zidane/chat";
6
+ import { spawn, execFile } from "node:child_process";
7
+ import { mkdirSync, readFileSync, writeFileSync, readdirSync, existsSync, copyFileSync, rmSync } from "node:fs";
8
8
  import { homedir, userInfo } from "node:os";
9
- import { compactConversation, applyCompactSummaryCutoff, summaryToTurn, buildPostCompactAttachments, selectFilesFromSession, flattenTurns, formatTokenUsage, toWireConfigSchema, resolveCompletionSubmit, inlineLoadedExtension, discoverAndBuildExtensionRegistry, consoleSink, disposeExtensionRegistry, installExtensionFromSpec, ExtensionInstallError, updateInstalledExtension, removeInstalledExtension, sanitizeExtensionConfigActionPatch, loginMcpServer, McpOAuthProvider, EXTENSION_EDIT_METADATA_KEY, readSkillEditMarker, SKILL_EDIT_METADATA_KEY, composeExtensionPreset, extensionDirForCwd, withZidaneExtensionSkill, withZidaneSkillEditSkill, resolvePersistDir, resolveTasksDir, createAgent, connectMcpServers, createProcessContext, isSpawnTool, ZIDANE_EXTENSION_SKILL_NAME, ZIDANE_SKILL_EDIT_SKILL_NAME, parseCommandInvocation, createLogger, executeCommand, commandBlockToEvent, generateStructuredData, commandBlocksToContent, extensionScaffold, resolveInlineSuggestion, createPathAutocompleteProvider, editSessionMetadata } from "zidane";
10
- import { loadSession, createSession } from "zidane/session";
9
+ import { migrateSessionArtifactDirs, createRingBufferSink, fanoutSink, consoleSink, createLogger, createExtensionBus, toWireConfigSchema, resolveCompletionSubmit, inlineLoadedExtension, discoverAndBuildExtensionRegistry, disposeExtensionRegistry, installExtensionFromSpec, ExtensionInstallError, updateInstalledExtension, removeInstalledExtension, sanitizeExtensionConfigActionPatch, loginMcpServer, McpOAuthProvider, extensionScaffold, resolveInlineSuggestion, createPathAutocompleteProvider, editSessionMetadata, loadSession } from "zidane";
10
+ import { IPC_BUILD_ID, defaultSocketPath, probeSocket, connectIpcClient, IpcVersionMismatchError } from "zidane/ipc";
11
11
  import { DatabaseSync } from "node:sqlite";
12
- import { readFile } from "node:fs/promises";
12
+ import { P as PARENT_USER_TURN, u as usageAssistantDaily$1, b as usageUserDaily$1, a as usageSessionDaily$1 } from "./chunks/usage-sql-BdDLRz11.js";
13
13
  import { installSkillFromSpec, SkillInstallError } from "zidane/skills";
14
+ import { promisify } from "node:util";
15
+ import { Worker } from "node:worker_threads";
14
16
  import { setImmediate as setImmediate$1 } from "node:timers/promises";
15
- import { nonOwningMcpView } from "zidane/mcp";
16
17
  import { BASH_CALL_ID_PREFIX } from "zidane/chat/pure";
17
18
  import { tailTruncate } from "zidane/tools";
19
+ import __cjs_mod__ from "node:module";
20
+ const __filename = import.meta.filename;
21
+ const __dirname = import.meta.dirname;
22
+ const require2 = __cjs_mod__.createRequire(import.meta.url);
18
23
  let resolvedDir = null;
19
24
  function userDataDir() {
20
25
  if (resolvedDir) {
@@ -23,10 +28,14 @@ function userDataDir() {
23
28
  const override = process.env.ZIDANE_GUI_DATA_DIR?.trim();
24
29
  const prefix = (process.env.ZIDANE_PREFIX?.trim() || ".zidane").replace(/\/+$/, "");
25
30
  const storageDir = process.env.ZIDANE_STORAGE_DIR?.trim() || homedir();
26
- const target = override || resolve(storageDir, prefix);
31
+ const target = resolve(override || resolve(storageDir, prefix));
27
32
  try {
28
33
  mkdirSync(target, { recursive: true });
29
34
  resolvedDir = target;
35
+ try {
36
+ migrateSessionArtifactDirs({ userDir: target });
37
+ } catch {
38
+ }
30
39
  return target;
31
40
  } catch {
32
41
  const fallback = app.getPath("userData");
@@ -78,14 +87,17 @@ function saveKeybindings(map) {
78
87
  function keybindingsFilePath() {
79
88
  return keybindingsPath(userDataDir());
80
89
  }
81
- function openKeybindingsInEditor() {
82
- const path = ensureKeybindingsFile(userDataDir());
83
- const editor = process.env.VISUAL || process.env.EDITOR;
84
- if (editor) {
85
- spawnDetached(editor, [path]);
86
- return;
90
+ function openFileInEditor(path) {
91
+ const spec = (process.env.VISUAL ?? "").trim() || (process.env.EDITOR ?? "").trim();
92
+ const tokens = spec ? parseEditorCommand(spec) : [];
93
+ if (tokens.length === 0) {
94
+ return spawnDetached("open", [path]);
87
95
  }
88
- spawnDetached("open", [path]);
96
+ const [cmd, ...args] = tokens;
97
+ return spawnDetached(cmd, [...args, path]);
98
+ }
99
+ function openKeybindingsInEditor() {
100
+ return openFileInEditor(ensureKeybindingsFile(userDataDir()));
89
101
  }
90
102
  function listSafelist() {
91
103
  const file = readProjects(userDataDir());
@@ -128,11 +140,20 @@ async function removeSafelistEntry(project, entry) {
128
140
  });
129
141
  }
130
142
  function spawnDetached(cmd, args) {
131
- try {
132
- const child = spawn(cmd, args, { detached: true, stdio: "ignore" });
133
- child.unref();
134
- } catch {
135
- }
143
+ return new Promise((resolve2, reject) => {
144
+ let child;
145
+ try {
146
+ child = spawn(cmd, args, { detached: true, stdio: "ignore" });
147
+ } catch (err) {
148
+ reject(err instanceof Error ? err : new Error(String(err)));
149
+ return;
150
+ }
151
+ child.once("error", (err) => reject(new Error(`could not launch ${cmd}: ${err.message}`)));
152
+ child.once("spawn", () => {
153
+ child.unref();
154
+ resolve2();
155
+ });
156
+ });
136
157
  }
137
158
  function applyAuthEnv() {
138
159
  const dir = userDataDir();
@@ -209,22 +230,115 @@ function cancelAllOAuth() {
209
230
  }
210
231
  oauthFlights.clear();
211
232
  }
212
- let store = null;
233
+ const buffer = createRingBufferSink();
234
+ let broadcast$2 = null;
235
+ function installLogBroadcast(fn) {
236
+ broadcast$2 = fn;
237
+ }
238
+ const guiLogSink = fanoutSink([
239
+ buffer,
240
+ ...process.env.ZIDANE_DEBUG ? [consoleSink({ minLevel: "warn" })] : [],
241
+ {
242
+ emit(record) {
243
+ broadcast$2?.(record);
244
+ }
245
+ }
246
+ ]);
247
+ function getLogRecords() {
248
+ return buffer.getRecords();
249
+ }
250
+ const guiLog = createLogger(guiLogSink);
213
251
  let db$1 = null;
252
+ function getDb() {
253
+ if (db$1) {
254
+ return db$1;
255
+ }
256
+ const dbPath = join(app.getPath("userData"), "zidane-gui.db");
257
+ db$1 = new DatabaseSync(dbPath);
258
+ db$1.exec("PRAGMA journal_mode = WAL");
259
+ db$1.exec("PRAGMA foreign_keys = ON");
260
+ runMigrations(db$1);
261
+ return db$1;
262
+ }
263
+ function runMigrations(database) {
264
+ database.exec(`CREATE TABLE IF NOT EXISTS schema_migrations (
265
+ name TEXT PRIMARY KEY,
266
+ applied_at INTEGER NOT NULL
267
+ );`);
268
+ const migrationsDir = resolve(import.meta.dirname, "../../migrations");
269
+ const files = readdirSync(migrationsDir).filter((f) => f.endsWith(".sql")).sort();
270
+ const applied = new Set(
271
+ database.prepare("SELECT name FROM schema_migrations").all().map((r) => r.name)
272
+ );
273
+ const insert = database.prepare("INSERT INTO schema_migrations (name, applied_at) VALUES (?, ?)");
274
+ for (const file of files) {
275
+ if (applied.has(file)) {
276
+ continue;
277
+ }
278
+ const sql = readFileSync(join(migrationsDir, file), "utf8");
279
+ database.exec("BEGIN");
280
+ try {
281
+ database.exec(sql);
282
+ insert.run(file, Date.now());
283
+ database.exec("COMMIT");
284
+ } catch (err) {
285
+ try {
286
+ database.exec("ROLLBACK");
287
+ } catch {
288
+ }
289
+ throw err;
290
+ }
291
+ }
292
+ }
293
+ const settingsRepo = {
294
+ get(key) {
295
+ const row = getDb().prepare("SELECT value FROM settings WHERE key = ?").get(key);
296
+ return row?.value ?? null;
297
+ },
298
+ set(key, value) {
299
+ getDb().prepare("INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(key, value);
300
+ },
301
+ delete(key) {
302
+ getDb().prepare("DELETE FROM settings WHERE key = ?").run(key);
303
+ }
304
+ };
305
+ const pendingApprovalsRepo = {
306
+ list() {
307
+ const rows = getDb().prepare("SELECT * FROM pending_approvals ORDER BY created_at ASC").all();
308
+ return rows.map((row) => {
309
+ try {
310
+ return JSON.parse(row.payload_json);
311
+ } catch {
312
+ return null;
313
+ }
314
+ }).filter((r) => r !== null);
315
+ },
316
+ insert(req) {
317
+ getDb().prepare("INSERT OR REPLACE INTO pending_approvals (id, chat_id, payload_json, created_at) VALUES (?, ?, ?, ?)").run(req.id, req.sessionId, JSON.stringify(req), Date.now());
318
+ },
319
+ delete(id) {
320
+ getDb().prepare("DELETE FROM pending_approvals WHERE id = ?").run(id);
321
+ },
322
+ clear() {
323
+ getDb().prepare("DELETE FROM pending_approvals").run();
324
+ }
325
+ };
326
+ let store = null;
327
+ let db = null;
214
328
  function sessionsDbPath() {
215
329
  return join(userDataDir(), "sessions.db");
216
330
  }
217
331
  function openDb() {
218
- if (db$1) {
219
- return db$1;
332
+ if (db) {
333
+ return db;
220
334
  }
221
335
  const path = sessionsDbPath();
222
336
  mkdirSync(dirname(path), { recursive: true });
223
- db$1 = new DatabaseSync(path);
224
- db$1.exec("PRAGMA busy_timeout = 5000");
225
- db$1.exec("PRAGMA journal_mode = WAL");
226
- db$1.exec("PRAGMA foreign_keys = ON");
227
- db$1.exec(`
337
+ db = new DatabaseSync(path);
338
+ db.exec("PRAGMA busy_timeout = 5000");
339
+ db.exec("PRAGMA journal_mode = WAL");
340
+ db.exec("PRAGMA foreign_keys = ON");
341
+ db.exec(`
228
342
  CREATE TABLE IF NOT EXISTS sessions (
229
343
  id TEXT PRIMARY KEY,
230
344
  agent_id TEXT,
@@ -235,9 +349,9 @@ function openDb() {
235
349
  updated_at INTEGER NOT NULL
236
350
  )
237
351
  `);
238
- db$1.exec("CREATE INDEX IF NOT EXISTS idx_sessions_agent_id ON sessions(agent_id)");
239
- db$1.exec("CREATE INDEX IF NOT EXISTS idx_sessions_project_root ON sessions(project_root)");
240
- db$1.exec(`
352
+ db.exec("CREATE INDEX IF NOT EXISTS idx_sessions_agent_id ON sessions(agent_id)");
353
+ db.exec("CREATE INDEX IF NOT EXISTS idx_sessions_project_root ON sessions(project_root)");
354
+ db.exec(`
241
355
  CREATE TABLE IF NOT EXISTS turns (
242
356
  session_id TEXT NOT NULL,
243
357
  seq INTEGER NOT NULL,
@@ -246,7 +360,7 @@ function openDb() {
246
360
  FOREIGN KEY (session_id) REFERENCES sessions(id) ON DELETE CASCADE
247
361
  )
248
362
  `);
249
- db$1.exec(`
363
+ db.exec(`
250
364
  CREATE TABLE IF NOT EXISTS runs (
251
365
  session_id TEXT NOT NULL,
252
366
  run_id TEXT NOT NULL,
@@ -256,19 +370,19 @@ function openDb() {
256
370
  FOREIGN KEY (session_id) REFERENCES sessions(id) ON DELETE CASCADE
257
371
  )
258
372
  `);
259
- migrate(db$1, path);
260
- const turnCols = db$1.prepare("PRAGMA table_info(turns)").all();
373
+ migrate(db, path);
374
+ const turnCols = db.prepare("PRAGMA table_info(turns)").all();
261
375
  if (!turnCols.some((c) => c.name === "role")) {
262
- db$1.exec("ALTER TABLE turns ADD COLUMN role TEXT");
376
+ db.exec("ALTER TABLE turns ADD COLUMN role TEXT");
263
377
  }
264
- db$1.exec("CREATE INDEX IF NOT EXISTS idx_turns_role_null ON turns(session_id) WHERE role IS NULL");
265
- const needsRepair = db$1.prepare("SELECT 1 FROM turns WHERE role IS NULL AND json_valid(data) LIMIT 1").get();
378
+ db.exec("CREATE INDEX IF NOT EXISTS idx_turns_role_null ON turns(session_id) WHERE role IS NULL");
379
+ const needsRepair = db.prepare("SELECT 1 FROM turns WHERE role IS NULL AND json_valid(data) LIMIT 1").get();
266
380
  if (needsRepair) {
267
- db$1.exec("UPDATE turns SET role = json_extract(data, '$.role') WHERE role IS NULL AND json_valid(data)");
381
+ db.exec("UPDATE turns SET role = json_extract(data, '$.role') WHERE role IS NULL AND json_valid(data)");
268
382
  }
269
- db$1.exec("CREATE INDEX IF NOT EXISTS idx_turns_session_role ON turns(session_id, role, seq)");
270
- db$1.exec("CREATE INDEX IF NOT EXISTS idx_sessions_updated_at ON sessions(updated_at)");
271
- return db$1;
383
+ db.exec("CREATE INDEX IF NOT EXISTS idx_turns_session_role ON turns(session_id, role, seq)");
384
+ db.exec("CREATE INDEX IF NOT EXISTS idx_sessions_updated_at ON sessions(updated_at)");
385
+ return db;
272
386
  }
273
387
  function withImmediateTransaction(database, fn) {
274
388
  database.exec("BEGIN IMMEDIATE");
@@ -465,12 +579,6 @@ function loadRecentAssistantTurns(id, limit = 50) {
465
579
  const rows = database.prepare("SELECT data FROM turns WHERE session_id = ? AND role = 'assistant' ORDER BY seq DESC LIMIT ?").all(id, limit);
466
580
  return rows.map((r) => JSON.parse(r.data)).reverse();
467
581
  }
468
- const PARENT_USER_TURN = `t.role = 'user' AND json_valid(t.data) AND NOT EXISTS (
469
- SELECT 1 FROM runs r
470
- WHERE r.session_id = t.session_id
471
- AND r.run_id = json_extract(t.data, '$.runId')
472
- AND (json_extract(r.data, '$.depth') > 0 OR json_extract(r.data, '$.parentRunId') IS NOT NULL)
473
- )`;
474
582
  function resolveTurnPageStart(id, beforeSeq, limit) {
475
583
  const database = openDb();
476
584
  const upper = beforeSeq ?? Number.MAX_SAFE_INTEGER;
@@ -579,50 +687,14 @@ function loadTurnWindow(id, fromSeq, beforeSeq) {
579
687
  firstSeq: parsed.length > 0 ? parsed[0].seq : fromSeq
580
688
  };
581
689
  }
582
- const DAY_OF_CREATED_AT = "date(json_extract(t.data, '$.createdAt') / 1000, 'unixepoch', 'localtime')";
583
690
  function usageAssistantDaily() {
584
- const database = openDb();
585
- const rows = database.prepare(
586
- `SELECT ${DAY_OF_CREATED_AT} AS day,
587
- COALESCE(json_extract(t.data, '$.usage.modelId'), 'unknown') AS model,
588
- COUNT(*) AS turns,
589
- SUM(COALESCE(json_extract(t.data, '$.usage.input'), 0)) AS input,
590
- SUM(COALESCE(json_extract(t.data, '$.usage.output'), 0)) AS output,
591
- SUM(COALESCE(json_extract(t.data, '$.usage.cacheRead'), 0)) AS cacheRead,
592
- SUM(COALESCE(json_extract(t.data, '$.usage.cacheCreation'), 0)) AS cacheCreation,
593
- SUM(COALESCE(json_extract(t.data, '$.usage.cost'), 0)) AS cost
594
- FROM turns t
595
- WHERE t.role = 'assistant' AND json_valid(t.data)
596
- GROUP BY day, model
597
- HAVING day IS NOT NULL
598
- ORDER BY day`
599
- ).all();
600
- return rows;
691
+ return usageAssistantDaily$1(openDb());
601
692
  }
602
693
  function usageUserDaily() {
603
- const database = openDb();
604
- const rows = database.prepare(
605
- `SELECT ${DAY_OF_CREATED_AT} AS day,
606
- CAST(strftime('%H', json_extract(t.data, '$.createdAt') / 1000, 'unixepoch', 'localtime') AS INTEGER) AS hour,
607
- COUNT(*) AS messages
608
- FROM turns t
609
- WHERE ${PARENT_USER_TURN}
610
- GROUP BY day, hour
611
- HAVING day IS NOT NULL
612
- ORDER BY day`
613
- ).all();
614
- return rows;
694
+ return usageUserDaily$1(openDb());
615
695
  }
616
696
  function usageSessionDaily() {
617
- const database = openDb();
618
- const rows = database.prepare(
619
- `SELECT date(created_at / 1000, 'unixepoch', 'localtime') AS day, COUNT(*) AS sessions
620
- FROM sessions
621
- GROUP BY day
622
- HAVING day IS NOT NULL
623
- ORDER BY day`
624
- ).all();
625
- return rows;
697
+ return usageSessionDaily$1(openDb());
626
698
  }
627
699
  function saveSync(database, session) {
628
700
  database.prepare(
@@ -825,652 +897,121 @@ function forkSessionRow(opts) {
825
897
  saveSync(database, data);
826
898
  return id;
827
899
  }
828
- async function runCompaction(entry, broadcast2) {
829
- broadcast2({ kind: "compacting:start", sessionId: entry.sessionId });
830
- let ok = false;
831
- entry.compactionController = new AbortController();
832
- const { signal } = entry.compactionController;
833
- try {
834
- const store2 = getSessionStore();
835
- const data = await store2.load(entry.sessionId);
836
- if (!data) {
837
- return;
838
- }
839
- const turns = data.turns;
840
- const compactionProvider = entry.providerDescriptor?.factory() ?? BUILTIN_PROVIDERS[entry.providerKey]?.factory() ?? BUILTIN_PROVIDERS.anthropic.factory();
841
- const result = await compactConversation({
842
- provider: compactionProvider,
843
- model: entry.model,
844
- // Compact the WIRE view (same as the SDK's loop-native path): raw
845
- // turns still contain everything prior markers replaced, so
846
- // re-compacting raw history re-summarizes the same content forever
847
- // and the wire never shrinks.
848
- turns: applyCompactSummaryCutoff(turns),
849
- scope: "tail",
850
- signal
851
- });
852
- const summaryTurn = summaryToTurn({
853
- summary: result.summary,
854
- replacesTurnIds: result.summarizedTurnIds,
855
- usage: result.usage,
856
- model: entry.model
857
- });
858
- const session = entry.agent.session;
859
- const handle = entry.agent.handle ?? void 0;
860
- const attachments = session ? await buildPostCompactAttachments({
861
- recentFiles: selectFilesFromSession(session, handle?.cwd ?? entry.cwd),
862
- activeSkills: entry.agent.activeSkills,
863
- execution: entry.agent.execution,
864
- handle,
865
- // Thread the compaction abort signal so a cancel (timeout in the
866
- // `sendPrompt` barrier, session dispose) stops the post-compact file
867
- // reads instead of letting `entry.compacting` hang on FS I/O. (#6)
868
- signal
869
- }) : { turns: [], restoredFiles: 0, restoredSkills: 0, estimatedTokens: 0 };
870
- const compactedTurns = [summaryTurn, ...attachments.turns];
871
- if (session) {
872
- await session.appendTurns(compactedTurns);
873
- } else {
874
- await store2.appendTurns(entry.sessionId, compactedTurns);
875
- }
876
- const summaryBlock = summaryTurn.content.find((b) => b.type === "compact-summary");
877
- if (summaryBlock && summaryBlock.type === "compact-summary") {
878
- broadcast2({
879
- kind: "event",
880
- sessionId: entry.sessionId,
881
- event: compactSummaryEvent(summaryBlock, summaryTurn.id)
882
- });
883
- }
884
- ok = true;
885
- } catch (err) {
886
- if (signal.aborted) {
887
- broadcast2({
888
- kind: "event",
889
- sessionId: entry.sessionId,
890
- event: { kind: "info", text: "Auto-compaction cancelled." }
891
- });
892
- } else {
893
- broadcast2({
894
- kind: "event",
895
- sessionId: entry.sessionId,
896
- event: { kind: "error", text: `Auto-compaction failed: ${err.message}` }
897
- });
898
- }
899
- } finally {
900
- entry.compactionController = void 0;
901
- broadcast2({ kind: "compacting:end", sessionId: entry.sessionId, ok });
902
- }
903
- }
904
- class EditOutcomeLedger {
905
- _entries = /* @__PURE__ */ new Map();
906
- stash(callId, payload) {
907
- this._entries.set(callId, payload);
908
- }
909
- /** Read + remove the entry for `callId`. `null` when no stash exists. */
910
- drain(callId) {
911
- const entry = this._entries.get(callId);
912
- if (!entry) {
913
- return null;
914
- }
915
- this._entries.delete(callId);
916
- return entry;
917
- }
918
- /** Non-removing peek — used by `tool:before` to paint events without consuming the stash. */
919
- peek(callId) {
920
- return this._entries.get(callId) ?? null;
921
- }
922
- /** Drop entry without reading — used by `tool:error` (no transform on throw path). */
923
- discard(callId) {
924
- this._entries.delete(callId);
925
- }
926
- /** Clear every entry — called on `agent:done` and session disposal. */
927
- clear() {
928
- this._entries.clear();
929
- }
930
- }
931
- async function readFileSafe(path) {
932
- try {
933
- return await readFile(path, "utf8");
934
- } catch {
935
- return "";
936
- }
900
+ let cached = null;
901
+ const runtimeCache = /* @__PURE__ */ new Map();
902
+ function buildOptions() {
903
+ return {
904
+ store: () => getSessionStore()
905
+ };
937
906
  }
938
- function resolveCwdPath(cwd, p) {
939
- if (p.startsWith("/")) {
940
- return p;
907
+ function getResolvedConfig() {
908
+ if (!cached) {
909
+ cached = resolveConfig(buildOptions());
941
910
  }
942
- return `${cwd.replace(/\/$/, "")}/${p.replace(/^\//, "")}`;
911
+ return cached;
943
912
  }
944
- function extractEditPayloadForGate(name, input) {
945
- if (name === "edit" || name === "multi_edit") {
946
- return extractEditPayload(name, input);
947
- }
948
- if (name === "write_file") {
949
- return extractEditPayload(name, input, "");
913
+ async function getRuntimeConfig(cwd) {
914
+ const scoped = scopeCwd(cwd);
915
+ const settings = readSettings();
916
+ const key = extensionCacheKey(scoped, settings);
917
+ const existing = runtimeCache.get(key);
918
+ if (existing) {
919
+ return existing;
950
920
  }
951
- return void 0;
952
- }
953
- function serializePreview(preview) {
954
- return {
955
- diffText: preview.diffText,
956
- perHunkDiff: [...preview.perHunkDiff],
957
- resolution: preview.resolution.map((r) => ({ ...r })),
958
- resolvedPayload: {
959
- ...preview.resolvedPayload,
960
- hunks: preview.resolvedPayload.hunks.map((h) => ({ ...h })),
961
- ...preview.resolvedPayload.outcomes ? { outcomes: preview.resolvedPayload.outcomes.map((o) => ({ ...o })) } : {}
962
- }
963
- };
964
- }
965
- const pending$1 = /* @__PURE__ */ new Map();
966
- const resumedResponses = /* @__PURE__ */ new Map();
967
- const resumedRequestIds = /* @__PURE__ */ new Set();
968
- const flushChains = /* @__PURE__ */ new Map();
969
- function scheduleFlush(sessionId) {
970
- const prior = flushChains.get(sessionId) ?? Promise.resolve();
971
- const next = prior.catch(() => void 0).then(() => flushResumedBatch(sessionId));
972
- flushChains.set(sessionId, next);
973
- next.finally(() => {
974
- if (flushChains.get(sessionId) === next) {
975
- flushChains.delete(sessionId);
921
+ const promise = (async () => {
922
+ const extensionRegistry = await getExtensionRegistry(scoped, settings);
923
+ return resolveConfig({
924
+ ...buildOptions(),
925
+ cwd: scoped,
926
+ extensionRegistry
927
+ });
928
+ })();
929
+ runtimeCache.set(key, promise);
930
+ promise.catch(() => {
931
+ if (runtimeCache.get(key) === promise) {
932
+ runtimeCache.delete(key);
976
933
  }
977
934
  });
935
+ return promise;
978
936
  }
979
- function broadcast$3(channel, payload) {
980
- for (const win of BrowserWindow.getAllWindows()) {
981
- win.webContents.send(channel, payload);
982
- }
937
+ function invalidateConfig() {
938
+ cached = null;
939
+ runtimeCache.clear();
983
940
  }
984
- function makeRequestInteractionForSession(sessionId) {
985
- return (request) => {
986
- return new Promise((resolve2, reject) => {
987
- pending$1.set(request.id, { sessionId, request, resolve: resolve2, reject, live: true });
988
- broadcast$3("interactions:request", { sessionId, request, live: true });
989
- });
941
+ const LEGACY_SQLITE_KEY = "chat_settings";
942
+ const LEGACY_SQLITE_BACKUP_KEY = "chat_settings_migrated_backup";
943
+ function mergedFrom(state) {
944
+ const loaded = state.settings ?? {};
945
+ const interactionMode = loaded.interactionMode === "ask" || loaded.interactionMode === "skip" || loaded.interactionMode === "disabled" ? loaded.interactionMode : loaded.allowInteraction === false ? "disabled" : "ask";
946
+ const merged = {
947
+ ...DEFAULT_SETTINGS,
948
+ ...loaded,
949
+ interactionMode
990
950
  };
951
+ delete merged.allowInteraction;
952
+ return merged;
991
953
  }
992
- function resolveInteraction(requestId, response) {
993
- const slot = pending$1.get(requestId);
994
- if (!slot) {
995
- return { ok: false };
996
- }
997
- pending$1.delete(requestId);
998
- if (slot.live) {
999
- slot.resolve(response);
1000
- broadcast$3("interactions:resolved", { sessionId: slot.sessionId, requestId });
1001
- return { ok: true };
1002
- }
1003
- const bucket = resumedResponses.get(slot.sessionId) ?? /* @__PURE__ */ new Map();
1004
- bucket.set(requestId, response);
1005
- resumedResponses.set(slot.sessionId, bucket);
1006
- scheduleFlush(slot.sessionId);
1007
- broadcast$3("interactions:resolved", { sessionId: slot.sessionId, requestId });
1008
- return { ok: true };
1009
- }
1010
- function cancelInteraction(requestId, reason = "Interaction cancelled by user.") {
1011
- const slot = pending$1.get(requestId);
1012
- if (!slot) {
1013
- return { ok: false };
1014
- }
1015
- pending$1.delete(requestId);
1016
- resumedRequestIds.delete(requestId);
1017
- if (slot.live) {
1018
- slot.reject(new Error(reason));
1019
- }
1020
- broadcast$3("interactions:resolved", { sessionId: slot.sessionId, requestId });
1021
- return { ok: true };
1022
- }
1023
- async function flushResumedBatch(sessionId) {
1024
- const responses = resumedResponses.get(sessionId);
1025
- if (!responses || responses.size === 0) {
1026
- return;
1027
- }
1028
- const store2 = getSessionStore();
1029
- const data = await store2.load(sessionId);
1030
- if (!data) {
1031
- return;
1032
- }
1033
- const orphans = pendingInteractionsFromTurns(data.turns);
1034
- if (orphans.length === 0) {
1035
- resumedResponses.delete(sessionId);
1036
- return;
1037
- }
1038
- if (!orphans.every((r) => responses.has(r.id))) {
1039
- return;
1040
- }
1041
- const turn = buildResumedToolResultsTurn(orphans, responses, {
1042
- turnId: randomUUID()
1043
- });
1044
- await store2.appendTurns(sessionId, [turn]);
1045
- for (const r of orphans) {
1046
- pending$1.delete(r.id);
1047
- resumedRequestIds.delete(r.id);
1048
- }
1049
- resumedResponses.delete(sessionId);
954
+ function readSettings() {
955
+ return mergedFrom(getResolvedConfig().stateStore.load());
1050
956
  }
1051
- function listPendingInteractions(sessionId) {
1052
- const out = [];
1053
- for (const slot of pending$1.values()) {
1054
- if (sessionId && slot.sessionId !== sessionId) {
957
+ function foreignConfigFlags(settings = readSettings()) {
958
+ return {
959
+ foreignAgents: settings.importForeignConfigs === true,
960
+ ruler: settings.importRulerConfigs !== false
961
+ };
962
+ }
963
+ function writeSettingsPatch(patch) {
964
+ const { stateStore } = getResolvedConfig();
965
+ const state = stateStore.load();
966
+ const prev = mergedFrom(state);
967
+ const actualPatch = {};
968
+ const changed = /* @__PURE__ */ new Set();
969
+ for (const key of Object.keys(patch)) {
970
+ if (settingsValueEqual(prev[key], patch[key])) {
1055
971
  continue;
1056
972
  }
1057
- out.push({ sessionId: slot.sessionId, request: slot.request, live: slot.live });
973
+ Object.assign(actualPatch, { [key]: patch[key] });
974
+ changed.add(key);
1058
975
  }
1059
- return out;
1060
- }
1061
- async function rehydratePendingInteractions(sessionId) {
1062
- const store2 = getSessionStore();
1063
- const data = await store2.load(sessionId);
1064
- if (!data) {
1065
- return;
976
+ if (changed.size === 0) {
977
+ return { next: prev, changed };
1066
978
  }
1067
- const orphans = pendingInteractionsFromTurns(data.turns);
1068
- for (const request of orphans) {
1069
- if (pending$1.has(request.id)) {
1070
- continue;
979
+ const merged = { ...prev, ...actualPatch };
980
+ const next = enforceSettingsInvariants(merged);
981
+ for (const key of Object.keys(next)) {
982
+ if (!settingsValueEqual(merged[key], next[key])) {
983
+ changed.add(key);
1071
984
  }
1072
- pending$1.set(request.id, {
1073
- sessionId,
1074
- request,
1075
- live: false,
1076
- /**
1077
- * No live caller on the resume path — `resolveInteraction` reads
1078
- * the slot's `live` flag and routes to `flushResumedBatch`
1079
- * instead of calling these. Keep them as no-ops so the slot
1080
- * shape stays uniform.
1081
- */
1082
- resolve: () => void 0,
1083
- reject: () => void 0
1084
- });
1085
- resumedRequestIds.add(request.id);
1086
- broadcast$3("interactions:request", { sessionId, request, live: false });
1087
985
  }
986
+ stateStore.save({ ...state, settings: next });
987
+ return { next, changed };
1088
988
  }
1089
- function clearPendingInteractions(sessionId) {
1090
- for (const [id, slot] of pending$1) {
1091
- if (slot.sessionId === sessionId) {
1092
- if (slot.live) {
1093
- slot.reject(new Error("Session disposed before interaction resolved."));
989
+ function initSettings() {
990
+ const { stateStore, initialSettings } = getResolvedConfig();
991
+ const state = stateStore.load();
992
+ const slice = { ...initialSettings };
993
+ const raw = settingsRepo.get(LEGACY_SQLITE_KEY);
994
+ if (raw !== null) {
995
+ try {
996
+ const parsed = JSON.parse(raw);
997
+ if (isPlainRecord(parsed)) {
998
+ const defaults = { ...DEFAULT_SETTINGS };
999
+ const current = { ...slice };
1000
+ for (const [key, value] of Object.entries(parsed)) {
1001
+ if (settingsValueEqual(defaults[key], value) || settingsValueEqual(current[key], value)) {
1002
+ continue;
1003
+ }
1004
+ Object.assign(slice, { [key]: value });
1005
+ }
1094
1006
  }
1095
- pending$1.delete(id);
1096
- resumedRequestIds.delete(id);
1007
+ } catch {
1097
1008
  }
1009
+ settingsRepo.set(LEGACY_SQLITE_BACKUP_KEY, raw);
1010
+ settingsRepo.delete(LEGACY_SQLITE_KEY);
1011
+ console.log(`[zidane-gui] migrated sqlite chat settings into state.json (backup: ${LEGACY_SQLITE_BACKUP_KEY})`);
1098
1012
  }
1099
- resumedResponses.delete(sessionId);
1100
- }
1101
- const DEFAULT_TURN_LIMIT = 12;
1102
- const MAX_TURN_LIMIT = 50;
1103
- const DEFAULT_MAX_CHARS = 2e4;
1104
- const HARD_MAX_CHARS = 6e4;
1105
- function chatReferenceTokensForPrompt(prompt) {
1106
- const out = [];
1107
- const seen = /* @__PURE__ */ new Set();
1108
- const rx = /(^|\s)#(\S+)/g;
1109
- for (const m of prompt.matchAll(rx)) {
1110
- const token = (m[2] ?? "").replace(/[.,;:)\]}!?]+$/, "").replace(/^#/, "").replace(/-/g, "").toLowerCase();
1111
- if (!token || seen.has(token)) continue;
1112
- seen.add(token);
1113
- out.push(token);
1114
- }
1115
- return out;
1116
- }
1117
- function createChatTurnsReadTool(options) {
1118
- return {
1119
- isConcurrencySafe: true,
1120
- spec: {
1121
- name: "read_chat_turns",
1122
- description: "Read selected turns from a previous chat explicitly referenced by the user with `#<chat>` in the current prompt. Refuses chats that were not referenced.",
1123
- inputSchema: {
1124
- type: "object",
1125
- properties: {
1126
- session_id: { type: "string", description: 'The referenced chat id or # token, e.g. "abc123".' },
1127
- from: { type: "integer", description: "1-indexed turn number to start at. Default: 1." },
1128
- limit: { type: "integer", description: `Maximum turns to return. Default: ${DEFAULT_TURN_LIMIT}. Hard cap: ${MAX_TURN_LIMIT}.` },
1129
- max_chars: { type: "integer", description: `Maximum characters to return. Default: ${DEFAULT_MAX_CHARS}. Hard cap: ${HARD_MAX_CHARS}.` }
1130
- },
1131
- required: ["session_id"],
1132
- additionalProperties: false
1133
- }
1134
- },
1135
- async execute(input) {
1136
- const raw = typeof input.session_id === "string" ? input.session_id.trim().replace(/^#/, "") : "";
1137
- if (!raw) return "Read chat error: `session_id` is required.";
1138
- const allowed = normalizeTokens(options.getAllowedTokens());
1139
- if (allowed.length === 0) {
1140
- return "Read chat blocked: no previous chat was referenced in the current user prompt. Ask the user to reference a chat with `#<chat>` first.";
1141
- }
1142
- const resolved = await resolveAllowedSessionId(options.store, raw, allowed);
1143
- if (resolved.kind === "error") return resolved.message;
1144
- const data = await options.store.load(resolved.sessionId);
1145
- if (!data) return `Read chat error: session "${resolved.sessionId}" was not found.`;
1146
- const from = clampInt(input.from, 1, Number.MAX_SAFE_INTEGER, 1);
1147
- const limit = clampInt(input.limit, 1, MAX_TURN_LIMIT, DEFAULT_TURN_LIMIT);
1148
- const maxChars = clampInt(input.max_chars, 1, HARD_MAX_CHARS, DEFAULT_MAX_CHARS);
1149
- const start = Math.max(0, from - 1);
1150
- const turns = await options.store.getTurns(resolved.sessionId, start, limit);
1151
- const rendered = [
1152
- `<chat id="${escapeAttr(data.id)}" title="${escapeAttr(deriveTitle(data.turns, data.metadata))}"${data.projectRoot ? ` project="${escapeAttr(data.projectRoot)}"` : ""}>`,
1153
- `<range from="${start + 1}" returned="${turns.length}" total="${data.turns.length}" />`,
1154
- renderTurns(turns, start),
1155
- "</chat>"
1156
- ].join("\n");
1157
- return rendered.length <= maxChars ? rendered : `${rendered.slice(0, maxChars)}
1158
-
1159
- ...truncated at ${maxChars} characters. Re-read with a narrower range or higher max_chars.`;
1160
- }
1161
- };
1162
- }
1163
- function normalizeToken(token) {
1164
- return token.replace(/^#/, "").replace(/-/g, "").toLowerCase();
1165
- }
1166
- function normalizeTokens(tokens) {
1167
- return Array.from(new Set(tokens.map(normalizeToken).filter(Boolean)));
1168
- }
1169
- async function resolveAllowedSessionId(store2, requested, allowedTokens) {
1170
- const requestedNorm = normalizeToken(requested);
1171
- const ids = await store2.list();
1172
- const allowedIds = ids.filter((id) => {
1173
- const normalizedId = normalizeToken(id);
1174
- return allowedTokens.some((token) => normalizedId.startsWith(token) || token.startsWith(normalizedId));
1175
- });
1176
- const matches = allowedIds.filter((id) => {
1177
- const normalizedId = normalizeToken(id);
1178
- return normalizedId === requestedNorm || normalizedId.startsWith(requestedNorm) || requestedNorm.startsWith(normalizedId);
1179
- });
1180
- if (matches.length === 1) return { kind: "ok", sessionId: matches[0] };
1181
- if (matches.length > 1) {
1182
- return { kind: "error", message: `Read chat error: "${requested}" is ambiguous among ${matches.length} referenced chats. Use a longer # token.` };
1183
- }
1184
- return { kind: "error", message: `Read chat blocked: "${requested}" was not one of the chats referenced in the current user prompt.` };
1185
- }
1186
- function clampInt(value, min, max, fallback) {
1187
- if (typeof value !== "number" || !Number.isFinite(value)) return fallback;
1188
- return Math.max(min, Math.min(max, Math.floor(value)));
1189
- }
1190
- function deriveTitle(turns, metadata) {
1191
- const stored = typeof metadata?.title === "string" ? metadata.title.trim() : "";
1192
- if (stored) return stored;
1193
- const first = turns.find((turn) => turn.role === "user");
1194
- const text = first?.content.find((block) => block.type === "text")?.text.replace(/\s+/g, " ").trim();
1195
- if (!text) return "untitled";
1196
- return text.length > 60 ? `${text.slice(0, 60)}...` : text;
1197
- }
1198
- function renderTurns(turns, startIndex) {
1199
- return turns.map((turn, idx) => {
1200
- const content = turn.content.map(renderBlock).filter(Boolean).join("\n\n");
1201
- return `<turn index="${startIndex + idx + 1}" id="${escapeAttr(turn.id)}" role="${turn.role}">
1202
- ${content}
1203
- </turn>`;
1204
- }).join("\n");
1205
- }
1206
- function renderBlock(block) {
1207
- if (block.type === "text") return block.text;
1208
- if (block.type === "thinking") return `[thinking]
1209
- ${block.text}`;
1210
- if (block.type === "tool_call") return `[tool call: ${block.name}]
1211
- ${stringify(block.input)}`;
1212
- if (block.type === "tool_result") return `[tool result]
1213
- ${typeof block.output === "string" ? block.output : stringify(block.output)}`;
1214
- if (block.type === "compact-summary") return `[compaction summary]
1215
- ${block.summary}`;
1216
- return "";
1217
- }
1218
- function stringify(value) {
1219
- try {
1220
- return JSON.stringify(value, null, 2);
1221
- } catch {
1222
- return String(value);
1223
- }
1224
- }
1225
- function escapeAttr(value) {
1226
- return value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
1227
- }
1228
- let db = null;
1229
- function getDb() {
1230
- if (db) {
1231
- return db;
1232
- }
1233
- const dbPath = join(app.getPath("userData"), "zidane-gui.db");
1234
- db = new DatabaseSync(dbPath);
1235
- db.exec("PRAGMA journal_mode = WAL");
1236
- db.exec("PRAGMA foreign_keys = ON");
1237
- runMigrations(db);
1238
- return db;
1239
- }
1240
- function runMigrations(database) {
1241
- database.exec(`CREATE TABLE IF NOT EXISTS schema_migrations (
1242
- name TEXT PRIMARY KEY,
1243
- applied_at INTEGER NOT NULL
1244
- );`);
1245
- const migrationsDir = resolve(import.meta.dirname, "../../migrations");
1246
- const files = readdirSync(migrationsDir).filter((f) => f.endsWith(".sql")).sort();
1247
- const applied = new Set(
1248
- database.prepare("SELECT name FROM schema_migrations").all().map((r) => r.name)
1249
- );
1250
- const insert = database.prepare("INSERT INTO schema_migrations (name, applied_at) VALUES (?, ?)");
1251
- for (const file of files) {
1252
- if (applied.has(file)) {
1253
- continue;
1254
- }
1255
- const sql = readFileSync(join(migrationsDir, file), "utf8");
1256
- database.exec("BEGIN");
1257
- try {
1258
- database.exec(sql);
1259
- insert.run(file, Date.now());
1260
- database.exec("COMMIT");
1261
- } catch (err) {
1262
- try {
1263
- database.exec("ROLLBACK");
1264
- } catch {
1265
- }
1266
- throw err;
1267
- }
1268
- }
1269
- }
1270
- const settingsRepo = {
1271
- get(key) {
1272
- const row = getDb().prepare("SELECT value FROM settings WHERE key = ?").get(key);
1273
- return row?.value ?? null;
1274
- },
1275
- set(key, value) {
1276
- getDb().prepare("INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(key, value);
1277
- },
1278
- delete(key) {
1279
- getDb().prepare("DELETE FROM settings WHERE key = ?").run(key);
1280
- }
1281
- };
1282
- const pendingApprovalsRepo = {
1283
- list() {
1284
- const rows = getDb().prepare("SELECT * FROM pending_approvals ORDER BY created_at ASC").all();
1285
- return rows.map((row) => {
1286
- try {
1287
- return JSON.parse(row.payload_json);
1288
- } catch {
1289
- return null;
1290
- }
1291
- }).filter((r) => r !== null);
1292
- },
1293
- insert(req) {
1294
- getDb().prepare("INSERT OR REPLACE INTO pending_approvals (id, chat_id, payload_json, created_at) VALUES (?, ?, ?, ?)").run(req.id, req.sessionId, JSON.stringify(req), Date.now());
1295
- },
1296
- delete(id) {
1297
- getDb().prepare("DELETE FROM pending_approvals WHERE id = ?").run(id);
1298
- },
1299
- clear() {
1300
- getDb().prepare("DELETE FROM pending_approvals").run();
1301
- }
1302
- };
1303
- const pending = /* @__PURE__ */ new Map();
1304
- function broadcast$2(channel, payload) {
1305
- for (const win of BrowserWindow.getAllWindows()) {
1306
- win.webContents.send(channel, payload);
1307
- }
1308
- }
1309
- function safelistDataDir() {
1310
- return userDataDir();
1311
- }
1312
- async function requestApproval(input) {
1313
- const safelist = getSafelist(safelistDataDir(), input.cwd);
1314
- if (isOnSafelist(safelist, input.tool, input.input)) {
1315
- return "accept-once";
1316
- }
1317
- const id = randomUUID();
1318
- const full = {
1319
- id,
1320
- sessionId: input.sessionId,
1321
- cwd: input.cwd,
1322
- tool: input.tool,
1323
- input: input.input,
1324
- suggestedSafelistEntries: suggestSafelistEntries(input.tool, input.input),
1325
- ...input.edit ? { edit: input.edit } : {},
1326
- ...input.priorContent !== void 0 ? { priorContent: input.priorContent } : {},
1327
- ...input.preview ? { preview: input.preview } : {},
1328
- /*
1329
- * Omit `originator` when it's the implicit `'parent'` case so the
1330
- * IPC payload stays minimal — renderer treats absence as parent.
1331
- */
1332
- ...input.originator && input.originator.kind === "child" ? { originator: input.originator } : {}
1333
- };
1334
- pendingApprovalsRepo.insert(full);
1335
- return new Promise((resolve2) => {
1336
- pending.set(id, { request: full, resolve: resolve2 });
1337
- broadcast$2("safeMode:request", full);
1338
- });
1339
- }
1340
- function resolveApproval(id, decision) {
1341
- const entry = pending.get(id);
1342
- if (entry && decision === "accept-safelist") {
1343
- try {
1344
- const entries = entry.request.suggestedSafelistEntries ?? suggestSafelistEntries(entry.request.tool, entry.request.input);
1345
- addToSafelist(safelistDataDir(), entry.request.cwd, entries);
1346
- } catch {
1347
- }
1348
- }
1349
- pendingApprovalsRepo.delete(id);
1350
- if (!entry) {
1351
- return;
1352
- }
1353
- pending.delete(id);
1354
- entry.resolve(decision);
1355
- }
1356
- function denyAllPending(sessionId) {
1357
- if (sessionId === void 0) {
1358
- for (const [, entry] of pending) {
1359
- entry.resolve("deny");
1360
- }
1361
- pending.clear();
1362
- pendingApprovalsRepo.clear();
1363
- return;
1364
- }
1365
- for (const [id, entry] of pending) {
1366
- if (entry.request.sessionId !== sessionId) {
1367
- continue;
1368
- }
1369
- entry.resolve("deny");
1370
- pending.delete(id);
1371
- pendingApprovalsRepo.delete(id);
1372
- }
1373
- }
1374
- function listPendingApprovals() {
1375
- return pendingApprovalsRepo.list();
1376
- }
1377
- function rehydratePendingApprovals() {
1378
- const stored = pendingApprovalsRepo.list();
1379
- for (const req of stored) {
1380
- if (pending.has(req.id)) {
1381
- continue;
1382
- }
1383
- pending.set(req.id, { request: req, resolve: () => void 0 });
1384
- }
1385
- }
1386
- function buildSpawnStartEvent(ctx, startedAt) {
1387
- const taskPreview = previewLine(ctx.task, 80);
1388
- return {
1389
- kind: "spawn-start",
1390
- text: ctx.resumesChildId ? `resumes ${ctx.resumesChildId} · ${taskPreview}` : taskPreview,
1391
- childId: ctx.id,
1392
- depth: ctx.depth ?? 1,
1393
- spawn: { startedAt },
1394
- ...ctx.model ? { model: ctx.model } : {}
1395
- };
1396
- }
1397
- function buildSpawnEndEvent(ctx, started, now = Date.now()) {
1398
- const tag = ctx.status === "aborted" ? "aborted" : ctx.status === "error" ? "error" : "done";
1399
- const startedAt = started?.startedAt;
1400
- const elapsed = startedAt !== void 0 ? ` · ${formatDuration(now - startedAt)}` : "";
1401
- const cost = flattenTurns(ctx.stats).reduce((sum, turn) => sum + (turn.cost ?? 0), 0);
1402
- const costPart = cost > 0 ? ` · $${cost.toFixed(cost < 0.01 ? 4 : 2)}` : "";
1403
- const segments = `${elapsed}${costPart}`;
1404
- const usage = formatTokenUsage(ctx.stats);
1405
- return {
1406
- kind: "spawn-end",
1407
- text: segments ? `${tag}${segments} · ${usage}` : `${tag} ${usage}`,
1408
- childId: ctx.id,
1409
- depth: ctx.depth ?? 1,
1410
- spawn: { startedAt: startedAt ?? now, ...started?.task ? { task: started.task } : {}, turns: ctx.stats.turns },
1411
- ...started?.model ? { model: started.model } : {}
1412
- };
1413
- }
1414
- const LEGACY_SQLITE_KEY = "chat_settings";
1415
- const LEGACY_SQLITE_BACKUP_KEY = "chat_settings_migrated_backup";
1416
- function mergedFrom(state) {
1417
- return { ...DEFAULT_SETTINGS, ...state.settings };
1418
- }
1419
- function readSettings() {
1420
- return mergedFrom(getResolvedConfig().stateStore.load());
1421
- }
1422
- function foreignConfigFlags(settings = readSettings()) {
1423
- return {
1424
- foreignAgents: settings.importForeignConfigs === true,
1425
- ruler: settings.importRulerConfigs !== false
1426
- };
1427
- }
1428
- function writeSettingsPatch(patch) {
1429
- const { stateStore } = getResolvedConfig();
1430
- const state = stateStore.load();
1431
- const prev = mergedFrom(state);
1432
- const actualPatch = {};
1433
- const changed = /* @__PURE__ */ new Set();
1434
- for (const key of Object.keys(patch)) {
1435
- if (settingsValueEqual(prev[key], patch[key])) {
1436
- continue;
1437
- }
1438
- Object.assign(actualPatch, { [key]: patch[key] });
1439
- changed.add(key);
1440
- }
1441
- if (changed.size === 0) {
1442
- return { next: prev, changed };
1443
- }
1444
- const next = { ...prev, ...actualPatch };
1445
- stateStore.save({ ...state, settings: next });
1446
- return { next, changed };
1447
- }
1448
- function initSettings() {
1449
- const { stateStore, initialSettings } = getResolvedConfig();
1450
- const state = stateStore.load();
1451
- const slice = { ...initialSettings };
1452
- const raw = settingsRepo.get(LEGACY_SQLITE_KEY);
1453
- if (raw !== null) {
1454
- try {
1455
- const parsed = JSON.parse(raw);
1456
- if (isPlainRecord(parsed)) {
1457
- const defaults = { ...DEFAULT_SETTINGS };
1458
- const current = { ...slice };
1459
- for (const [key, value] of Object.entries(parsed)) {
1460
- if (settingsValueEqual(defaults[key], value) || settingsValueEqual(current[key], value)) {
1461
- continue;
1462
- }
1463
- Object.assign(slice, { [key]: value });
1464
- }
1465
- }
1466
- } catch {
1467
- }
1468
- settingsRepo.set(LEGACY_SQLITE_BACKUP_KEY, raw);
1469
- settingsRepo.delete(LEGACY_SQLITE_KEY);
1470
- console.log(`[zidane-gui] migrated sqlite chat settings into state.json (backup: ${LEGACY_SQLITE_BACKUP_KEY})`);
1471
- }
1472
- if (!settingsValueEqual(slice, state.settings ?? {})) {
1473
- stateStore.save({ ...state, settings: slice });
1013
+ if (!settingsValueEqual(slice, state.settings ?? {})) {
1014
+ stateStore.save({ ...state, settings: slice });
1474
1015
  }
1475
1016
  }
1476
1017
  function settingsValueEqual(a, b) {
@@ -1491,10 +1032,16 @@ function isPlainRecord(value) {
1491
1032
  return typeof value === "object" && value !== null && !Array.isArray(value);
1492
1033
  }
1493
1034
  const registryCache = /* @__PURE__ */ new Map();
1035
+ const extensionBus = createExtensionBus();
1036
+ function deliverExtensionSignal(envelope) {
1037
+ extensionBus.deliver(envelope);
1038
+ }
1039
+ function onExtensionBusEmit(fn) {
1040
+ return extensionBus.onEmit(fn);
1041
+ }
1494
1042
  const MAX_CACHED_REGISTRIES = 16;
1495
1043
  function extensionSink() {
1496
- return process.env.ZIDANE_DEBUG ? consoleSink({ minLevel: "warn" }) : { emit() {
1497
- } };
1044
+ return guiLogSink;
1498
1045
  }
1499
1046
  function trustProjectExtensions(settings) {
1500
1047
  return settings.loadProjectExtensions === true || process.env.ZIDANE_GUI_TRUST_PROJECT_EXTENSIONS === "1" || process.env.ZIDANE_TRUST_PROJECT_EXTENSIONS === "1";
@@ -1535,6 +1082,7 @@ async function getExtensionRegistry(cwd, settings) {
1535
1082
  trustProjectExtensions: trustProjectExtensions(settings),
1536
1083
  inlineExtensions: inline,
1537
1084
  sink: extensionSink(),
1085
+ bus: extensionBus,
1538
1086
  // Live config reads for extension hooks/tools — read the DB fresh on
1539
1087
  // each `ctx.config.get` (not the snapshot used for the cache key), so
1540
1088
  // a value edited via Settings takes effect without a registry rebuild.
@@ -1674,328 +1222,38 @@ async function loadDevExtensions() {
1674
1222
  return [];
1675
1223
  }
1676
1224
  }
1677
- function folderlessCwd() {
1678
- return homedir();
1679
- }
1680
- function resolveSessionCwd(row) {
1681
- const recorded = typeof row.metadata?.cwd === "string" ? row.metadata.cwd : void 0;
1682
- return recorded || row.projectRoot || folderlessCwd();
1683
- }
1684
- function scopeCwd(cwd) {
1685
- return cwd || folderlessCwd();
1686
- }
1687
- let cached = null;
1688
- const runtimeCache = /* @__PURE__ */ new Map();
1689
- function buildOptions() {
1690
- return {
1691
- store: () => getSessionStore()
1692
- };
1225
+ function guiPrefix() {
1226
+ return process.env.ZIDANE_PREFIX ?? ".zidane";
1693
1227
  }
1694
- function getResolvedConfig() {
1695
- if (!cached) {
1696
- cached = resolveConfig(buildOptions());
1697
- }
1698
- return cached;
1228
+ function compactPath(path) {
1229
+ const home = homedir();
1230
+ return path.startsWith(home) ? `~${path.slice(home.length)}` : path;
1699
1231
  }
1700
- async function getRuntimeConfig(cwd) {
1701
- const scoped = scopeCwd(cwd);
1702
- const settings = readSettings();
1703
- const key = extensionCacheKey(scoped, settings);
1704
- const existing = runtimeCache.get(key);
1705
- if (existing) {
1706
- return existing;
1707
- }
1708
- const promise = (async () => {
1709
- const extensionRegistry = await getExtensionRegistry(scoped, settings);
1710
- return resolveConfig({
1711
- ...buildOptions(),
1712
- cwd: scoped,
1713
- extensionRegistry
1232
+ async function installExtension(opts) {
1233
+ let result;
1234
+ try {
1235
+ result = await installExtensionFromSpec({
1236
+ source: opts.req.source,
1237
+ ...opts.req.extension !== void 0 ? { extension: opts.req.extension } : {},
1238
+ scope: opts.req.scope,
1239
+ cwd: opts.cwd,
1240
+ prefix: guiPrefix(),
1241
+ ...opts.onProgress !== void 0 ? { onProgress: opts.onProgress } : {}
1714
1242
  });
1715
- })();
1716
- runtimeCache.set(key, promise);
1717
- promise.catch(() => {
1718
- if (runtimeCache.get(key) === promise) {
1719
- runtimeCache.delete(key);
1243
+ } catch (err) {
1244
+ if (err instanceof ExtensionInstallError && err.code === "exists") {
1245
+ throw new Error("already installed — use Update on its row to refresh it, or Remove it first.");
1720
1246
  }
1721
- });
1722
- return promise;
1723
- }
1724
- function invalidateConfig() {
1725
- cached = null;
1726
- runtimeCache.clear();
1727
- }
1728
- const CACHE_TTL_MS = 6e4;
1729
- let bucketCache = null;
1730
- let bucketLoad = null;
1731
- function invalidateUsageSummaryCache() {
1732
- bucketCache = null;
1733
- }
1734
- function yieldToPump() {
1735
- return new Promise((resolve2) => setImmediate(resolve2));
1736
- }
1737
- async function loadBuckets(now) {
1738
- if (bucketCache && now - bucketCache.loadedAt < CACHE_TTL_MS) {
1739
- return bucketCache;
1740
- }
1741
- bucketLoad ??= (async () => {
1742
- try {
1743
- const assistant = usageAssistantDaily();
1744
- await yieldToPump();
1745
- const user = usageUserDaily();
1746
- await yieldToPump();
1747
- const sessions = usageSessionDaily();
1748
- bucketCache = { assistant, user, sessions, loadedAt: Date.now() };
1749
- return bucketCache;
1750
- } finally {
1751
- bucketLoad = null;
1752
- }
1753
- })();
1754
- return bucketLoad;
1755
- }
1756
- function localDayString(d) {
1757
- const y = d.getFullYear();
1758
- const m = String(d.getMonth() + 1).padStart(2, "0");
1759
- const day = String(d.getDate()).padStart(2, "0");
1760
- return `${y}-${m}-${day}`;
1761
- }
1762
- function cutoffDay(today, days) {
1763
- const d = new Date(today.getFullYear(), today.getMonth(), today.getDate() - (days - 1));
1764
- return localDayString(d);
1765
- }
1766
- function providerOfModel(modelId) {
1767
- const id = modelId.toLowerCase();
1768
- if (id === "unknown") {
1769
- return "Unknown";
1770
- }
1771
- if (id.includes("/")) {
1772
- return "OpenRouter";
1773
- }
1774
- if (id.startsWith("claude")) {
1775
- return "Anthropic";
1776
- }
1777
- if (id.startsWith("gpt") || /^o\d/.test(id) || id.startsWith("codex")) {
1778
- return "OpenAI";
1779
- }
1780
- if (id.startsWith("gemini")) {
1781
- return "Google";
1782
- }
1783
- if (id.startsWith("grok")) {
1784
- return "xAI";
1785
- }
1786
- if (id.startsWith("zai") || id.startsWith("glm")) {
1787
- return "Z.AI";
1788
- }
1789
- if (id.startsWith("deepseek")) {
1790
- return "DeepSeek";
1791
- }
1792
- if (id.startsWith("kimi") || id.startsWith("moonshot")) {
1793
- return "Moonshot";
1794
- }
1795
- if (id.startsWith("mistral") || id.startsWith("devstral") || id.startsWith("magistral")) {
1796
- return "Mistral";
1797
- }
1798
- return "Other";
1799
- }
1800
- function computeStreaks(activeDays, today) {
1801
- if (activeDays.size === 0) {
1802
- return { current: 0, longest: 0 };
1803
- }
1804
- const dayMs = 864e5;
1805
- const anchor = new Date(today.getFullYear(), today.getMonth(), today.getDate());
1806
- let current = 0;
1807
- let probe = anchor.getTime();
1808
- if (!activeDays.has(localDayString(new Date(probe)))) {
1809
- probe -= dayMs;
1810
- }
1811
- while (activeDays.has(localDayString(new Date(probe)))) {
1812
- current += 1;
1813
- probe -= dayMs;
1814
- }
1815
- const sorted = [...activeDays].sort();
1816
- let longest = 0;
1817
- let run = 0;
1818
- let prev = null;
1819
- for (const day of sorted) {
1820
- const [y, m, d] = day.split("-").map(Number);
1821
- const t = new Date(y, m - 1, d).getTime();
1822
- run = prev !== null && t - prev === dayMs ? run + 1 : 1;
1823
- prev = t;
1824
- if (run > longest) {
1825
- longest = run;
1826
- }
1827
- }
1828
- return { current, longest };
1829
- }
1830
- let cachedFirstName;
1831
- function resolveFirstName() {
1832
- if (cachedFirstName !== void 0) {
1833
- return cachedFirstName;
1834
- }
1835
- let name = null;
1836
- if (process.platform === "darwin") {
1837
- try {
1838
- const full = execFileSync("id", ["-F"], { timeout: 500 }).toString().trim();
1839
- name = full.split(/\s+/)[0] || null;
1840
- } catch {
1841
- name = null;
1842
- }
1843
- }
1844
- if (!name) {
1845
- try {
1846
- const login = userInfo().username;
1847
- const token = login.split(/[._-]/)[0] ?? "";
1848
- name = token.length >= 2 ? token[0].toUpperCase() + token.slice(1) : null;
1849
- } catch {
1850
- name = null;
1851
- }
1852
- }
1853
- cachedFirstName = name;
1854
- return cachedFirstName;
1855
- }
1856
- const CHART_MAX_DAYS = 120;
1857
- const HEATMAP_DAYS = 182;
1858
- async function getUsageSummary(range, now = /* @__PURE__ */ new Date()) {
1859
- const buckets = await loadBuckets(now.getTime());
1860
- const cutoff = range === "7d" ? cutoffDay(now, 7) : range === "30d" ? cutoffDay(now, 30) : null;
1861
- const inRange = (day) => cutoff === null || day >= cutoff;
1862
- const models = /* @__PURE__ */ new Map();
1863
- const chartCutoff = cutoffDay(now, CHART_MAX_DAYS);
1864
- const daily = [];
1865
- let totalTokens = 0;
1866
- let tokensIn = 0;
1867
- let tokensOut = 0;
1868
- let totalCost = 0;
1869
- for (const row of buckets.assistant) {
1870
- if (!inRange(row.day)) {
1871
- continue;
1872
- }
1873
- const rowIn = row.input + row.cacheRead + row.cacheCreation;
1874
- const rowTokens = rowIn + row.output;
1875
- tokensIn += rowIn;
1876
- tokensOut += row.output;
1877
- totalTokens += rowTokens;
1878
- totalCost += row.cost;
1879
- let m = models.get(row.model);
1880
- if (!m) {
1881
- m = { modelId: row.model, provider: providerOfModel(row.model), turns: 0, tokensIn: 0, tokensOut: 0, cost: 0 };
1882
- models.set(row.model, m);
1883
- }
1884
- m.turns += row.turns;
1885
- m.tokensIn += rowIn;
1886
- m.tokensOut += row.output;
1887
- m.cost += row.cost;
1888
- if (row.day >= chartCutoff) {
1889
- daily.push({ day: row.day, modelId: row.model, tokens: rowTokens });
1890
- }
1891
- }
1892
- const modelRows = [...models.values()].filter((m) => m.tokensIn + m.tokensOut > 0 || m.cost > 0).sort((a, b) => b.tokensIn + b.tokensOut - (a.tokensIn + a.tokensOut));
1893
- const providerTotals = /* @__PURE__ */ new Map();
1894
- for (const m of modelRows) {
1895
- providerTotals.set(m.provider, (providerTotals.get(m.provider) ?? 0) + m.cost);
1896
- }
1897
- const providers = [...providerTotals.entries()].map(([provider, cost]) => ({ provider, cost })).filter((p) => p.cost > 0).sort((a, b) => b.cost - a.cost);
1898
- let messages = 0;
1899
- const activeDays = /* @__PURE__ */ new Set();
1900
- const hourCounts = new Array(24).fill(0);
1901
- for (const row of buckets.user) {
1902
- if (!inRange(row.day)) {
1903
- continue;
1904
- }
1905
- messages += row.messages;
1906
- activeDays.add(row.day);
1907
- if (row.hour >= 0 && row.hour < 24) {
1908
- hourCounts[row.hour] += row.messages;
1909
- }
1910
- }
1911
- const streaks = computeStreaks(activeDays, now);
1912
- let peakHour = null;
1913
- let peakCount = 0;
1914
- hourCounts.forEach((count, hour) => {
1915
- if (count > peakCount) {
1916
- peakCount = count;
1917
- peakHour = hour;
1918
- }
1919
- });
1920
- let sessions = 0;
1921
- for (const row of buckets.sessions) {
1922
- if (inRange(row.day)) {
1923
- sessions += row.sessions;
1924
- }
1925
- }
1926
- const heatmapCutoff = cutoffDay(now, HEATMAP_DAYS);
1927
- const heatmapTokens = /* @__PURE__ */ new Map();
1928
- const heatmapMessages = /* @__PURE__ */ new Map();
1929
- for (const row of buckets.assistant) {
1930
- if (row.day >= heatmapCutoff) {
1931
- const t = row.input + row.cacheRead + row.cacheCreation + row.output;
1932
- heatmapTokens.set(row.day, (heatmapTokens.get(row.day) ?? 0) + t);
1933
- }
1934
- }
1935
- for (const row of buckets.user) {
1936
- if (row.day >= heatmapCutoff) {
1937
- heatmapMessages.set(row.day, (heatmapMessages.get(row.day) ?? 0) + row.messages);
1938
- }
1939
- }
1940
- const heatmapDays = /* @__PURE__ */ new Set([...heatmapTokens.keys(), ...heatmapMessages.keys()]);
1941
- const heatmap = [...heatmapDays].sort().map((day) => ({ day, tokens: heatmapTokens.get(day) ?? 0, messages: heatmapMessages.get(day) ?? 0 }));
1942
- const favoriteModel = modelRows.reduce(
1943
- (best, m) => best === null || m.turns > best.turns ? m : best,
1944
- null
1945
- );
1946
- return {
1947
- range,
1948
- userName: resolveFirstName(),
1949
- sessions,
1950
- messages,
1951
- totalTokens,
1952
- tokensIn,
1953
- tokensOut,
1954
- totalCost,
1955
- activeDays: activeDays.size,
1956
- currentStreak: streaks.current,
1957
- longestStreak: streaks.longest,
1958
- peakHour,
1959
- favoriteModel: favoriteModel?.modelId ?? null,
1960
- models: modelRows,
1961
- modelDaily: daily,
1962
- providers,
1963
- heatmap,
1964
- generatedAt: now.getTime()
1965
- };
1966
- }
1967
- function guiPrefix() {
1968
- return process.env.ZIDANE_PREFIX ?? ".zidane";
1969
- }
1970
- function compactPath(path) {
1971
- const home = homedir();
1972
- return path.startsWith(home) ? `~${path.slice(home.length)}` : path;
1973
- }
1974
- async function installExtension(opts) {
1975
- let result;
1976
- try {
1977
- result = await installExtensionFromSpec({
1978
- source: opts.req.source,
1979
- ...opts.req.extension !== void 0 ? { extension: opts.req.extension } : {},
1980
- scope: opts.req.scope,
1981
- cwd: opts.cwd,
1982
- prefix: guiPrefix(),
1983
- ...opts.onProgress !== void 0 ? { onProgress: opts.onProgress } : {}
1984
- });
1985
- } catch (err) {
1986
- if (err instanceof ExtensionInstallError && err.code === "exists") {
1987
- throw new Error("already installed — use Update on its row to refresh it, or Remove it first.");
1988
- }
1989
- throw err;
1990
- }
1991
- const warnings = [...result.warnings];
1992
- if (opts.req.scope === "project" && !opts.trusted) {
1993
- warnings.push(
1994
- "Project extensions are currently untrusted — enable “Load project extensions” in Settings › Safety for it to load."
1995
- );
1996
- }
1997
- const warn = warnings.length > 0 ? ` — ⚠ ${warnings.join(" ⚠ ")}` : "";
1998
- return { name: result.name, message: `installed "${result.name}" (${result.provenance})${warn}` };
1247
+ throw err;
1248
+ }
1249
+ const warnings = [...result.warnings];
1250
+ if (opts.req.scope === "project" && !opts.trusted) {
1251
+ warnings.push(
1252
+ "Project extensions are currently untrusted — enable “Load project extensions” in Settings › Safety for it to load."
1253
+ );
1254
+ }
1255
+ const warn = warnings.length > 0 ? ` — ⚠ ${warnings.join(" ⚠ ")}` : "";
1256
+ return { name: result.name, message: `installed "${result.name}" (${result.provenance})${warn}` };
1999
1257
  }
2000
1258
  async function updateExtension(opts) {
2001
1259
  const result = await updateInstalledExtension({ dir: opts.dir, cwd: opts.cwd, prefix: guiPrefix() });
@@ -2284,130 +1542,367 @@ function startMcpLogin(cwd, name) {
2284
1542
  queueMicrotask(() => broadcast$1({ requestId, name, kind: "error", error }));
2285
1543
  return { requestId };
2286
1544
  }
2287
- const config2 = match.config;
2288
- if (config2.transport === "stdio") {
2289
- const error = `MCP server "${name}" uses stdio transport — OAuth login is HTTP-only.`;
2290
- queueMicrotask(() => broadcast$1({ requestId, name, kind: "error", error }));
2291
- return { requestId };
1545
+ const config2 = match.config;
1546
+ if (config2.transport === "stdio") {
1547
+ const error = `MCP server "${name}" uses stdio transport — OAuth login is HTTP-only.`;
1548
+ queueMicrotask(() => broadcast$1({ requestId, name, kind: "error", error }));
1549
+ return { requestId };
1550
+ }
1551
+ const controller = new AbortController();
1552
+ flights.set(requestId, { name, controller });
1553
+ latestFlightByName.set(name, requestId);
1554
+ lastError.delete(name);
1555
+ void loginMcpServer(config2, {
1556
+ store: getStore(),
1557
+ signal: controller.signal,
1558
+ onAuthorizationUrl: (url) => {
1559
+ const urlString = url.toString();
1560
+ broadcast$1({ requestId, name, kind: "url", url: urlString });
1561
+ safeOpenExternal(urlString);
1562
+ }
1563
+ }).then(() => {
1564
+ if (latestFlightByName.get(name) !== requestId) {
1565
+ return;
1566
+ }
1567
+ lastError.delete(name);
1568
+ broadcast$1({ requestId, name, kind: "authed" });
1569
+ }).catch((err) => {
1570
+ if (latestFlightByName.get(name) !== requestId) {
1571
+ return;
1572
+ }
1573
+ if (controller.signal.aborted) {
1574
+ return;
1575
+ }
1576
+ const message = err?.message ?? String(err);
1577
+ lastError.set(name, message);
1578
+ broadcast$1({ requestId, name, kind: "error", error: message });
1579
+ }).finally(() => {
1580
+ flights.delete(requestId);
1581
+ if (latestFlightByName.get(name) === requestId) {
1582
+ latestFlightByName.delete(name);
1583
+ }
1584
+ });
1585
+ return { requestId };
1586
+ }
1587
+ function logoutMcpServer(_cwd, name) {
1588
+ getStore().delete(name);
1589
+ lastError.delete(name);
1590
+ lastToolError.delete(name);
1591
+ }
1592
+ function cancelMcpLogin(requestId) {
1593
+ const entry = flights.get(requestId);
1594
+ if (!entry) {
1595
+ return;
1596
+ }
1597
+ entry.controller.abort();
1598
+ flights.delete(requestId);
1599
+ if (latestFlightByName.get(entry.name) === requestId) {
1600
+ latestFlightByName.delete(entry.name);
1601
+ }
1602
+ }
1603
+ function cancelAllMcpLogins() {
1604
+ for (const [, entry] of flights) {
1605
+ entry.controller.abort();
1606
+ }
1607
+ flights.clear();
1608
+ latestFlightByName.clear();
1609
+ }
1610
+ const CACHE_TTL_MS = 6e4;
1611
+ let bucketCache = null;
1612
+ let bucketLoad = null;
1613
+ function invalidateUsageSummaryCache() {
1614
+ bucketCache = null;
1615
+ }
1616
+ function yieldToPump() {
1617
+ return new Promise((resolve2) => setImmediate(resolve2));
1618
+ }
1619
+ function loadBucketsOffThread(dbPath) {
1620
+ return new Promise((resolve2, reject) => {
1621
+ const worker = new Worker(join(__dirname, "usage-worker.js"));
1622
+ const timer = setTimeout(() => {
1623
+ void worker.terminate();
1624
+ reject(new Error("usage worker timed out"));
1625
+ }, 3e4);
1626
+ const done = () => {
1627
+ clearTimeout(timer);
1628
+ void worker.terminate();
1629
+ };
1630
+ worker.once("message", (reply) => {
1631
+ done();
1632
+ if (reply.ok) {
1633
+ resolve2(reply.buckets);
1634
+ } else {
1635
+ reject(new Error(reply.error));
1636
+ }
1637
+ });
1638
+ worker.once("error", (err) => {
1639
+ done();
1640
+ reject(err);
1641
+ });
1642
+ worker.once("exit", (code) => {
1643
+ if (code !== 0) {
1644
+ done();
1645
+ reject(new Error(`usage worker exited with ${code}`));
1646
+ }
1647
+ });
1648
+ worker.postMessage({ dbPath });
1649
+ });
1650
+ }
1651
+ async function loadBucketsInProcess() {
1652
+ const assistant = usageAssistantDaily();
1653
+ await yieldToPump();
1654
+ const user = usageUserDaily();
1655
+ await yieldToPump();
1656
+ const sessions = usageSessionDaily();
1657
+ return { assistant, user, sessions };
1658
+ }
1659
+ async function loadBuckets(now) {
1660
+ if (bucketCache && now - bucketCache.loadedAt < CACHE_TTL_MS) {
1661
+ return bucketCache;
1662
+ }
1663
+ bucketLoad ??= (async () => {
1664
+ try {
1665
+ let buckets;
1666
+ try {
1667
+ buckets = await loadBucketsOffThread(sessionsDbPath());
1668
+ } catch {
1669
+ buckets = await loadBucketsInProcess();
1670
+ }
1671
+ bucketCache = { ...buckets, loadedAt: Date.now() };
1672
+ return bucketCache;
1673
+ } finally {
1674
+ bucketLoad = null;
1675
+ }
1676
+ })();
1677
+ return bucketLoad;
1678
+ }
1679
+ function localDayString(d) {
1680
+ const y = d.getFullYear();
1681
+ const m = String(d.getMonth() + 1).padStart(2, "0");
1682
+ const day = String(d.getDate()).padStart(2, "0");
1683
+ return `${y}-${m}-${day}`;
1684
+ }
1685
+ function cutoffDay(today, days) {
1686
+ const d = new Date(today.getFullYear(), today.getMonth(), today.getDate() - (days - 1));
1687
+ return localDayString(d);
1688
+ }
1689
+ function providerOfModel(modelId) {
1690
+ const id = modelId.toLowerCase();
1691
+ if (id === "unknown") {
1692
+ return "Unknown";
1693
+ }
1694
+ if (id.includes("/")) {
1695
+ return "OpenRouter";
1696
+ }
1697
+ if (id.startsWith("claude")) {
1698
+ return "Anthropic";
1699
+ }
1700
+ if (id.startsWith("gpt") || /^o\d/.test(id) || id.startsWith("codex")) {
1701
+ return "OpenAI";
1702
+ }
1703
+ if (id.startsWith("gemini")) {
1704
+ return "Google";
1705
+ }
1706
+ if (id.startsWith("grok")) {
1707
+ return "xAI";
1708
+ }
1709
+ if (id.startsWith("zai") || id.startsWith("glm")) {
1710
+ return "Z.AI";
1711
+ }
1712
+ if (id.startsWith("deepseek")) {
1713
+ return "DeepSeek";
1714
+ }
1715
+ if (id.startsWith("kimi") || id.startsWith("moonshot")) {
1716
+ return "Moonshot";
1717
+ }
1718
+ if (id.startsWith("mistral") || id.startsWith("devstral") || id.startsWith("magistral")) {
1719
+ return "Mistral";
1720
+ }
1721
+ return "Other";
1722
+ }
1723
+ function computeStreaks(activeDays, today) {
1724
+ if (activeDays.size === 0) {
1725
+ return { current: 0, longest: 0 };
1726
+ }
1727
+ const dayMs = 864e5;
1728
+ const anchor = new Date(today.getFullYear(), today.getMonth(), today.getDate());
1729
+ let current = 0;
1730
+ let probe = anchor.getTime();
1731
+ if (!activeDays.has(localDayString(new Date(probe)))) {
1732
+ probe -= dayMs;
1733
+ }
1734
+ while (activeDays.has(localDayString(new Date(probe)))) {
1735
+ current += 1;
1736
+ probe -= dayMs;
1737
+ }
1738
+ const sorted = [...activeDays].sort();
1739
+ let longest = 0;
1740
+ let run = 0;
1741
+ let prev = null;
1742
+ for (const day of sorted) {
1743
+ const [y, m, d] = day.split("-").map(Number);
1744
+ const t = new Date(y, m - 1, d).getTime();
1745
+ run = prev !== null && t - prev === dayMs ? run + 1 : 1;
1746
+ prev = t;
1747
+ if (run > longest) {
1748
+ longest = run;
1749
+ }
1750
+ }
1751
+ return { current, longest };
1752
+ }
1753
+ let cachedFirstName;
1754
+ const execFileAsync = promisify(execFile);
1755
+ async function resolveFirstName() {
1756
+ if (cachedFirstName !== void 0) {
1757
+ return cachedFirstName;
1758
+ }
1759
+ let name = null;
1760
+ try {
1761
+ if (process.platform === "darwin") {
1762
+ const { stdout } = await execFileAsync("id", ["-F"], { timeout: 500 });
1763
+ const full = stdout.trim();
1764
+ name = full.split(/\s+/)[0] || null;
1765
+ }
1766
+ } catch {
1767
+ }
1768
+ if (!name) {
1769
+ try {
1770
+ const login = userInfo().username;
1771
+ const token = login.split(/[._-]/)[0] ?? "";
1772
+ name = token.length >= 2 ? token[0].toUpperCase() + token.slice(1) : null;
1773
+ } catch {
1774
+ name = null;
1775
+ }
2292
1776
  }
2293
- const controller = new AbortController();
2294
- flights.set(requestId, { name, controller });
2295
- latestFlightByName.set(name, requestId);
2296
- lastError.delete(name);
2297
- void loginMcpServer(config2, {
2298
- store: getStore(),
2299
- signal: controller.signal,
2300
- onAuthorizationUrl: (url) => {
2301
- const urlString = url.toString();
2302
- broadcast$1({ requestId, name, kind: "url", url: urlString });
2303
- safeOpenExternal(urlString);
1777
+ cachedFirstName = name;
1778
+ return cachedFirstName;
1779
+ }
1780
+ const CHART_MAX_DAYS = 120;
1781
+ const HEATMAP_DAYS = 182;
1782
+ async function getUsageSummary(range, now = /* @__PURE__ */ new Date()) {
1783
+ const [buckets, userName] = await Promise.all([loadBuckets(now.getTime()), resolveFirstName()]);
1784
+ const cutoff = range === "7d" ? cutoffDay(now, 7) : range === "30d" ? cutoffDay(now, 30) : null;
1785
+ const inRange = (day) => cutoff === null || day >= cutoff;
1786
+ const models = /* @__PURE__ */ new Map();
1787
+ const chartCutoff = cutoffDay(now, CHART_MAX_DAYS);
1788
+ const daily = [];
1789
+ let totalTokens = 0;
1790
+ let tokensIn = 0;
1791
+ let tokensOut = 0;
1792
+ let totalCost = 0;
1793
+ for (const row of buckets.assistant) {
1794
+ if (!inRange(row.day)) {
1795
+ continue;
2304
1796
  }
2305
- }).then(() => {
2306
- if (latestFlightByName.get(name) !== requestId) {
2307
- return;
1797
+ const rowIn = row.input + row.cacheRead + row.cacheCreation;
1798
+ const rowTokens = rowIn + row.output;
1799
+ tokensIn += rowIn;
1800
+ tokensOut += row.output;
1801
+ totalTokens += rowTokens;
1802
+ totalCost += row.cost;
1803
+ let m = models.get(row.model);
1804
+ if (!m) {
1805
+ m = { modelId: row.model, provider: providerOfModel(row.model), turns: 0, tokensIn: 0, tokensOut: 0, cost: 0 };
1806
+ models.set(row.model, m);
2308
1807
  }
2309
- lastError.delete(name);
2310
- broadcast$1({ requestId, name, kind: "authed" });
2311
- }).catch((err) => {
2312
- if (latestFlightByName.get(name) !== requestId) {
2313
- return;
1808
+ m.turns += row.turns;
1809
+ m.tokensIn += rowIn;
1810
+ m.tokensOut += row.output;
1811
+ m.cost += row.cost;
1812
+ if (row.day >= chartCutoff) {
1813
+ daily.push({ day: row.day, modelId: row.model, tokens: rowTokens });
2314
1814
  }
2315
- if (controller.signal.aborted) {
2316
- return;
1815
+ }
1816
+ const modelRows = [...models.values()].filter((m) => m.tokensIn + m.tokensOut > 0 || m.cost > 0).sort((a, b) => b.tokensIn + b.tokensOut - (a.tokensIn + a.tokensOut));
1817
+ const providerTotals = /* @__PURE__ */ new Map();
1818
+ for (const m of modelRows) {
1819
+ providerTotals.set(m.provider, (providerTotals.get(m.provider) ?? 0) + m.cost);
1820
+ }
1821
+ const providers = [...providerTotals.entries()].map(([provider, cost]) => ({ provider, cost })).filter((p) => p.cost > 0).sort((a, b) => b.cost - a.cost);
1822
+ let messages = 0;
1823
+ const activeDays = /* @__PURE__ */ new Set();
1824
+ const hourCounts = new Array(24).fill(0);
1825
+ for (const row of buckets.user) {
1826
+ if (!inRange(row.day)) {
1827
+ continue;
2317
1828
  }
2318
- const message = err?.message ?? String(err);
2319
- lastError.set(name, message);
2320
- broadcast$1({ requestId, name, kind: "error", error: message });
2321
- }).finally(() => {
2322
- flights.delete(requestId);
2323
- if (latestFlightByName.get(name) === requestId) {
2324
- latestFlightByName.delete(name);
1829
+ messages += row.messages;
1830
+ activeDays.add(row.day);
1831
+ if (row.hour >= 0 && row.hour < 24) {
1832
+ hourCounts[row.hour] += row.messages;
1833
+ }
1834
+ }
1835
+ const streaks = computeStreaks(activeDays, now);
1836
+ let peakHour = null;
1837
+ let peakCount = 0;
1838
+ hourCounts.forEach((count, hour) => {
1839
+ if (count > peakCount) {
1840
+ peakCount = count;
1841
+ peakHour = hour;
2325
1842
  }
2326
1843
  });
2327
- return { requestId };
2328
- }
2329
- function logoutMcpServer(_cwd, name) {
2330
- getStore().delete(name);
2331
- lastError.delete(name);
2332
- lastToolError.delete(name);
2333
- }
2334
- function cancelMcpLogin(requestId) {
2335
- const entry = flights.get(requestId);
2336
- if (!entry) {
2337
- return;
1844
+ let sessions = 0;
1845
+ for (const row of buckets.sessions) {
1846
+ if (inRange(row.day)) {
1847
+ sessions += row.sessions;
1848
+ }
2338
1849
  }
2339
- entry.controller.abort();
2340
- flights.delete(requestId);
2341
- if (latestFlightByName.get(entry.name) === requestId) {
2342
- latestFlightByName.delete(entry.name);
1850
+ const heatmapCutoff = cutoffDay(now, HEATMAP_DAYS);
1851
+ const heatmapTokens = /* @__PURE__ */ new Map();
1852
+ const heatmapMessages = /* @__PURE__ */ new Map();
1853
+ for (const row of buckets.assistant) {
1854
+ if (row.day >= heatmapCutoff) {
1855
+ const t = row.input + row.cacheRead + row.cacheCreation + row.output;
1856
+ heatmapTokens.set(row.day, (heatmapTokens.get(row.day) ?? 0) + t);
1857
+ }
2343
1858
  }
2344
- }
2345
- function cancelAllMcpLogins() {
2346
- for (const [, entry] of flights) {
2347
- entry.controller.abort();
1859
+ for (const row of buckets.user) {
1860
+ if (row.day >= heatmapCutoff) {
1861
+ heatmapMessages.set(row.day, (heatmapMessages.get(row.day) ?? 0) + row.messages);
1862
+ }
2348
1863
  }
2349
- flights.clear();
2350
- latestFlightByName.clear();
1864
+ const heatmapDays = /* @__PURE__ */ new Set([...heatmapTokens.keys(), ...heatmapMessages.keys()]);
1865
+ const heatmap = [...heatmapDays].sort().map((day) => ({ day, tokens: heatmapTokens.get(day) ?? 0, messages: heatmapMessages.get(day) ?? 0 }));
1866
+ const favoriteModel = modelRows.reduce(
1867
+ (best, m) => best === null || m.turns > best.turns ? m : best,
1868
+ null
1869
+ );
1870
+ return {
1871
+ range,
1872
+ userName,
1873
+ sessions,
1874
+ messages,
1875
+ totalTokens,
1876
+ tokensIn,
1877
+ tokensOut,
1878
+ totalCost,
1879
+ activeDays: activeDays.size,
1880
+ currentStreak: streaks.current,
1881
+ longestStreak: streaks.longest,
1882
+ peakHour,
1883
+ favoriteModel: favoriteModel?.modelId ?? null,
1884
+ models: modelRows,
1885
+ modelDaily: daily,
1886
+ providers,
1887
+ heatmap,
1888
+ generatedAt: now.getTime()
1889
+ };
2351
1890
  }
2352
- const active = /* @__PURE__ */ new Map();
2353
- const MAX_IDLE_ACTIVE_AGENTS = 8;
2354
- const pendingBuilds = /* @__PURE__ */ new Map();
2355
- let teardownGeneration = 0;
2356
- function discardRun(run) {
2357
- run.compactionController?.abort();
2358
- run.controller.abort();
2359
- run.ledger.clear();
2360
- run.work.clear();
2361
- run.agent.destroy().catch(() => void 0);
1891
+ function sendChatStream(signal) {
1892
+ sendToAllWindows("chat:stream", signal);
2362
1893
  }
2363
- function disposeActiveEntry(sessionId, entry) {
2364
- entry.compactionController?.abort();
2365
- entry.controller.abort();
2366
- entry.ledger.clear();
2367
- entry.work.clear();
2368
- broadcastWorkSnapshot({ sessionId, work: entry.work });
2369
- entry.agent.destroy().catch(() => void 0);
2370
- active.delete(sessionId);
2371
- }
2372
- function pruneIdleAgents() {
2373
- const idle = [...active.entries()].filter(([, entry]) => !entry.agent.isRunning && !entry.compacting && entry.work.size === 0).sort((a, b) => a[1].lastUsedAt - b[1].lastUsedAt);
2374
- const overflow = active.size - MAX_IDLE_ACTIVE_AGENTS;
2375
- if (overflow <= 0) {
1894
+ function sendToAllWindows(channel, payload, opts) {
1895
+ const windows = BrowserWindow.getAllWindows();
1896
+ if (windows.length === 0) {
1897
+ if (!opts?.bufferedElsewhere) {
1898
+ console.warn(`[stream] broadcast had 0 windows; event lost on ${channel}`);
1899
+ }
2376
1900
  return;
2377
1901
  }
2378
- for (const [sessionId, entry] of idle.slice(0, overflow)) {
2379
- clearPendingInteractions(sessionId);
2380
- denyAllPending(sessionId);
2381
- disposeActiveEntry(sessionId, entry);
1902
+ for (const win of windows) {
1903
+ win.webContents.send(channel, payload);
2382
1904
  }
2383
1905
  }
2384
- const COMPACTION_BARRIER_TIMEOUT_MS = 10 * 60 * 1e3;
2385
- function isThinkingLevel$1(value) {
2386
- return value === "off" || value === "minimal" || value === "low" || value === "medium" || value === "high" || value === "xhigh" || value === "max" || value === "adaptive";
2387
- }
2388
- const DEBUG_STREAM = process.env.ZIDANE_GUI_DEBUG_STREAM === "1";
2389
- function broadcastTodosSnapshot(entry) {
2390
- const session = entry.agent.session;
2391
- if (!session) return;
2392
- const state = selectActiveTodos(session);
2393
- broadcast({
2394
- kind: "todos:snapshot",
2395
- sessionId: entry.sessionId,
2396
- snapshot: {
2397
- runId: state.runId,
2398
- todos: [...state.todos],
2399
- archive: [...state.archive],
2400
- inProgress: state.inProgress,
2401
- tally: state.tally
2402
- }
2403
- });
2404
- }
2405
- function visibleWorkItems(entry) {
2406
- return [...entry.work.values()].filter((item) => item.childId === void 0);
2407
- }
2408
- function broadcastWorkSnapshot(entry) {
2409
- broadcast({ kind: "work:snapshot", sessionId: entry.sessionId, items: visibleWorkItems(entry) });
2410
- }
2411
1906
  const DELTA_FLUSH_MS = 16;
2412
1907
  const pendingDeltas = [];
2413
1908
  let deltaFlushTimer = null;
@@ -2434,7 +1929,7 @@ function flushPendingDeltas(sessionId) {
2434
1929
  }
2435
1930
  for (const d of drained) {
2436
1931
  const event = d.kind === "markdown" ? { kind: "markdown", text: d.text, streaming: true, turnId: d.turnId } : { kind: "thinking", text: d.text, turnId: d.turnId };
2437
- sendToWindows({ kind: "event", sessionId: d.sessionId, event });
1932
+ sendChatStream({ kind: "event", sessionId: d.sessionId, event });
2438
1933
  }
2439
1934
  }
2440
1935
  function queueStreamDelta(sessionId, kind, delta, turnId) {
@@ -2448,1096 +1943,477 @@ function queueStreamDelta(sessionId, kind, delta, turnId) {
2448
1943
  deltaFlushTimer = setTimeout(flushPendingDeltas, DELTA_FLUSH_MS);
2449
1944
  }
2450
1945
  }
2451
- function broadcast(signal) {
2452
- flushPendingDeltas("sessionId" in signal && typeof signal.sessionId === "string" ? signal.sessionId : void 0);
2453
- if (signal.kind === "run:end") {
2454
- invalidateUsageSummaryCache();
1946
+ function resetDeltaCoalescer() {
1947
+ if (deltaFlushTimer) {
1948
+ clearTimeout(deltaFlushTimer);
1949
+ deltaFlushTimer = null;
2455
1950
  }
2456
- sendToWindows(signal);
1951
+ pendingDeltas.length = 0;
2457
1952
  }
2458
- function sendToWindows(signal) {
2459
- if (DEBUG_STREAM) {
2460
- const preview = signal.kind === "event" && signal.event.kind === "markdown" ? `markdown:"${signal.event.text.slice(0, 30)}${signal.event.text.length > 30 ? "…" : ""}"` : signal.kind === "event" ? `event:${signal.event.kind}${signal.event.kind === "tool" || signal.event.kind === "tool-result" ? `(${signal.event.tool})` : ""}` : signal.kind === "run:start" ? `run:start runId=${signal.runId}` : signal.kind === "run:end" ? `run:end ok=${signal.ok}${signal.error ? ` error="${signal.error}"` : ""}` : signal.kind;
2461
- console.log(`[stream] → ${preview}`);
2462
- }
2463
- const windows = BrowserWindow.getAllWindows();
2464
- if (windows.length === 0) {
2465
- console.warn("[stream] broadcast had 0 windows; event lost:", signal.kind);
2466
- return;
2467
- }
2468
- for (const win of windows) {
2469
- win.webContents.send("chat:stream", signal);
1953
+ function isStreamDelta(event) {
1954
+ if (event.childId !== void 0) {
1955
+ return false;
2470
1956
  }
1957
+ return event.kind === "markdown" && event.streaming === true || event.kind === "thinking";
2471
1958
  }
2472
- function resultToText(result) {
2473
- if (typeof result === "string") {
2474
- return result;
1959
+ let daemonSignalsLive = false;
1960
+ let daemonHealth = "disconnected";
1961
+ function setDaemonHealth(next) {
1962
+ if (daemonHealth === next) {
1963
+ return;
2475
1964
  }
2476
- try {
2477
- return toolResultText(result);
2478
- } catch {
2479
- return JSON.stringify(result);
1965
+ daemonHealth = next;
1966
+ daemonSignalsLive = next === "connected";
1967
+ for (const window of BrowserWindow.getAllWindows()) {
1968
+ window.webContents.send("daemon:state", { connected: daemonSignalsLive, health: next });
2480
1969
  }
2481
1970
  }
2482
- function buildProvider(providers, providerKey = "anthropic") {
2483
- applyAuthEnv();
2484
- const descriptor = providerDescriptorFor(providers, providerKey);
2485
- try {
2486
- return descriptor.factory();
2487
- } catch (err) {
2488
- const message = err.message ?? String(err);
2489
- if (/No API key found|no credential|not authenticated/i.test(message)) {
2490
- throw new Error(`No credentials for ${descriptor.label}. Open Settings → Authentication to sign in.`);
2491
- }
2492
- throw err;
2493
- }
1971
+ function setDaemonSignalsLive(live) {
1972
+ setDaemonHealth(live ? "connected" : "disconnected");
2494
1973
  }
2495
- function runCapsFromSettings(settings) {
2496
- const caps = {};
2497
- if (settings.resumeOnMaxTokens) {
2498
- caps.resumeOnMaxTokens = true;
2499
- }
2500
- if (settings.maxOutputTokens > 0) {
2501
- caps.maxTokens = settings.maxOutputTokens;
2502
- }
2503
- if (settings.maxTurns > 0) {
2504
- caps.maxTurns = settings.maxTurns;
2505
- }
2506
- if (settings.maxCostUsd > 0) {
2507
- caps.maxCostUsd = settings.maxCostUsd;
2508
- }
2509
- if (settings.maxTotalTokens > 0) {
2510
- caps.maxTotalTokens = settings.maxTotalTokens;
2511
- }
2512
- if (settings.maxWallMinutes > 0) {
2513
- caps.maxWallMs = settings.maxWallMinutes * 6e4;
2514
- }
2515
- if (settings.retryMaxAttempts > 0) {
2516
- caps.retry = { maxAttempts: settings.retryMaxAttempts };
2517
- }
2518
- return caps;
1974
+ function getDaemonHealth() {
1975
+ return daemonHealth;
2519
1976
  }
2520
- function resolveCompactionSummarizer(settings, providers, main) {
2521
- const raw = settings.compactionModel;
2522
- if (!raw) {
2523
- return void 0;
2524
- }
2525
- const slash = raw.indexOf("/");
2526
- if (slash <= 0 || slash === raw.length - 1) {
2527
- return void 0;
1977
+ function broadcast(signal) {
1978
+ if (signal.kind === "event" && isStreamDelta(signal.event)) {
1979
+ queueStreamDelta(signal.sessionId, signal.event.kind, signal.event.text, signal.event.turnId);
1980
+ return;
2528
1981
  }
2529
- const providerKey = raw.slice(0, slash);
2530
- const model = raw.slice(slash + 1);
2531
- if (providerKey === main.providerKey && model === main.model) {
2532
- return void 0;
1982
+ flushPendingDeltas("sessionId" in signal && typeof signal.sessionId === "string" ? signal.sessionId : void 0);
1983
+ if (signal.kind === "run:end") {
1984
+ invalidateUsageSummaryCache();
2533
1985
  }
2534
- try {
2535
- return { provider: buildProvider(providers, providerKey), model };
2536
- } catch {
2537
- return void 0;
1986
+ switch (signal.kind) {
1987
+ case "interaction:request":
1988
+ sendToAllWindows("interactions:request", {
1989
+ sessionId: signal.sessionId,
1990
+ request: signal.request,
1991
+ live: signal.live
1992
+ });
1993
+ return;
1994
+ case "interaction:resolved":
1995
+ sendToAllWindows("interactions:resolved", { sessionId: signal.sessionId, requestId: signal.requestId });
1996
+ return;
1997
+ case "approval:request":
1998
+ sendToAllWindows("safeMode:request", signal.request);
1999
+ return;
2000
+ case "approval:resolved":
2001
+ sendToAllWindows("safeMode:resolved", {
2002
+ sessionId: signal.sessionId,
2003
+ requestId: signal.requestId,
2004
+ decision: signal.decision
2005
+ });
2006
+ return;
2007
+ case "sessions:changed":
2008
+ sendToAllWindows("sessions:changed", { op: signal.op, sessionId: signal.sessionId });
2009
+ return;
2010
+ /*
2011
+ * Daemon-shared ephemeral state — forwarded ONLY in daemon mode (in-
2012
+ * process these were always dropped: the GUI renderer owns its own
2013
+ * composer/search/queue surfaces when it is the only window). In
2014
+ * daemon mode other windows edit the same session, so the renderer
2015
+ * mirrors the shared state off these channels.
2016
+ */
2017
+ case "draft:changed":
2018
+ if (daemonSignalsLive) {
2019
+ sendToAllWindows("drafts:changed", {
2020
+ sessionId: signal.sessionId,
2021
+ text: signal.text,
2022
+ shell: signal.shell === true
2023
+ });
2024
+ }
2025
+ return;
2026
+ case "draft:attachments":
2027
+ if (daemonSignalsLive) {
2028
+ sendToAllWindows("drafts:attachments", { sessionId: signal.sessionId, attachments: signal.attachments });
2029
+ }
2030
+ return;
2031
+ case "search:changed":
2032
+ if (daemonSignalsLive) {
2033
+ sendToAllWindows("search:changed", {
2034
+ sessionId: signal.sessionId,
2035
+ active: signal.active,
2036
+ query: signal.query
2037
+ });
2038
+ }
2039
+ return;
2040
+ case "suggest:changed":
2041
+ if (daemonSignalsLive) {
2042
+ sendToAllWindows("suggest:changed", {
2043
+ sessionId: signal.sessionId,
2044
+ seq: signal.seq,
2045
+ basis: signal.basis,
2046
+ caret: signal.caret,
2047
+ suggestion: signal.suggestion,
2048
+ ...signal.candidates ? { candidates: signal.candidates } : {}
2049
+ });
2050
+ }
2051
+ return;
2052
+ case "queue:changed":
2053
+ if (daemonSignalsLive) {
2054
+ sendToAllWindows("queue:changed", { sessionId: signal.sessionId, items: signal.items });
2055
+ }
2056
+ return;
2057
+ case "presence:changed":
2058
+ if (daemonSignalsLive) {
2059
+ sendToAllWindows("presence:changed", { sessions: signal.sessions });
2060
+ }
2061
+ return;
2062
+ case "skills:snapshot":
2063
+ if (daemonSignalsLive) {
2064
+ sendToAllWindows("skills:changed", { sessionId: signal.sessionId, active: signal.active });
2065
+ }
2066
+ return;
2067
+ case "settings:changed":
2068
+ if (daemonSignalsLive) {
2069
+ sendToAllWindows("settings:changed", { settings: signal.settings });
2070
+ }
2071
+ return;
2072
+ case "extension:signal":
2073
+ deliverExtensionSignal({
2074
+ extensionId: signal.extensionId,
2075
+ ...signal.sessionId !== void 0 ? { sessionId: signal.sessionId } : {},
2076
+ payload: signal.payload,
2077
+ seq: signal.seq,
2078
+ ...signal.nonce !== void 0 ? { nonce: signal.nonce } : {}
2079
+ });
2080
+ return;
2081
+ case "mcp:auth":
2082
+ case "hud:state":
2083
+ case "hud:notify":
2084
+ case "stream:retry":
2085
+ return;
2086
+ // ALLOWLIST — only signal kinds the renderer's stream reducer actually
2087
+ // consumes are forwarded. The protocol grows kinds faster than the GUI
2088
+ // adopts them; a default-forward would leak every future addition into
2089
+ // the renderer as an unknown payload (queue:changed already did).
2090
+ case "run:start":
2091
+ case "run:end":
2092
+ case "turn:end":
2093
+ case "compacting:start":
2094
+ case "compacting:end":
2095
+ case "model:fallback":
2096
+ case "work:snapshot":
2097
+ case "todos:snapshot":
2098
+ /*
2099
+ * Forwarded so the renderer HAS the data: the GUI does not render a
2100
+ * cache chip or an Instructions/SYSTEM.md surface yet, but both signals
2101
+ * are per-session facts a window is entitled to, and forwarding now
2102
+ * means the eventual surface is a renderer-only change. Unknown kinds
2103
+ * are ignored downstream.
2104
+ */
2105
+ case "cache:break":
2106
+ case "system-md":
2107
+ case "compacting:progress":
2108
+ case "stream:retry:cleared":
2109
+ case "prompt-turns":
2110
+ // GUI-local: main-side extension registry invalidation push.
2111
+ case "extensions:invalidated":
2112
+ sendChatStream(signal);
2113
+ return;
2114
+ case "event":
2115
+ sendChatStream(signal);
2116
+ return;
2117
+ default:
2118
+ if (process.env.ZIDANE_GUI_DEBUG_STREAM === "1") {
2119
+ guiLog.warn("dropping unrouted host signal", { scope: "stream", kind: signal.kind });
2120
+ }
2538
2121
  }
2539
2122
  }
2540
- function providerDescriptorFor(providers, providerKey = "anthropic") {
2541
- return providers[providerKey] ?? providers.anthropic ?? BUILTIN_PROVIDERS.anthropic;
2123
+ let host = null;
2124
+ function getChatHost() {
2125
+ if (host) {
2126
+ return host;
2127
+ }
2128
+ host = createChatHost({
2129
+ broadcast,
2130
+ store: getSessionStore(),
2131
+ readSettings,
2132
+ runtimeConfig: getRuntimeConfig,
2133
+ userDataDir,
2134
+ applyAuthEnv,
2135
+ mcpCredentialStore: getMcpCredentialStore,
2136
+ approvalsPersistence: pendingApprovalsRepo,
2137
+ debugStream: process.env.ZIDANE_GUI_DEBUG_STREAM === "1"
2138
+ });
2139
+ return host;
2542
2140
  }
2543
- function resolveModel(providers, providerKey, override) {
2544
- const descriptor = providerDescriptorFor(providers, providerKey);
2545
- const modelId = override ?? descriptor.defaultModel ?? "claude-opus-4-8";
2546
- return { providerKey, modelId };
2141
+ function resolveApproval(id, decision) {
2142
+ const daemon = getDaemonClient();
2143
+ if (daemon) {
2144
+ void daemon.request("approvals.resolve", { requestId: id, decision }).catch(() => {
2145
+ });
2146
+ return;
2147
+ }
2148
+ getChatHost().approvals.resolve(id, decision);
2547
2149
  }
2548
- function readSessionProvider(metadata, providers) {
2549
- const raw = metadata?.providerKey;
2550
- if (typeof raw === "string" && raw in providers) {
2551
- return raw;
2150
+ function denyAllPending(sessionId) {
2151
+ const daemon = getDaemonClient();
2152
+ if (daemon) {
2153
+ void daemon.request("approvals.denyAll", sessionId ? { sessionId } : {}).catch(() => {
2154
+ });
2155
+ return;
2552
2156
  }
2553
- return "anthropic";
2157
+ getChatHost().approvals.denyAll(sessionId);
2554
2158
  }
2555
- function persistedProviderMissing(metadata, providers) {
2556
- const raw = metadata?.providerKey;
2557
- return typeof raw === "string" && raw.length > 0 && !(raw in providers);
2159
+ async function listPendingApprovals() {
2160
+ const daemon = getDaemonClient();
2161
+ if (daemon) {
2162
+ return await daemon.request("approvals.listPending", {});
2163
+ }
2164
+ return getChatHost().approvals.listPending();
2558
2165
  }
2559
- function readSessionModel(metadata, providers) {
2560
- if (persistedProviderMissing(metadata, providers)) {
2561
- return void 0;
2166
+ let rehydrated = false;
2167
+ function rehydratePendingApprovals() {
2168
+ if (rehydrated || getDaemonClient()) {
2169
+ return;
2562
2170
  }
2563
- const raw = metadata?.modelId;
2564
- return typeof raw === "string" && raw.length > 0 ? raw : void 0;
2171
+ rehydrated = true;
2172
+ getChatHost().approvals.rehydrate();
2565
2173
  }
2566
- function systemFor(agentId, cwd, settings) {
2567
- const allowInteraction = settings.allowInteraction !== false;
2568
- const rules = discoverAgentsMd({
2569
- cwd,
2570
- scope: settings.userInstructionsScope,
2571
- ruler: settings.importRulerConfigs !== false
2572
- });
2573
- const userInstructions = rules.block ?? void 0;
2574
- const system = agentId === "plan" ? buildPlanSystem({ cwd, userInstructions, allowInteraction }) : buildBuildSystem({ cwd, userInstructions, allowInteraction });
2575
- return {
2576
- system,
2577
- ...rules.block ? { rulesBlock: rules.block } : {},
2578
- ...rules.files.length > 0 ? { rulesFiles: rules.files.map((f) => ({ path: f.path, source: f.source })) } : {}
2579
- };
2174
+ const RETRY_MS = 5e3;
2175
+ let client = null;
2176
+ let retryTimer = null;
2177
+ let connecting = false;
2178
+ let started = false;
2179
+ let deferredForLocalWork = false;
2180
+ function getDaemonClient() {
2181
+ return client;
2580
2182
  }
2581
- function agentIdOf(stored, agents) {
2582
- if (stored && stored in agents) {
2583
- return stored;
2183
+ function daemonEnabled() {
2184
+ if (process.env.ZIDANE_NO_DAEMON === "1") {
2185
+ return false;
2584
2186
  }
2585
- return DEFAULT_AGENT_ID;
2187
+ return readSettings().useDaemon === true;
2586
2188
  }
2587
- function dedupByName(entries) {
2588
- const seen = /* @__PURE__ */ new Set();
2589
- const out = [];
2590
- for (const entry of entries) {
2591
- if (seen.has(entry.name)) {
2592
- continue;
2593
- }
2594
- seen.add(entry.name);
2595
- out.push(entry);
2189
+ function startDaemonClient() {
2190
+ if (started) {
2191
+ return;
2596
2192
  }
2597
- return out;
2598
- }
2599
- function appendSystemFragments(system, fragments) {
2600
- if (fragments.length === 0) {
2601
- return system;
2193
+ started = true;
2194
+ onExtensionBusEmit((envelope) => {
2195
+ client?.notify("extension.emit", envelope);
2196
+ });
2197
+ console.log(`[daemon] client ready — socket=${defaultSocketPath()} build=${IPC_BUILD_ID}`);
2198
+ refreshDaemonClient();
2199
+ }
2200
+ function refreshDaemonClient() {
2201
+ if (!daemonEnabled()) {
2202
+ if (client) {
2203
+ const current = client;
2204
+ client = null;
2205
+ setDaemonSignalsLive(false);
2206
+ current.close();
2207
+ console.log("[daemon] disabled — chat host back to in-process");
2208
+ }
2209
+ rehydratePendingApprovals();
2210
+ scheduleRetry();
2211
+ return;
2602
2212
  }
2603
- const suffix = fragments.join("\n\n");
2604
- return system ? `${system}
2605
-
2606
- ${suffix}` : suffix;
2607
- }
2608
- async function ensureAgent(sessionId, settings) {
2609
- const existing = active.get(sessionId);
2610
- if (existing) {
2611
- existing.lastUsedAt = Date.now();
2612
- return existing;
2213
+ if (client || connecting) {
2214
+ return;
2613
2215
  }
2614
- const inFlight = pendingBuilds.get(sessionId);
2615
- if (inFlight) {
2616
- return inFlight;
2216
+ void tryConnect();
2217
+ }
2218
+ function scheduleRetry() {
2219
+ if (retryTimer) {
2220
+ return;
2617
2221
  }
2618
- const generation = teardownGeneration;
2619
- const build = buildActiveRun(sessionId, settings).then((run) => {
2620
- if (generation !== teardownGeneration || pendingBuilds.get(sessionId) !== build) {
2621
- discardRun(run);
2622
- throw new Error(`Session "${sessionId}" was reset while its agent was starting. Retry the action.`);
2623
- }
2624
- active.set(sessionId, run);
2625
- pruneIdleAgents();
2626
- return run;
2627
- });
2628
- pendingBuilds.set(sessionId, build);
2629
- build.catch(() => void 0).finally(() => {
2630
- if (pendingBuilds.get(sessionId) === build) {
2631
- pendingBuilds.delete(sessionId);
2632
- }
2633
- });
2634
- return build;
2635
- }
2636
- async function buildActiveRun(sessionId, settings) {
2637
- const store2 = getSessionStore();
2638
- const data = await store2.load(sessionId);
2639
- if (!data) {
2640
- throw new Error(`Session "${sessionId}" not found. Create the session before sending a prompt.`);
2641
- }
2642
- const cwd = resolveSessionCwd(data);
2643
- const extensionEditMarker = data.metadata?.[EXTENSION_EDIT_METADATA_KEY];
2644
- const isExtensionEdit = typeof extensionEditMarker === "object" && extensionEditMarker !== null;
2645
- const skillEditMarker = readSkillEditMarker(data.metadata?.[SKILL_EDIT_METADATA_KEY]);
2646
- const runtimeConfig = await getRuntimeConfig(cwd);
2647
- const agents = runtimeConfig.agents;
2648
- const providers = runtimeConfig.providers;
2649
- const agentId = agentIdOf(data.agentId, agents);
2650
- const profile = agents[agentId] ?? agents[DEFAULT_AGENT_ID] ?? Object.values(agents)[0];
2651
- if (!profile) {
2652
- throw new Error("No agent profiles are registered.");
2653
- }
2654
- const composedPreset = composeExtensionPreset(runtimeConfig.extensions, profile.preset);
2655
- const session = await loadSession(store2, sessionId) ?? await createSession({
2656
- id: sessionId,
2657
- agentId: profile.id,
2658
- projectRoot: data.projectRoot ?? cwd,
2659
- store: store2
2660
- });
2661
- const extensionSkillNames = runtimeConfig.extensions.skills.map((skill) => skill.name);
2662
- const mergedEnabledSkills = settings.enabledSkills === void 0 ? void 0 : Array.from(/* @__PURE__ */ new Set([...settings.enabledSkills, ...extensionSkillNames]));
2663
- const skillsConfig = buildSkillsConfig({
2664
- scan: defaultSkillScanPaths({
2665
- cwd,
2666
- prefix: "claude",
2667
- // Same foreign/ruler gates as MCP discovery — skill dirs other agents
2668
- // maintain are opt-in, ruler skill dirs default ON (mirrors the TUI).
2669
- foreignAgents: settings.importForeignConfigs === true,
2670
- ruler: settings.importRulerConfigs !== false
2671
- }),
2672
- enabled: mergedEnabledSkills
2673
- });
2674
- const mergedSkills = { ...skillsConfig, ...composedPreset.skills ?? {} };
2675
- const injectExtensionSkill = isExtensionEdit || extensionDirForCwd(cwd) !== null;
2676
- const withExtensionSkill = injectExtensionSkill ? withZidaneExtensionSkill(mergedSkills, { cwd }) : mergedSkills;
2677
- const finalSkills = skillEditMarker ? withZidaneSkillEditSkill(withExtensionSkill, skillEditMarker, { cwd }) : withExtensionSkill;
2678
- const { servers: discoveredMcps } = discoverProjectMcps({
2679
- cwd,
2680
- // Foreign-agent configs (Claude Code / Codex / Pi) are opt-in — their
2681
- // stdio servers execute commands from files zidane doesn't own. Ruler
2682
- // configs default ON (committed project intent); both mirror the TUI.
2683
- foreignAgents: settings.importForeignConfigs === true,
2684
- ruler: settings.importRulerConfigs !== false
2685
- });
2686
- const mcpServers = buildMcpServers({
2687
- discovered: discoveredMcps,
2688
- enabled: settings.enabledMcps,
2689
- ...settings.disabledMcpTools ? { disabledTools: settings.disabledMcpTools } : {}
2690
- });
2691
- const persistDir = resolvePersistDir({ userDir: userDataDir(), sessionId });
2692
- const tasksDir = resolveTasksDir({ userDir: userDataDir(), sessionId });
2693
- const persistBehavior = settings.persistToolResults ? { persistDir } : { persistThreshold: 0, persistDir };
2694
- const providerKey = readSessionProvider(data.metadata, providers);
2695
- const providerDescriptor = providerDescriptorFor(providers, providerKey);
2696
- const modelOverride = readSessionModel(data.metadata, providers);
2697
- const { modelId: model } = resolveModel(providers, providerKey, modelOverride);
2698
- const modelFallbacks = restoreChainFallbacks(
2699
- data.metadata?.modelChain,
2700
- { provider: providerKey, model },
2701
- (k) => providers[k] !== void 0
2702
- );
2703
- const requestInteraction = makeRequestInteractionForSession(sessionId);
2704
- const interactionTools = createInteractionTools({
2705
- requestInteraction: (request) => {
2706
- if (readSettings().allowInteraction === false) {
2707
- return Promise.reject(new Error("Interaction tools are disabled in Settings."));
2708
- }
2709
- return requestInteraction(request);
2710
- }
2711
- });
2712
- const chatReferenceTokens = { current: [] };
2713
- const chatTurnsReadTool = createChatTurnsReadTool({
2714
- store: store2,
2715
- getAllowedTokens: () => chatReferenceTokens.current
2716
- });
2717
- const ledger = new EditOutcomeLedger();
2718
- const builtInSystem = agentId === "build" || agentId === "plan" ? systemFor(agentId, cwd, settings) : null;
2719
- const system = appendSystemFragments(
2720
- builtInSystem?.system ?? composedPreset.system,
2721
- runtimeConfig.extensionSystemFragments
2722
- );
2723
- const work = /* @__PURE__ */ new Map();
2724
- const sessionSafelist = /* @__PURE__ */ new Set();
2725
- const provider = buildProvider(providers, providerKey);
2726
- const providerNameByKey = /* @__PURE__ */ new Map([[providerKey, provider.name]]);
2727
- const extraProviders = [];
2728
- const seenProviderNames = /* @__PURE__ */ new Set([provider.name]);
2729
- for (const entry of modelFallbacks) {
2730
- if (providerNameByKey.has(entry.provider)) {
2731
- continue;
2732
- }
2733
- const descriptor = providers[entry.provider];
2734
- if (!descriptor) {
2735
- continue;
2736
- }
2737
- let instance;
2738
- try {
2739
- instance = descriptor.factory();
2740
- } catch {
2741
- continue;
2742
- }
2743
- if (seenProviderNames.has(instance.name)) {
2744
- continue;
2745
- }
2746
- seenProviderNames.add(instance.name);
2747
- providerNameByKey.set(entry.provider, instance.name);
2748
- extraProviders.push(instance);
2222
+ retryTimer = setTimeout(() => {
2223
+ retryTimer = null;
2224
+ refreshDaemonClient();
2225
+ }, RETRY_MS);
2226
+ retryTimer.unref?.();
2227
+ }
2228
+ function stopRetry() {
2229
+ if (retryTimer) {
2230
+ clearTimeout(retryTimer);
2231
+ retryTimer = null;
2749
2232
  }
2750
- const agentTools = {
2751
- ...interactionTools,
2752
- chatTurnsRead: chatTurnsReadTool,
2753
- ...composedPreset.tools ?? {}
2754
- };
2755
- const agentBehavior = {
2756
- ...composedPreset.behavior,
2757
- ...persistBehavior,
2758
- tasksDir
2759
- };
2760
- const agent = createAgent({
2761
- ...composedPreset,
2762
- // Chain fallbacks need their provider instances owned by the agent —
2763
- // the loop resolves pinned `{ provider, model }` targets by instance
2764
- // name. Single-model sessions keep the bare provider (unchanged path).
2765
- provider: extraProviders.length > 0 ? [provider, ...extraProviders] : provider,
2766
- name: profile.label,
2767
- ...system ? { system } : {},
2768
- session,
2769
- execution: createProcessContext({ cwd }),
2770
- skills: finalSkills,
2771
- mcpServers: dedupByName([...mcpServers, ...composedPreset.mcpServers ?? []]),
2772
- mcpConnector: (configs) => connectMcpServers(configs, void 0, agent.hooks, {
2773
- buildAuthProvider: (config2) => new McpOAuthProvider({ name: config2.name, store: getMcpCredentialStore() })
2774
- }),
2775
- tools: agentTools,
2776
- contextBreakdownSections: [
2777
- ...runtimeConfig.extensions.contextBreakdownSections,
2778
- ...runtimeConfig.extensions.contextPanelSections
2779
- ],
2780
- behavior: agentBehavior
2781
- });
2782
- subscribeMcpToolsCache(agent.hooks, { dataDir: userDataDir() });
2783
- const spawnCandidate = (composedPreset.tools ?? {}).spawn;
2784
- const commandSeam = isSpawnTool(spawnCandidate) ? {
2785
- spawnTool: spawnCandidate,
2786
- provider,
2787
- providers: [provider, ...extraProviders],
2788
- ...system ? { system } : {},
2789
- tools: agentTools,
2790
- skills: finalSkills,
2791
- behavior: agentBehavior,
2792
- name: profile.label
2793
- } : void 0;
2794
- agent.hooks.hook("stream:text", (ctx) => {
2795
- queueStreamDelta(sessionId, "markdown", ctx.delta, ctx.turnId);
2796
- });
2797
- agent.hooks.hook("stream:thinking", (ctx) => {
2798
- queueStreamDelta(sessionId, "thinking", ctx.delta, ctx.turnId);
2799
- });
2800
- const manuallyEmittedGateBlocks = /* @__PURE__ */ new Set();
2801
- const emitToolEvent = (callId, name, liveInput, priorContent, turnId, ownership) => {
2802
- const stashed = ledger.peek(callId);
2803
- let inputForEvent;
2804
- let edit;
2805
- if (stashed) {
2806
- inputForEvent = stashed.originalInput;
2807
- edit = { ...stashed.originalPayload, outcomes: stashed.outcomes.slice() };
2808
- } else {
2809
- inputForEvent = liveInput;
2810
- if (name === "write_file") {
2811
- edit = extractEditPayload(name, liveInput, priorContent ?? "");
2812
- } else if (name === "edit" || name === "multi_edit") {
2813
- edit = extractEditPayload(name, liveInput);
2814
- }
2815
- }
2816
- const event = {
2817
- kind: "tool",
2818
- text: toolCallPreview(name, inputForEvent),
2819
- tool: name,
2820
- callId,
2821
- input: inputForEvent,
2822
- ...turnId ? { turnId } : {},
2823
- ...ownership ? { childId: ownership.childId, depth: ownership.depth } : {},
2824
- ...edit ? { edit } : {}
2825
- };
2826
- broadcast({ kind: "event", sessionId, event });
2827
- };
2828
- const registerWork = (item) => {
2829
- work.set(item.id, item);
2830
- broadcast({ kind: "work:snapshot", sessionId, items: visibleWorkItems({ work }) });
2831
- };
2832
- const dropWork = (id) => {
2833
- if (!work.delete(id)) {
2834
- return;
2835
- }
2836
- broadcast({ kind: "work:snapshot", sessionId, items: visibleWorkItems({ work }) });
2837
- };
2838
- const emitGateBlockedResult = (callId, name, reason, turnId, ownership) => {
2839
- const event = {
2840
- kind: "tool-result",
2841
- text: `Blocked: ${reason}`,
2842
- tool: name,
2843
- callId,
2844
- ...turnId ? { turnId } : {},
2845
- ...ownership ? { childId: ownership.childId, depth: ownership.depth } : {}
2846
- };
2847
- broadcast({ kind: "event", sessionId, event });
2848
- };
2849
- agent.hooks.hook("tool:before", (ctx) => {
2850
- registerWork({ kind: "tool", id: ctx.callId, label: ctx.name, startedAt: Date.now() });
2851
- emitToolEvent(ctx.callId, ctx.name, ctx.input, ctx.priorContent, ctx.turnId);
2852
- });
2853
- agent.hooks.hook("child:tool:before", (ctx) => {
2854
- registerWork({
2855
- kind: "tool",
2856
- id: ctx.callId,
2857
- label: ctx.name,
2858
- startedAt: Date.now(),
2859
- childId: ctx.childId
2860
- });
2861
- emitToolEvent(ctx.callId, ctx.name, ctx.input, ctx.priorContent, ctx.turnId, {
2862
- childId: ctx.childId,
2863
- depth: ctx.depth
2864
- });
2865
- });
2866
- agent.hooks.hook("tool:dispatched", (ctx) => {
2867
- if (ctx.outcome === "execute" || ctx.outcome === "unknown") {
2868
- return;
2869
- }
2870
- if (ctx.outcome === "gate-block" && manuallyEmittedGateBlocks.delete(ctx.callId)) {
2871
- return;
2872
- }
2873
- emitToolEvent(ctx.callId, ctx.name, ctx.input, void 0, ctx.turnId);
2874
- if (ctx.outcome === "gate-block" && ctx.reason) {
2875
- emitGateBlockedResult(ctx.callId, ctx.name, ctx.reason, ctx.turnId);
2876
- }
2877
- });
2878
- agent.hooks.hook("child:tool:dispatched", (ctx) => {
2879
- if (ctx.outcome === "execute" || ctx.outcome === "unknown") {
2880
- return;
2881
- }
2882
- if (ctx.outcome === "gate-block" && manuallyEmittedGateBlocks.delete(ctx.callId)) {
2233
+ }
2234
+ async function tryConnect() {
2235
+ connecting = true;
2236
+ setDaemonHealth("connecting");
2237
+ try {
2238
+ const socketPath = defaultSocketPath();
2239
+ if (!await probeSocket(socketPath)) {
2240
+ setDaemonHealth("disconnected");
2241
+ rehydratePendingApprovals();
2242
+ scheduleRetry();
2883
2243
  return;
2884
2244
  }
2885
- const ownership = { childId: ctx.childId, depth: ctx.depth };
2886
- emitToolEvent(ctx.callId, ctx.name, ctx.input, void 0, ctx.turnId, ownership);
2887
- if (ctx.outcome === "gate-block" && ctx.reason) {
2888
- emitGateBlockedResult(ctx.callId, ctx.name, ctx.reason, ctx.turnId, ownership);
2889
- }
2890
- });
2891
- const annotateEditResult = (callId, toolName, result) => {
2892
- const stashed = ledger.drain(callId);
2893
- if (!stashed) {
2894
- return void 0;
2895
- }
2896
- const bodyOutcomes = parseEditOutcomesFromResult(result);
2897
- const merged = mergeApprovalAndBodyOutcomes(stashed.outcomes, bodyOutcomes);
2898
- const annotation = buildEditOutcomesAnnotation(merged);
2899
- if (typeof result === "string") {
2900
- let body = stripEditOutcomesAnnotation(result);
2901
- if (toolName === "multi_edit") {
2902
- const path = stashed.originalInput.file_path ?? "";
2903
- body = rewriteMultiEditHeader(body, merged, path);
2904
- }
2905
- return body.length === 0 ? annotation : `${body}
2906
-
2907
- ${annotation}`;
2908
- }
2909
- const peeled = result.map(
2910
- (block) => block.type === "text" && typeof block.text === "string" ? { ...block, text: stripEditOutcomesAnnotation(block.text) } : block
2911
- );
2912
- return [...peeled, { type: "text", text: `
2913
- ${annotation}` }];
2914
- };
2915
- agent.hooks.hook("tool:transform", (ctx) => {
2916
- const next = annotateEditResult(ctx.callId, ctx.name, ctx.result);
2917
- if (next !== void 0) {
2918
- ctx.result = next;
2919
- }
2920
- });
2921
- agent.hooks.hook("child:tool:transform", (ctx) => {
2922
- const next = annotateEditResult(ctx.callId, ctx.name, ctx.result);
2923
- if (next !== void 0) {
2924
- ctx.result = next;
2925
- }
2926
- });
2927
- agent.hooks.hook("tool:after", (ctx) => {
2928
- dropWork(ctx.callId);
2929
- const event = {
2930
- kind: "tool-result",
2931
- text: resultToText(ctx.result),
2932
- tool: ctx.name,
2933
- callId: ctx.callId,
2934
- turnId: ctx.turnId
2935
- };
2936
- broadcast({ kind: "event", sessionId, event });
2937
- if (isTodoTool(ctx.name)) {
2938
- broadcastTodosSnapshot({ sessionId, agent });
2939
- }
2940
- });
2941
- agent.hooks.hook("child:tool:after", (ctx) => {
2942
- dropWork(ctx.callId);
2943
- const event = {
2944
- kind: "tool-result",
2945
- text: resultToText(ctx.result),
2946
- tool: ctx.name,
2947
- callId: ctx.callId,
2948
- turnId: ctx.turnId,
2949
- childId: ctx.childId,
2950
- depth: ctx.depth
2951
- };
2952
- broadcast({ kind: "event", sessionId, event });
2953
- if (isTodoTool(ctx.name)) {
2954
- broadcastTodosSnapshot({ sessionId, agent });
2955
- }
2956
- });
2957
- agent.hooks.hook("tool:error", (ctx) => {
2958
- dropWork(ctx.callId);
2959
- ledger.discard(ctx.callId);
2960
- const event = {
2961
- kind: "error",
2962
- text: ctx.error.message,
2963
- tool: ctx.name,
2964
- callId: ctx.callId,
2965
- turnId: ctx.turnId
2966
- };
2967
- broadcast({ kind: "event", sessionId, event });
2968
- });
2969
- agent.hooks.hook("child:tool:error", (ctx) => {
2970
- dropWork(ctx.callId);
2971
- ledger.discard(ctx.callId);
2972
- const event = {
2973
- kind: "error",
2974
- text: ctx.error.message,
2975
- tool: ctx.name,
2976
- callId: ctx.callId,
2977
- turnId: ctx.turnId,
2978
- childId: ctx.childId,
2979
- depth: ctx.depth
2980
- };
2981
- broadcast({ kind: "event", sessionId, event });
2982
- });
2983
- agent.hooks.hook("tool:cancelled", (ctx) => {
2984
- dropWork(ctx.callId);
2985
- });
2986
- agent.hooks.hook("child:tool:cancelled", (ctx) => {
2987
- dropWork(ctx.callId);
2988
- });
2989
- const spawnStartedAt = /* @__PURE__ */ new Map();
2990
- agent.hooks.hook("spawn:before", (ctx) => {
2991
- const record = {
2992
- startedAt: Date.now(),
2993
- task: previewLine(ctx.task, 80),
2994
- ...ctx.model ? { model: ctx.model } : {}
2995
- };
2996
- spawnStartedAt.set(ctx.id, record);
2997
- broadcast({ kind: "event", sessionId, event: buildSpawnStartEvent(ctx, record.startedAt) });
2998
- });
2999
- agent.hooks.hook("spawn:complete", (ctx) => {
3000
- const started = spawnStartedAt.get(ctx.id);
3001
- spawnStartedAt.delete(ctx.id);
3002
- broadcast({ kind: "event", sessionId, event: buildSpawnEndEvent(ctx, started) });
3003
- });
3004
- agent.hooks.hook("spawn:error", ({ id, depth, error }) => {
3005
- spawnStartedAt.delete(id);
3006
- broadcast({
3007
- kind: "event",
3008
- sessionId,
3009
- event: { kind: "error", text: `[${id}] ${error.message}`, childId: id, depth: depth ?? 1 }
3010
- });
3011
- });
3012
- const registerBackgroundTask = (ctx) => {
3013
- registerWork({
3014
- kind: "task",
3015
- id: ctx.taskId,
3016
- label: `shell (background): ${previewLine(ctx.command, 60)}`,
3017
- startedAt: ctx.startedAt,
3018
- ...ctx.childId ? { childId: ctx.childId } : {}
3019
- });
3020
- };
3021
- const dropBackgroundTaskAndEmitBanner = (ctx) => {
3022
- dropWork(ctx.taskId);
3023
- broadcast({
3024
- kind: "event",
3025
- sessionId,
3026
- event: {
3027
- kind: "task-notification",
3028
- text: formatTaskSummary(ctx),
3029
- task: {
3030
- taskId: ctx.taskId,
3031
- status: ctx.status,
3032
- exitCode: ctx.exitCode,
3033
- outputPath: ctx.outputPath,
3034
- command: ctx.command,
3035
- durationMs: ctx.durationMs
3036
- },
3037
- ...ctx.childId ? { childId: ctx.childId } : {},
3038
- ...typeof ctx.depth === "number" ? { depth: ctx.depth } : {}
2245
+ if (getChatHost().hasActiveWork()) {
2246
+ if (!deferredForLocalWork) {
2247
+ deferredForLocalWork = true;
2248
+ console.log("[daemon] local run in flight — deferring daemon attach until it drains");
3039
2249
  }
3040
- });
3041
- };
3042
- agent.hooks.hook("background:start", (ctx) => registerBackgroundTask(ctx));
3043
- agent.hooks.hook("background:exit", (ctx) => dropBackgroundTaskAndEmitBanner(ctx));
3044
- agent.hooks.hook("background:reassign", (ctx) => {
3045
- const existing = work.get(ctx.taskId);
3046
- if (!existing) {
3047
- return;
3048
- }
3049
- work.set(ctx.taskId, { kind: "task", id: existing.id, label: existing.label, startedAt: existing.startedAt });
3050
- broadcast({ kind: "work:snapshot", sessionId, items: visibleWorkItems({ work }) });
3051
- });
3052
- agent.hooks.hook("child:background:start", (ctx) => registerBackgroundTask(ctx));
3053
- agent.hooks.hook("child:background:exit", (ctx) => dropBackgroundTaskAndEmitBanner(ctx));
3054
- agent.hooks.hook("agent:done", () => {
3055
- ledger.clear();
3056
- manuallyEmittedGateBlocks.clear();
3057
- });
3058
- const applyGate = async (ctx, originator) => {
3059
- if (ctx.block) {
3060
- return;
3061
- }
3062
- const input = ctx.input;
3063
- if (readSettings().safeMode === false || isOnSafelist([...sessionSafelist], ctx.name, input)) {
2250
+ scheduleRetry();
3064
2251
  return;
3065
2252
  }
3066
- const payload = extractEditPayloadForGate(ctx.name, input);
3067
- let priorContent = null;
3068
- let preview;
3069
- if (payload) {
3070
- const path = typeof input.path === "string" ? input.path : void 0;
3071
- priorContent = path ? await readFileSafe(resolveCwdPath(cwd, path)) : "";
3072
- try {
3073
- const result = previewEditPayload(payload, priorContent, 3);
3074
- preview = serializePreview(result);
3075
- } catch {
3076
- }
3077
- }
3078
- const decision = await requestApproval({
3079
- sessionId,
3080
- cwd,
3081
- tool: ctx.name,
3082
- input,
3083
- ...payload ? { edit: payload, priorContent } : {},
3084
- ...preview ? { preview } : {},
3085
- ...originator.kind === "child" ? { originator } : {}
2253
+ deferredForLocalWork = false;
2254
+ const next = await connectIpcClient({
2255
+ socketPath,
2256
+ appVersion: `zidane-gui/${app.getVersion()}`,
2257
+ drainOnMismatch: false,
2258
+ onClose: handleDisconnect
3086
2259
  });
3087
- if (decision === "accept-session") {
3088
- for (const entry of suggestSafelistEntries(ctx.name, input)) {
3089
- sessionSafelist.add(entry);
3090
- }
3091
- }
3092
- if (payload) {
3093
- const resolved = resolveApprovalForPayload(decision, payload);
3094
- if (resolved.shouldBlock) {
3095
- ctx.block = true;
3096
- ctx.reason = decision === "deny" ? "User denied this tool call" : "All edits denied";
3097
- const ownership = ctx.childId !== void 0 && ctx.depth !== void 0 ? { childId: ctx.childId, depth: ctx.depth } : void 0;
3098
- const syntheticEdit = resolved.syntheticEvent ?? { ...payload, outcomes: resolved.outcomes };
3099
- const toolEvent = {
3100
- kind: "tool",
3101
- text: toolCallPreview(ctx.name, input),
3102
- tool: ctx.name,
3103
- callId: ctx.callId,
3104
- input,
3105
- edit: syntheticEdit,
3106
- ...ctx.turnId ? { turnId: ctx.turnId } : {},
3107
- ...ownership ? ownership : {}
3108
- };
3109
- broadcast({ kind: "event", sessionId, event: toolEvent });
3110
- const annotation = buildEditOutcomesAnnotation(resolved.outcomes);
3111
- const resultEvent = {
3112
- kind: "tool-result",
3113
- text: `Blocked: ${ctx.reason}
3114
-
3115
- ${annotation}`,
3116
- tool: ctx.name,
3117
- callId: ctx.callId,
3118
- ...ctx.turnId ? { turnId: ctx.turnId } : {},
3119
- ...ownership ? ownership : {}
3120
- };
3121
- broadcast({ kind: "event", sessionId, event: resultEvent });
3122
- manuallyEmittedGateBlocks.add(ctx.callId);
3123
- return;
3124
- }
3125
- if (typeof decision === "object" && decision.kind === "partial" && Array.isArray(input.edits)) {
3126
- const reducedEdits = input.edits.filter((_, i) => decision.mask[i] === true);
3127
- ctx.input = { ...input, edits: reducedEdits };
3128
- ledger.stash(ctx.callId, {
3129
- outcomes: resolved.outcomes,
3130
- originalInput: input,
3131
- originalPayload: payload
3132
- });
3133
- }
2260
+ if (!daemonEnabled()) {
2261
+ next.close();
3134
2262
  return;
3135
2263
  }
3136
- if (decision === "deny" || typeof decision === "object" && decision.kind === "partial") {
3137
- ctx.block = true;
3138
- ctx.reason = "User denied this tool call";
3139
- }
3140
- };
3141
- agent.hooks.hook("tool:gate", (ctx) => applyGate(ctx, { kind: "parent" }));
3142
- agent.hooks.hook("child:tool:gate", (ctx) => applyGate(ctx, { kind: "child", label: ctx.childId }));
3143
- agent.hooks.hook("mcp:tool:gate", async (ctx) => {
3144
- const gate = {
3145
- block: ctx.block,
3146
- reason: ctx.reason,
3147
- name: ctx.displayName,
3148
- input: ctx.input,
3149
- callId: ctx.callId,
3150
- turnId: ctx.turnId
3151
- };
3152
- await applyGate(gate, { kind: "parent" });
3153
- ctx.block = gate.block;
3154
- ctx.reason = gate.reason;
3155
- ctx.input = gate.input;
3156
- });
3157
- agent.hooks.hook("child:mcp:tool:gate", async (ctx) => {
3158
- const gate = {
3159
- block: ctx.block,
3160
- reason: ctx.reason,
3161
- name: ctx.displayName,
3162
- input: ctx.input,
3163
- callId: ctx.callId,
3164
- turnId: ctx.turnId,
3165
- childId: ctx.childId,
3166
- depth: ctx.depth
3167
- };
3168
- await applyGate(gate, { kind: "child", label: ctx.childId });
3169
- ctx.block = gate.block;
3170
- ctx.reason = gate.reason;
3171
- ctx.input = gate.input;
3172
- });
3173
- agent.hooks.hook("turn:after", (ctx) => {
3174
- broadcast({ kind: "turn:end", sessionId, turnId: ctx.turnId });
3175
- });
3176
- agent.hooks.hook("compact:start", () => {
3177
- broadcast({ kind: "compacting:start", sessionId });
3178
- broadcast({
3179
- kind: "event",
3180
- sessionId,
3181
- event: { kind: "info", text: "Auto-compacting conversation…" }
3182
- });
3183
- });
3184
- agent.hooks.hook("compact:end", (ctx) => {
3185
- if (ctx.status === "success") {
3186
- const markerTurn = [...agent.session?.turns ?? []].reverse().find((t) => t.content.some((b) => b.type === "compact-summary"));
3187
- const marker = markerTurn?.content.find((b) => b.type === "compact-summary");
3188
- if (markerTurn && marker && marker.type === "compact-summary") {
3189
- broadcast({ kind: "event", sessionId, event: compactSummaryEvent(marker, markerTurn.id) });
3190
- }
3191
- } else {
3192
- const msg = ctx.error?.message ?? String(ctx.error);
3193
- if (!/abort/i.test(msg)) {
3194
- broadcast({
3195
- kind: "event",
3196
- sessionId,
3197
- event: { kind: "error", text: `Auto-compaction failed: ${msg}` }
3198
- });
3199
- }
3200
- }
3201
- broadcast({ kind: "compacting:end", sessionId, ok: ctx.status === "success" });
3202
- });
3203
- agent.hooks.hook("model:fallback", (ctx) => {
3204
- broadcast({ kind: "model:fallback", sessionId, from: ctx.from, to: ctx.to });
3205
- const reason = ctx.err?.message ?? String(ctx.err);
3206
- broadcast({
3207
- kind: "event",
3208
- sessionId,
3209
- event: {
3210
- kind: "info",
3211
- text: `⚠ model fallback: ${ctx.from.provider}/${ctx.from.model} failed (${reason}) — continuing on ${ctx.to.provider}/${ctx.to.model}`
2264
+ client = next;
2265
+ setDaemonSignalsLive(true);
2266
+ next.onSignal((signal) => {
2267
+ broadcast(signal);
2268
+ if (signal.kind === "settings:changed" && !daemonEnabled()) {
2269
+ setImmediate(() => refreshDaemonClient());
3212
2270
  }
3213
2271
  });
3214
- });
3215
- const run = {
3216
- sessionId,
3217
- cwd,
3218
- agent,
3219
- controller: new AbortController(),
3220
- providerKey,
3221
- providerDescriptor,
3222
- model,
3223
- ...modelOverride ? { modelOverride } : {},
3224
- ...modelFallbacks.length > 0 ? { modelFallbacks } : {},
3225
- providerNameByKey,
3226
- ledger,
3227
- work,
3228
- chatReferenceTokens,
3229
- lastUsedAt: Date.now(),
3230
- ...system ? { system } : {},
3231
- ...isExtensionEdit || skillEditMarker ? {
3232
- autoActivateSkills: [
3233
- ...isExtensionEdit ? [ZIDANE_EXTENSION_SKILL_NAME] : [],
3234
- ...skillEditMarker ? [ZIDANE_SKILL_EDIT_SKILL_NAME] : []
3235
- ]
3236
- } : {},
3237
- ...commandSeam ? { commandSeam } : {},
3238
- ...builtInSystem?.rulesBlock || builtInSystem?.rulesFiles ? { rules: { rulesBlock: builtInSystem.rulesBlock, rulesFiles: builtInSystem.rulesFiles } } : {}
3239
- };
3240
- return run;
3241
- }
3242
- async function sendPrompt(opts) {
3243
- const settings = readSettings();
3244
- const run = await ensureAgent(opts.sessionId, settings);
3245
- if (run.compacting) {
3246
- const compacting = run.compacting;
3247
- let barrierTimer;
3248
- const timedOut = await Promise.race([
3249
- compacting.then(
3250
- () => false,
3251
- () => false
3252
- // errors already surfaced through the stream; proceed.
3253
- ),
3254
- new Promise((resolve2) => {
3255
- barrierTimer = setTimeout(() => resolve2(true), COMPACTION_BARRIER_TIMEOUT_MS);
3256
- })
3257
- ]);
3258
- if (barrierTimer) {
3259
- clearTimeout(barrierTimer);
3260
- }
3261
- if (timedOut) {
3262
- run.compactionController?.abort();
3263
- broadcast({
3264
- kind: "event",
3265
- sessionId: opts.sessionId,
3266
- event: {
3267
- kind: "error",
3268
- text: `Compaction timed out after ${COMPACTION_BARRIER_TIMEOUT_MS}ms; continuing with your prompt.`
3269
- }
2272
+ stopRetry();
2273
+ console.log(`[daemon] connected (${socketPath}) — chat execution routes over the wire`);
2274
+ } catch (error) {
2275
+ if (error instanceof IpcVersionMismatchError) {
2276
+ guiLog.warn("version mismatch, staying in-process (will keep probing)", {
2277
+ scope: "daemon",
2278
+ error: error.message
3270
2279
  });
3271
2280
  }
2281
+ setDaemonHealth("disconnected");
2282
+ rehydratePendingApprovals();
2283
+ scheduleRetry();
2284
+ } finally {
2285
+ connecting = false;
3272
2286
  }
3273
- for (const name of run.autoActivateSkills ?? []) {
3274
- try {
3275
- await run.agent.activateSkill(name);
3276
- } catch {
3277
- }
3278
- }
3279
- const runId = randomUUID();
3280
- const requestedSkills = Array.from(/* @__PURE__ */ new Set([...opts.activatedSkills ?? [], ...run.autoActivateSkills ?? []]));
3281
- const systemNudge = requestedSkills.length > 0 ? `The user invoked the following skill(s) via the \`/<name>\` syntax: ${requestedSkills.map((n) => `\`${n}\``).join(
3282
- ", "
3283
- )}.
3284
- Call \`skills_use({ name: ... })\` for each one before responding, then follow the returned instructions strictly when composing your reply.` : void 0;
3285
- let thinking;
3286
- const modelOverride = run.modelOverride;
3287
- let modelOptions;
3288
- try {
3289
- const data = await getSessionStore().load(opts.sessionId);
3290
- const rawEffort = data?.metadata?.effort;
3291
- if (typeof rawEffort === "string" && isThinkingLevel$1(rawEffort)) {
3292
- thinking = rawEffort;
3293
- }
3294
- const descriptor = run.providerDescriptor ?? BUILTIN_PROVIDERS.anthropic;
3295
- const modelId = modelOverride ?? run.model;
3296
- const enabled = enabledModelOptions(data?.metadata?.modelOptions);
3297
- modelOptions = restoreModelOptions(descriptor, modelId, { [modelId]: enabled });
3298
- } catch {
2287
+ }
2288
+ function handleDisconnect() {
2289
+ if (!client) {
2290
+ return;
3299
2291
  }
3300
- broadcast({ kind: "run:start", sessionId: opts.sessionId, runId });
3301
- broadcastTodosSnapshot(run);
3302
- const promptValue = opts.attachments && opts.attachments.length > 0 ? [
3303
- ...opts.prompt.length > 0 ? [{ type: "text", text: opts.prompt }] : [],
3304
- ...opts.attachments.map(
3305
- (a) => (
3306
- /*
3307
- * Branch by media type — `image/*` rides the canonical
3308
- * `PromptImagePart`, everything else (PDF, plain text,
3309
- * .docx, …) rides `PromptDocumentPart`. The renderer
3310
- * passes everything as base64-encoded data URLs already
3311
- * stripped of the `data:…;base64,` prefix, so the
3312
- * document encoding is always `'base64'` here.
3313
- */
3314
- a.mediaType.startsWith("image/") ? {
3315
- type: "image",
3316
- mediaType: a.mediaType,
3317
- data: a.data,
3318
- ...a.name ? { name: a.name } : {}
3319
- } : {
3320
- type: "document",
3321
- mediaType: a.mediaType,
3322
- data: a.data,
3323
- encoding: "base64",
3324
- ...a.name ? { name: a.name } : {}
3325
- }
3326
- )
3327
- )
3328
- ] : opts.prompt;
3329
- const autoCompactDescriptor = BUILTIN_PROVIDERS[run.providerKey] ?? BUILTIN_PROVIDERS.anthropic;
3330
- const runtimeProviders = (await getRuntimeConfig(run.cwd)).providers;
3331
- const summarizer = resolveCompactionSummarizer(settings, runtimeProviders, {
3332
- providerKey: run.providerKey,
3333
- model: modelOverride ?? run.model
3334
- });
3335
- const autoCompactRun = chatAutoCompactBehavior({
3336
- enabled: settings.autoCompact,
3337
- threshold: settings.autoCompactThreshold,
3338
- rawContextWindow: getContextWindow(autoCompactDescriptor, modelOverride ?? run.model),
3339
- ...summarizer ? { summarizer } : {}
3340
- });
3341
- run.chatReferenceTokens.current = chatReferenceTokensForPrompt(opts.prompt);
3342
- run.agent.run({
3343
- prompt: promptValue,
3344
- system: systemNudge && run.system ? `${run.system}
3345
-
3346
- ${systemNudge}` : systemNudge,
3347
- signal: run.controller.signal,
3348
- behavior: { autoCompact: autoCompactRun, ...runCapsFromSettings(settings) },
3349
- // Attribute the Rules bucket only when the agent's composed system (with
3350
- // the AGENTS.md block) is actually in use — a `systemNudge` override
3351
- // replaces it, so the rules wouldn't be on the wire that run.
3352
- ...run.rules && !systemNudge ? { contextSections: run.rules } : {},
3353
- /*
3354
- * Only forward `model` when the session has an explicit override.
3355
- * Forwarding `run.model` (== the provider's default) for every
3356
- * run would shadow the agent's own per-turn model-selection
3357
- * logic — historically this is how cache-aware routing decides
3358
- * between e.g. opus-4-7 and sonnet-4-6 on a per-call basis.
3359
- *
3360
- * With a fallback chain, the override expands to pinned
3361
- * `{ provider, model }` targets via canonical `buildRunModel` —
3362
- * mirrors the TUI's `runModelFor` (`src/tui/app.tsx`), including
3363
- * per-target context windows so the loop re-bases the auto-compact
3364
- * trigger when a fallback advances. A single-entry chain collapses
3365
- * back to the bare string (byte-identical to the pre-chain path).
3366
- */
3367
- ...modelOverride ? {
3368
- model: run.modelFallbacks && run.modelFallbacks.length > 0 ? buildRunModel(
3369
- [{ provider: run.providerKey, model: modelOverride }, ...run.modelFallbacks],
3370
- (k) => run.providerNameByKey?.get(k),
3371
- (entry) => {
3372
- const d = runtimeProviders[entry.provider];
3373
- return d ? getContextWindow(d, entry.model) ?? void 0 : void 0;
3374
- }
3375
- ) : modelOverride
3376
- } : {},
3377
- ...thinking ? { thinking } : {},
3378
- ...modelOptions ? { modelOptions } : {}
3379
- }).then(() => {
3380
- broadcast({ kind: "run:end", sessionId: opts.sessionId, runId, ok: true });
3381
- broadcastTodosSnapshot(run);
3382
- }).catch((err) => {
3383
- broadcast({
3384
- kind: "run:end",
2292
+ client = null;
2293
+ setDaemonSignalsLive(false);
2294
+ guiLog.warn("connection lost — falling back to in-process chat host", { scope: "daemon" });
2295
+ rehydratePendingApprovals();
2296
+ scheduleRetry();
2297
+ }
2298
+ function sendPrompt(opts) {
2299
+ const daemon = getDaemonClient();
2300
+ if (daemon) {
2301
+ return daemon.request("chat.send", {
3385
2302
  sessionId: opts.sessionId,
3386
- runId,
3387
- ok: false,
3388
- error: err.message
2303
+ prompt: opts.prompt,
2304
+ ...opts.activatedSkills ? { activatedSkills: opts.activatedSkills } : {},
2305
+ ...opts.attachments ? { attachments: opts.attachments } : {}
3389
2306
  });
3390
- broadcastTodosSnapshot(run);
3391
- }).finally(() => {
3392
- run.chatReferenceTokens.current = [];
3393
- run.lastUsedAt = Date.now();
3394
- pruneIdleAgents();
3395
- });
3396
- return { runId };
3397
- }
3398
- function getLiveSession(sessionId) {
3399
- return active.get(sessionId)?.agent.session ?? null;
2307
+ }
2308
+ return getChatHost().sendPrompt(opts);
3400
2309
  }
3401
2310
  function interruptChat(sessionId) {
3402
- const entry = active.get(sessionId);
3403
- if (!entry) {
2311
+ const daemon = getDaemonClient();
2312
+ if (daemon) {
2313
+ void daemon.request("chat.interrupt", { sessionId }).catch(() => {
2314
+ });
3404
2315
  return;
3405
2316
  }
3406
- entry.commandAbort?.abort();
3407
- entry.controller.abort();
3408
- entry.agent.abort();
2317
+ getChatHost().interrupt(sessionId);
3409
2318
  }
3410
- function listRunningWork(sessionId) {
3411
- const entry = active.get(sessionId);
3412
- if (entry) entry.lastUsedAt = Date.now();
3413
- return entry ? visibleWorkItems(entry) : [];
2319
+ function steerSession(sessionId, message) {
2320
+ const daemon = getDaemonClient();
2321
+ if (daemon) {
2322
+ void daemon.request("chat.steer", { sessionId, message }).catch(() => {
2323
+ });
2324
+ return;
2325
+ }
2326
+ getChatHost().steer(sessionId, message);
3414
2327
  }
3415
- async function cancelRunningWork(sessionId, id, reason) {
3416
- const entry = active.get(sessionId);
3417
- if (!entry) {
3418
- return false;
2328
+ function followUpSession(sessionId, message) {
2329
+ const daemon = getDaemonClient();
2330
+ if (daemon) {
2331
+ void daemon.request("chat.followUp", { sessionId, message }).catch(() => {
2332
+ });
2333
+ return;
3419
2334
  }
3420
- entry.lastUsedAt = Date.now();
3421
- const targets = id === "all" ? visibleWorkItems(entry) : visibleWorkItems(entry).filter((item) => item.id === id);
3422
- let cancelled = false;
3423
- for (const item of targets) {
3424
- if (item.kind === "task") {
3425
- cancelled = await entry.agent.killBackgroundTask(item.id) || cancelled;
3426
- } else {
3427
- cancelled = entry.agent.cancelTool(item.id, reason ?? "user-cancelled-tool") || cancelled;
3428
- }
2335
+ getChatHost().followUp(sessionId, message);
2336
+ }
2337
+ function listRunningWork(sessionId) {
2338
+ const daemon = getDaemonClient();
2339
+ if (daemon) {
2340
+ return daemon.request("chat.listWork", { sessionId });
3429
2341
  }
3430
- return cancelled;
2342
+ return getChatHost().listRunningWork(sessionId);
3431
2343
  }
3432
- function isSessionRunning(sessionId) {
3433
- const entry = active.get(sessionId);
3434
- if (entry) entry.lastUsedAt = Date.now();
3435
- return entry?.agent.isRunning === true;
2344
+ function cancelRunningWork(sessionId, id, reason) {
2345
+ const daemon = getDaemonClient();
2346
+ if (daemon) {
2347
+ return daemon.request("chat.cancelWork", { sessionId, id, ...reason ? { reason } : {} });
2348
+ }
2349
+ return getChatHost().cancelRunningWork(sessionId, id, reason);
3436
2350
  }
3437
2351
  function getTodosSnapshot(sessionId) {
3438
- const entry = active.get(sessionId);
3439
- if (!entry) return null;
3440
- entry.lastUsedAt = Date.now();
3441
- const session = entry.agent.session;
3442
- return session ? selectActiveTodos(session) : null;
3443
- }
3444
- async function getContextBreakdown(sessionId) {
3445
- let entry = active.get(sessionId);
3446
- if (!entry) {
3447
- try {
3448
- entry = await ensureAgent(sessionId, readSettings());
3449
- } catch {
3450
- return null;
3451
- }
2352
+ const daemon = getDaemonClient();
2353
+ if (daemon) {
2354
+ return daemon.request("todos.get", { sessionId });
3452
2355
  }
3453
- entry.lastUsedAt = Date.now();
3454
- const modelId = entry.model;
3455
- const descriptor = entry.providerDescriptor ?? BUILTIN_PROVIDERS.anthropic;
3456
- const effWindow = effectiveContextWindow(getContextWindow(descriptor, modelId));
3457
- const settings = readSettings();
3458
- return entry.agent.getContextBreakdown({
3459
- model: modelId,
3460
- ...effWindow !== null ? { effectiveWindow: effWindow } : {},
3461
- autocompactBuffer: OUTPUT_RESERVE_TOKENS,
3462
- ...settings.autoCompact && settings.autoCompactThreshold ? { compactThreshold: settings.autoCompactThreshold } : {}
3463
- });
2356
+ return getChatHost().getTodosSnapshot(sessionId);
3464
2357
  }
3465
- async function compactSessionNow(sessionId) {
3466
- const entry = active.get(sessionId);
3467
- if (!entry) {
3468
- throw new Error(
3469
- `Session "${sessionId}" must be opened (send at least one prompt) before it can be compacted manually.`
3470
- );
2358
+ async function setSessionTodos(sessionId, items) {
2359
+ const daemon = getDaemonClient();
2360
+ if (daemon) {
2361
+ return daemon.request("todos.set", { sessionId, items });
3471
2362
  }
3472
- if (entry.compacting) {
3473
- await entry.compacting;
3474
- return;
2363
+ const state = await getChatHost().setTodos(sessionId, items);
2364
+ return state ? toTodosSnapshot(state) : null;
2365
+ }
2366
+ function getContextBreakdown(sessionId) {
2367
+ const daemon = getDaemonClient();
2368
+ if (daemon) {
2369
+ return daemon.request("sessions.contextBreakdown", { sessionId });
3475
2370
  }
3476
- entry.compacting = runCompaction(entry, broadcast).finally(() => {
3477
- const live = active.get(sessionId);
3478
- if (live && live.compacting === entry.compacting) {
3479
- live.compacting = void 0;
3480
- }
3481
- });
3482
- await entry.compacting;
2371
+ return getChatHost().getContextBreakdown(sessionId);
3483
2372
  }
3484
- function steerSession(sessionId, message) {
3485
- const entry = active.get(sessionId);
3486
- if (!entry) {
3487
- return;
2373
+ function getSessionSystemMd(sessionId) {
2374
+ const daemon = getDaemonClient();
2375
+ if (daemon) {
2376
+ return daemon.request("sessions.systemMd", { sessionId });
3488
2377
  }
3489
- entry.agent.steer(message);
2378
+ return Promise.resolve(getChatHost().sessionSystemMd(sessionId));
3490
2379
  }
3491
- function followUpSession(sessionId, message) {
3492
- const entry = active.get(sessionId);
3493
- if (!entry) {
3494
- return;
2380
+ function getSessionContextSegments(sessionId) {
2381
+ const daemon = getDaemonClient();
2382
+ if (daemon) {
2383
+ return daemon.request("sessions.contextSegments", { sessionId });
2384
+ }
2385
+ return getChatHost().getContextSegments(sessionId);
2386
+ }
2387
+ function ensureMainSession() {
2388
+ const daemon = getDaemonClient();
2389
+ if (daemon) {
2390
+ return daemon.request("orchestration.main", {});
2391
+ }
2392
+ return getChatHost().orchestration.ensureMain();
2393
+ }
2394
+ function createSessionSystemOverride(sessionId) {
2395
+ const daemon = getDaemonClient();
2396
+ if (daemon) {
2397
+ return daemon.request("sessions.createSystemOverride", { sessionId });
3495
2398
  }
3496
- entry.agent.followUp(message);
2399
+ return getChatHost().createSystemOverride(sessionId);
3497
2400
  }
3498
- function dropPendingDeltas(sessionId) {
3499
- for (let i = pendingDeltas.length - 1; i >= 0; i--) {
3500
- if (pendingDeltas[i].sessionId === sessionId) {
3501
- pendingDeltas.splice(i, 1);
3502
- }
2401
+ function compactSessionNow(sessionId) {
2402
+ const daemon = getDaemonClient();
2403
+ if (daemon) {
2404
+ return daemon.request("sessions.compact", { sessionId });
3503
2405
  }
2406
+ return getChatHost().compactSessionNow(sessionId);
3504
2407
  }
3505
- function disposeSession(sessionId) {
3506
- const entry = active.get(sessionId);
3507
- dropPendingDeltas(sessionId);
3508
- clearPendingInteractions(sessionId);
3509
- denyAllPending(sessionId);
3510
- pendingBuilds.delete(sessionId);
3511
- if (!entry) {
3512
- return;
2408
+ function getLiveSession(sessionId) {
2409
+ if (getDaemonClient()) {
2410
+ return null;
3513
2411
  }
3514
- entry.compactionController?.abort();
3515
- entry.controller.abort();
3516
- entry.ledger.clear();
3517
- entry.work.clear();
3518
- broadcastWorkSnapshot(entry);
3519
- entry.agent.destroy().catch(() => void 0);
3520
- active.delete(sessionId);
2412
+ return getChatHost().getLiveSession(sessionId);
3521
2413
  }
3522
2414
  function shutdownChat() {
3523
- teardownGeneration += 1;
3524
- pendingBuilds.clear();
3525
- if (deltaFlushTimer) {
3526
- clearTimeout(deltaFlushTimer);
3527
- deltaFlushTimer = null;
3528
- }
3529
- pendingDeltas.length = 0;
3530
- denyAllPending();
3531
- for (const [sessionId, entry] of active) {
3532
- entry.compactionController?.abort();
3533
- entry.controller.abort();
3534
- entry.ledger.clear();
3535
- entry.work.clear();
3536
- broadcastWorkSnapshot(entry);
3537
- entry.agent.destroy().catch(() => void 0);
3538
- clearPendingInteractions(sessionId);
3539
- }
3540
- active.clear();
2415
+ resetDeltaCoalescer();
2416
+ return getChatHost().shutdown();
3541
2417
  }
3542
2418
  function attachAttachmentsToUserPrompts(events, turns) {
3543
2419
  const perUserTurn = [];
@@ -3712,438 +2588,6 @@ function tokenizeQuery(query) {
3712
2588
  }
3713
2589
  return tokens;
3714
2590
  }
3715
- function errorMessage(err) {
3716
- return err instanceof Error ? err.message : String(err);
3717
- }
3718
- async function listCommands(cwd) {
3719
- try {
3720
- const runtimeConfig = await getRuntimeConfig(cwd);
3721
- return runtimeConfig.extensions.commands.map((command) => ({
3722
- name: command.name,
3723
- description: command.description,
3724
- ...command.aliases && command.aliases.length > 0 ? { aliases: [...command.aliases] } : {},
3725
- ...command.group ? { group: command.group } : {},
3726
- ...command.completeArgs ? { hasArgCompletion: true } : {}
3727
- }));
3728
- } catch {
3729
- return [];
3730
- }
3731
- }
3732
- async function completeCommandArgs(cwd, name, argsPrefix) {
3733
- try {
3734
- const runtimeConfig = await getRuntimeConfig(cwd);
3735
- const command = runtimeConfig.extensions.commands.find(
3736
- (c) => c.name === name || (c.aliases?.includes(name) ?? false)
3737
- );
3738
- if (!command?.completeArgs) {
3739
- return [];
3740
- }
3741
- const suggestions = await command.completeArgs(argsPrefix) ?? [];
3742
- return suggestions.map((s) => ({
3743
- value: s.value,
3744
- ...s.label ? { label: s.label } : {},
3745
- ...s.description ? { description: s.description } : {}
3746
- }));
3747
- } catch {
3748
- return [];
3749
- }
3750
- }
3751
- async function resolveRunSettings(run) {
3752
- let thinking;
3753
- let modelOptions;
3754
- try {
3755
- const data = await getSessionStore().load(run.sessionId);
3756
- const rawEffort = data?.metadata?.effort;
3757
- if (typeof rawEffort === "string" && isThinkingLevel$1(rawEffort)) {
3758
- thinking = rawEffort;
3759
- }
3760
- const descriptor2 = run.providerDescriptor ?? BUILTIN_PROVIDERS.anthropic;
3761
- const modelId = run.modelOverride ?? run.model;
3762
- const enabled = enabledModelOptions(data?.metadata?.modelOptions);
3763
- modelOptions = restoreModelOptions(descriptor2, modelId, { [modelId]: enabled });
3764
- } catch {
3765
- }
3766
- const settings = readSettings();
3767
- const descriptor = BUILTIN_PROVIDERS[run.providerKey] ?? BUILTIN_PROVIDERS.anthropic;
3768
- const autoCompact = chatAutoCompactBehavior({
3769
- enabled: settings.autoCompact,
3770
- threshold: settings.autoCompactThreshold,
3771
- rawContextWindow: getContextWindow(descriptor, run.modelOverride ?? run.model)
3772
- });
3773
- return {
3774
- ...thinking ? { thinking } : {},
3775
- ...modelOptions ? { modelOptions } : {},
3776
- autoCompact,
3777
- caps: runCapsFromSettings(settings)
3778
- };
3779
- }
3780
- async function runSlashCommand(opts) {
3781
- const prompt = opts.prompt.trim();
3782
- if (!prompt.startsWith("/")) {
3783
- return { ran: false };
3784
- }
3785
- const run = await ensureAgent(opts.sessionId, readSettings());
3786
- const runtimeConfig = await getRuntimeConfig(run.cwd);
3787
- const commands = runtimeConfig.extensions.commands;
3788
- const invocation = parseCommandInvocation(prompt, commands);
3789
- if (!invocation) {
3790
- return { ran: false };
3791
- }
3792
- const command = commands.find((c) => c.name === invocation.name);
3793
- if (!command) {
3794
- return { ran: false };
3795
- }
3796
- if (run.agent.isRunning) {
3797
- throw new Error(`/${invocation.name}: a run is already in progress — wait for it to finish.`);
3798
- }
3799
- const session = run.agent.session;
3800
- if (!session) {
3801
- throw new Error(`/${invocation.name}: session is not available`);
3802
- }
3803
- const sessionId = opts.sessionId;
3804
- const controller = new AbortController();
3805
- run.commandAbort = controller;
3806
- const requestInteraction = makeRequestInteractionForSession(sessionId);
3807
- const requestCommandInteraction = (request) => {
3808
- if (controller.signal.aborted) {
3809
- return Promise.reject(new Error("command aborted"));
3810
- }
3811
- const promise = requestInteraction(request);
3812
- const onAbort = () => {
3813
- cancelInteraction(request.id, "command aborted");
3814
- };
3815
- controller.signal.addEventListener("abort", onAbort, { once: true });
3816
- return promise.finally(() => controller.signal.removeEventListener("abort", onAbort));
3817
- };
3818
- const emitEvent = (event) => {
3819
- broadcast({ kind: "event", sessionId, event });
3820
- };
3821
- let pending2 = [];
3822
- let pendingTurnId = null;
3823
- let separateNextEmit = false;
3824
- const flushCommandTurn = async () => {
3825
- if (pending2.length === 0) {
3826
- return;
3827
- }
3828
- const content = commandBlocksToContent(pending2);
3829
- const turnId = pendingTurnId ?? randomUUID();
3830
- pending2 = [];
3831
- pendingTurnId = null;
3832
- await session.appendTurns([{ id: turnId, role: "command", createdAt: Date.now(), content }]).catch(() => void 0);
3833
- };
3834
- const emitBlock = (block) => {
3835
- if (separateNextEmit) {
3836
- emitEvent({ kind: "separator", text: "" });
3837
- separateNextEmit = false;
3838
- }
3839
- pendingTurnId ??= randomUUID();
3840
- pending2.push(block);
3841
- emitEvent({ ...commandBlockToEvent(block), turnId: pendingTurnId });
3842
- };
3843
- const ctx = {
3844
- args: invocation.args,
3845
- argv: invocation.argv,
3846
- ...invocation.invokedAs ? { invokedAs: invocation.invokedAs } : {},
3847
- ...opts.attachments && opts.attachments.length > 0 ? {
3848
- attachments: opts.attachments.map((a) => ({
3849
- name: a.name ?? "attachment",
3850
- mediaType: a.mediaType,
3851
- data: a.data
3852
- }))
3853
- } : {},
3854
- data: {},
3855
- emit: emitBlock,
3856
- runAgent: async (agentPrompt, agentOpts) => {
3857
- if (controller.signal.aborted) {
3858
- throw new Error("runAgent: command aborted");
3859
- }
3860
- await flushCommandTurn();
3861
- for (const name of run.autoActivateSkills ?? []) {
3862
- try {
3863
- await run.agent.activateSkill(name);
3864
- } catch {
3865
- }
3866
- }
3867
- emitEvent({ kind: "separator", text: "" });
3868
- emitEvent({ kind: "user-prompt", text: agentOpts?.display ?? agentPrompt });
3869
- if (agentOpts?.display) {
3870
- emitEvent({ kind: "command-detail", label: "prompt", text: agentPrompt });
3871
- }
3872
- const before = session.turns.length;
3873
- const beforeRuns = session.runs.length;
3874
- const { thinking, modelOptions, autoCompact, caps } = await resolveRunSettings(run);
3875
- const runId = randomUUID();
3876
- broadcast({ kind: "run:start", sessionId, runId });
3877
- try {
3878
- await run.agent.run({
3879
- prompt: agentPrompt,
3880
- signal: controller.signal,
3881
- behavior: { autoCompact, ...caps },
3882
- ...run.modelOverride ? { model: run.modelOverride } : {},
3883
- ...thinking ? { thinking } : {},
3884
- ...modelOptions ? { modelOptions } : {}
3885
- });
3886
- broadcast({ kind: "run:end", sessionId, runId, ok: true });
3887
- } catch (err) {
3888
- broadcast({ kind: "run:end", sessionId, runId, ok: false, error: errorMessage(err) });
3889
- throw err;
3890
- }
3891
- await session.save().catch(() => void 0);
3892
- for (const sessionRun of session.runs.slice(beforeRuns)) {
3893
- if (sessionRun.parentRunId) {
3894
- continue;
3895
- }
3896
- sessionRun.origin = { kind: "command", ...agentOpts?.display ? { display: agentOpts.display } : {} };
3897
- await session.updateRun(sessionRun).catch(() => void 0);
3898
- }
3899
- separateNextEmit = true;
3900
- const text = session.turns.slice(before).filter((t) => t.role === "assistant").flatMap((t) => t.content.flatMap((b) => b.type === "text" ? [b.text] : [])).join("\n");
3901
- return { text };
3902
- },
3903
- // Single implementation behind the overloaded contract (zod-inferred
3904
- // vs. explicit-generic) — the cast is the standard TS pattern for
3905
- // implementing an overload set with one function.
3906
- generateData: (async (dataOpts) => {
3907
- if (controller.signal.aborted) {
3908
- throw new Error("generateData: command aborted");
3909
- }
3910
- const provider = buildProvider(runtimeConfig.providers, run.providerKey);
3911
- return generateStructuredData({
3912
- provider,
3913
- model: dataOpts.model ?? run.modelOverride ?? run.model,
3914
- prompt: dataOpts.prompt,
3915
- schema: dataOpts.schema,
3916
- ...dataOpts.system ? { system: dataOpts.system } : {},
3917
- ...dataOpts.includeConversation ? { turns: session.turns } : {},
3918
- signal: controller.signal
3919
- });
3920
- }),
3921
- logger: createLogger({ emit() {
3922
- } }, { command: invocation.name }),
3923
- signal: controller.signal,
3924
- cwd: run.cwd,
3925
- // Read-only live view — getters, so turns/runs appended mid-workflow
3926
- // are visible on re-read. Projection only: no mutators cross into
3927
- // extension code.
3928
- session: {
3929
- get id() {
3930
- return session.id;
3931
- },
3932
- get turns() {
3933
- return session.turns;
3934
- },
3935
- get runs() {
3936
- return session.runs;
3937
- },
3938
- get metadata() {
3939
- return session.metadata;
3940
- }
3941
- },
3942
- interaction: {
3943
- confirm: async (confirmPrompt, confirmOpts) => {
3944
- const response = await requestCommandInteraction({
3945
- id: `command_${randomUUID()}`,
3946
- kind: "question",
3947
- tool: ASK_USER_TOOL,
3948
- createdAt: Date.now(),
3949
- payload: {
3950
- ...confirmOpts?.intro ? { intro: confirmOpts.intro } : {},
3951
- questions: [
3952
- {
3953
- id: "confirm",
3954
- type: "confirm",
3955
- prompt: confirmPrompt,
3956
- ...confirmOpts?.affirmLabel ? { affirmLabel: confirmOpts.affirmLabel } : {},
3957
- ...confirmOpts?.denyLabel ? { denyLabel: confirmOpts.denyLabel } : {}
3958
- }
3959
- ]
3960
- }
3961
- });
3962
- if (response.kind !== "question") {
3963
- throw new Error("confirm: unexpected interaction response kind");
3964
- }
3965
- return response.answers.confirm === true;
3966
- },
3967
- askUser: async (form) => {
3968
- const response = await requestCommandInteraction({
3969
- id: `command_${randomUUID()}`,
3970
- kind: "question",
3971
- tool: ASK_USER_TOOL,
3972
- createdAt: Date.now(),
3973
- payload: form
3974
- });
3975
- if (response.kind !== "question") {
3976
- throw new Error("askUser: unexpected interaction response kind");
3977
- }
3978
- return response.answers;
3979
- },
3980
- presentPlan: async (plan) => {
3981
- const response = await requestCommandInteraction({
3982
- id: `command_${randomUUID()}`,
3983
- kind: "plan",
3984
- tool: PRESENT_PLAN_TOOL,
3985
- createdAt: Date.now(),
3986
- payload: plan
3987
- });
3988
- if (response.kind !== "plan") {
3989
- throw new Error("presentPlan: unexpected interaction response kind");
3990
- }
3991
- return response;
3992
- }
3993
- },
3994
- // Isolated child agents — the spawn tool driven host-side via the
3995
- // build-time seam (`run.commandSeam`), so command children get the
3996
- // exact model routing, persistence, and concurrency accounting of
3997
- // model-initiated spawns.
3998
- spawnAgents: async (tasks, spawnOpts) => {
3999
- const seam = run.commandSeam;
4000
- const agent = run.agent;
4001
- if (!seam || !isSpawnTool(seam.spawnTool)) {
4002
- throw new Error("spawnAgents: no spawn tool available for this agent");
4003
- }
4004
- if (controller.signal.aborted) {
4005
- throw new Error("spawnAgents: command aborted");
4006
- }
4007
- if (tasks.length === 0) {
4008
- return [];
4009
- }
4010
- await flushCommandTurn();
4011
- const handle = await agent.ensureExecution();
4012
- let onAbort;
4013
- try {
4014
- await Promise.race([
4015
- agent.warmup(),
4016
- new Promise((resolveAbort) => {
4017
- if (controller.signal.aborted) {
4018
- resolveAbort();
4019
- return;
4020
- }
4021
- onAbort = () => resolveAbort();
4022
- controller.signal.addEventListener("abort", onAbort, { once: true });
4023
- })
4024
- ]);
4025
- } catch {
4026
- } finally {
4027
- if (onAbort) {
4028
- controller.signal.removeEventListener("abort", onAbort);
4029
- }
4030
- }
4031
- if (controller.signal.aborted) {
4032
- throw new Error("spawnAgents: command aborted");
4033
- }
4034
- const parentMcp = agent.mcpConnection;
4035
- const results = tasks.map((task, i) => ({
4036
- label: task.label ?? `task-${i + 1}`,
4037
- ...task.model !== void 0 ? { model: task.model } : {},
4038
- status: "aborted",
4039
- text: "",
4040
- message: "spawnAgents: batch aborted before this task ran"
4041
- }));
4042
- let cursor = 0;
4043
- const worker = async () => {
4044
- while (cursor < tasks.length && !controller.signal.aborted) {
4045
- const index = cursor++;
4046
- const spawnTask = tasks[index];
4047
- try {
4048
- const outcome = await seam.spawnTool.runTask(
4049
- {
4050
- task: spawnTask.prompt,
4051
- ...spawnTask.system !== void 0 ? { system: spawnTask.system } : {},
4052
- ...spawnTask.model !== void 0 ? { model: spawnTask.model } : {}
4053
- },
4054
- {
4055
- provider: seam.provider,
4056
- providers: seam.providers,
4057
- ...seam.name !== void 0 ? { name: seam.name } : {},
4058
- model: run.modelOverride ?? run.model,
4059
- signal: controller.signal,
4060
- execution: agent.execution,
4061
- handle,
4062
- hooks: agent.hooks,
4063
- ...seam.system !== void 0 ? { system: seam.system } : {},
4064
- tools: seam.tools,
4065
- mcpServers: [...agent.mcpServers],
4066
- ...parentMcp ? { mcpConnection: nonOwningMcpView(parentMcp) } : {},
4067
- skills: seam.skills,
4068
- behavior: seam.behavior,
4069
- turnId: `command_${invocation.name}`,
4070
- callId: `command_spawn_${randomUUID()}`,
4071
- session
4072
- }
4073
- );
4074
- results[index] = {
4075
- label: spawnTask.label ?? outcome.id ?? `task-${index + 1}`,
4076
- ...spawnTask.model !== void 0 ? { model: spawnTask.model } : {},
4077
- status: outcome.status,
4078
- text: outcome.text,
4079
- message: outcome.message
4080
- };
4081
- } catch (err) {
4082
- results[index] = {
4083
- label: spawnTask.label ?? `task-${index + 1}`,
4084
- ...spawnTask.model !== void 0 ? { model: spawnTask.model } : {},
4085
- status: "error",
4086
- text: "",
4087
- message: `spawnAgents: ${errorMessage(err)}`
4088
- };
4089
- }
4090
- }
4091
- };
4092
- const cap = seam.spawnTool.maxConcurrent;
4093
- const width = Math.max(1, Math.min(spawnOpts?.maxConcurrent ?? cap, cap, tasks.length));
4094
- await Promise.all(Array.from({ length: width }, () => worker()));
4095
- await session.save().catch(() => void 0);
4096
- separateNextEmit = true;
4097
- return results;
4098
- },
4099
- // Model-visible context note — a plain user turn appended straight to
4100
- // the session (no run). The next `agent.run` rebuilds conversation
4101
- // from `session.turns`, so the note reaches the wire on the next
4102
- // prompt; `synthetic` keeps the live echo out of prompt history.
4103
- appendContext: async (text, noteOpts) => {
4104
- if (controller.signal.aborted) {
4105
- throw new Error("appendContext: command aborted");
4106
- }
4107
- const trimmed = text.trim();
4108
- if (!trimmed) {
4109
- return;
4110
- }
4111
- await flushCommandTurn();
4112
- emitEvent({ kind: "separator", text: "" });
4113
- emitEvent({ kind: "user-prompt", text: noteOpts?.display ?? trimmed, synthetic: true });
4114
- await session.appendTurns([
4115
- {
4116
- id: await session.generateTurnId(),
4117
- role: "user",
4118
- content: [{ type: "text", text: trimmed }],
4119
- createdAt: Date.now(),
4120
- ...noteOpts?.display ? { display: noteOpts.display } : {}
4121
- }
4122
- ]);
4123
- separateNextEmit = true;
4124
- }
4125
- };
4126
- try {
4127
- if (session.turns.length > 0) {
4128
- emitEvent({ kind: "separator", text: "" });
4129
- }
4130
- emitBlock({ text: `\`❯ /${invocation.name}${invocation.args ? ` ${invocation.args}` : ""}\`` });
4131
- const result = await executeCommand(command, ctx);
4132
- if (result.error) {
4133
- emitEvent({ kind: "error", text: `/${invocation.name}: ${errorMessage(result.error)}` });
4134
- }
4135
- } catch (err) {
4136
- emitEvent({ kind: "error", text: `/${invocation.name}: ${errorMessage(err)}` });
4137
- } finally {
4138
- if (run.commandAbort === controller) {
4139
- delete run.commandAbort;
4140
- }
4141
- await flushCommandTurn();
4142
- await session.save().catch(() => void 0);
4143
- run.lastUsedAt = Date.now();
4144
- }
4145
- return { ran: true, runId: randomUUID() };
4146
- }
4147
2591
  const EXTENSION_NAME_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
4148
2592
  function validateExtensionName(name) {
4149
2593
  const trimmed = name.trim();
@@ -4187,6 +2631,35 @@ async function resolveInlineAutocomplete(registry, ctx) {
4187
2631
  const result = await resolveInlineSuggestion(providers, ctx);
4188
2632
  return result ? [...result.suffixes] : null;
4189
2633
  }
2634
+ async function resolveInteraction(requestId, response) {
2635
+ const daemon = getDaemonClient();
2636
+ if (daemon) {
2637
+ return daemon.request("interactions.respond", { requestId, response });
2638
+ }
2639
+ return getChatHost().interactions.respond(requestId, response);
2640
+ }
2641
+ async function cancelInteraction(requestId, reason) {
2642
+ const daemon = getDaemonClient();
2643
+ if (daemon) {
2644
+ return daemon.request("interactions.cancel", { requestId, ...reason ? { reason } : {} });
2645
+ }
2646
+ return getChatHost().interactions.cancel(requestId, reason);
2647
+ }
2648
+ async function listPendingInteractions(sessionId) {
2649
+ const daemon = getDaemonClient();
2650
+ if (daemon) {
2651
+ return daemon.request("interactions.list", sessionId ? { sessionId } : {});
2652
+ }
2653
+ return getChatHost().interactions.list(sessionId);
2654
+ }
2655
+ async function rehydratePendingInteractions(sessionId) {
2656
+ const daemon = getDaemonClient();
2657
+ if (daemon) {
2658
+ await daemon.request("interactions.rehydrate", { sessionId });
2659
+ return;
2660
+ }
2661
+ await getChatHost().interactions.rehydrate(sessionId);
2662
+ }
4190
2663
  const BASH_OUTPUT_CEILING_BYTES = 1024 * 1024;
4191
2664
  const BASH_KILL_GRACE_MS = 5e3;
4192
2665
  const BASH_RESULT_MAX_BYTES = 32 * 1024;
@@ -4402,24 +2875,6 @@ function killAllShellRuns() {
4402
2875
  run.controller.abort();
4403
2876
  }
4404
2877
  }
4405
- function modelChainMetadata(providerKey, modelId, fallbacks) {
4406
- const primary = { provider: providerKey, model: modelId };
4407
- const tail = filterChainFallbacks(
4408
- (fallbacks ?? []).map((f) => ({ provider: f.providerKey, model: f.modelId })),
4409
- primary,
4410
- // Availability is enforced at consumption time (`sessionModelFallbacks`
4411
- // checks the live provider registry); the write side only normalizes.
4412
- () => true
4413
- );
4414
- return tail.length > 0 ? [primary, ...tail] : void 0;
4415
- }
4416
- function sessionModelFallbacks(metadata, primary, isRegistered) {
4417
- return restoreChainFallbacks(
4418
- metadata?.modelChain,
4419
- { provider: primary.providerKey, model: primary.modelId },
4420
- isRegistered
4421
- );
4422
- }
4423
2878
  function loadHostState() {
4424
2879
  return getResolvedConfig().stateStore.load();
4425
2880
  }
@@ -4434,10 +2889,55 @@ function invalidateExtensionsAndNotify() {
4434
2889
  broadcast({ kind: "extensions:invalidated" });
4435
2890
  }
4436
2891
  const LAST_FOLDER_KEY = "last_folder";
2892
+ function announceSessionsTouch(sessionId) {
2893
+ getDaemonClient()?.notify("sessions.touch", { sessionId });
2894
+ }
2895
+ async function disposeOrRebuild(sessionId) {
2896
+ const daemon = getDaemonClient();
2897
+ if (daemon) {
2898
+ await daemon.request("chat.rebuildAgent", { sessionId });
2899
+ return;
2900
+ }
2901
+ getChatHost().disposeAgentForRebuild(sessionId);
2902
+ }
2903
+ async function assertDaemonNotRunning(sessionId, what) {
2904
+ const daemon = getDaemonClient();
2905
+ if (!daemon) {
2906
+ return;
2907
+ }
2908
+ let running = false;
2909
+ try {
2910
+ running = await daemon.request("chat.isRunning", { sessionId });
2911
+ } catch (err) {
2912
+ guiLog.warn("chat.isRunning probe failed; treating session as idle", {
2913
+ scope: "daemon",
2914
+ error: err?.message ?? String(err)
2915
+ });
2916
+ }
2917
+ if (running) {
2918
+ throw new Error(`Cannot ${what}: the session has a run in flight on the daemon — interrupt it first.`);
2919
+ }
2920
+ }
4437
2921
  const suggestControllers = /* @__PURE__ */ new Map();
4438
2922
  const SUGGEST_TIMEOUT_MS = 5e3;
4439
2923
  const inlineAutocompleteControllers = /* @__PURE__ */ new Map();
2924
+ const inlineSuggestSeqs = /* @__PURE__ */ new Map();
4440
2925
  const runningActions = /* @__PURE__ */ new Set();
2926
+ function toAuthStatus(r, providers) {
2927
+ const desc = descriptorFor(r.key, providers);
2928
+ const customFields = customFieldsForDescriptor(desc);
2929
+ const configuredFields = configuredFieldsForDescriptor(desc);
2930
+ return {
2931
+ key: r.key,
2932
+ label: r.label,
2933
+ available: r.available,
2934
+ hasApiKey: r.methods.some((m) => m.source === "apikey"),
2935
+ hasOAuth: r.methods.some((m) => m.source === "oauth"),
2936
+ methods: r.methods,
2937
+ ...customFields ? { customFields } : {},
2938
+ ...configuredFields ? { configuredFields } : {}
2939
+ };
2940
+ }
4441
2941
  async function providersFor(cwd) {
4442
2942
  if (!cwd) {
4443
2943
  return BUILTIN_PROVIDERS;
@@ -4511,10 +3011,9 @@ async function sidebarRowFromMeta(meta) {
4511
3011
  const explicitProvider = typeof meta.metadata.providerKey === "string" ? providerKey : void 0;
4512
3012
  const modelId = readSessionModelId(meta.metadata, providers);
4513
3013
  const modelOptions = modelOptionsForSession(meta.metadata);
4514
- const modelFallbacks = modelId ? sessionModelFallbacks(meta.metadata, { providerKey, modelId }, (k) => k in providers).map((e) => ({
4515
- providerKey: e.provider,
4516
- modelId: e.model
4517
- })) : [];
3014
+ const modelFallbacks = modelId ? (sessionModelFallbacks({ modelChain: meta.metadata.modelChain, providerKey, modelId }) ?? []).filter(
3015
+ (e) => e.providerKey in providers
3016
+ ) : [];
4518
3017
  return {
4519
3018
  id: meta.id,
4520
3019
  title: deriveSessionTitle(meta.firstUserTurn ? [meta.firstUserTurn] : [], meta.metadata),
@@ -4539,7 +3038,8 @@ async function sidebarRowFromMeta(meta) {
4539
3038
  ...explicitProvider ? { providerKey: explicitProvider } : {},
4540
3039
  ...modelId ? { modelId } : {},
4541
3040
  ...modelFallbacks.length > 0 ? { modelFallbacks } : {},
4542
- archived: meta.metadata.archived === true
3041
+ archived: meta.metadata.archived === true,
3042
+ ...isMainSession(meta.metadata) ? { isMain: true } : {}
4543
3043
  };
4544
3044
  }
4545
3045
  async function buildSidebarRow(id) {
@@ -4633,6 +3133,7 @@ function modelOptionsForSession(metadata) {
4633
3133
  }
4634
3134
  function registerChatIpc() {
4635
3135
  initSettings();
3136
+ startDaemonClient();
4636
3137
  ipcMain.handle("sessions:list", async (_e, filter) => {
4637
3138
  const metas = listSidebarMeta(filter);
4638
3139
  const present = await Promise.all(metas.map((m) => sidebarRowFromMeta(m)));
@@ -4655,16 +3156,47 @@ function registerChatIpc() {
4655
3156
  }
4656
3157
  );
4657
3158
  ipcMain.handle("sessions:create", async (_e, input) => {
3159
+ const daemon = getDaemonClient();
3160
+ if (daemon) {
3161
+ const seededFallbacks = input.providerKey && input.modelId ? sessionModelFallbacks({
3162
+ modelChain: loadHostState().lastModelChain,
3163
+ providerKey: input.providerKey,
3164
+ modelId: input.modelId
3165
+ }) : void 0;
3166
+ const row2 = await daemon.request("sessions.create", {
3167
+ // '' = directory-less "pure chat" session — same sentinel the
3168
+ // local path and the read sides already coerce to "unset".
3169
+ cwd: input.cwd ?? "",
3170
+ agentId: input.agentId ?? "build",
3171
+ ...input.title ? { title: input.title } : {},
3172
+ ...input.providerKey && input.modelId ? { providerKey: input.providerKey, modelId: input.modelId } : {},
3173
+ ...seededFallbacks && seededFallbacks.length > 0 ? { fallbacks: [...seededFallbacks] } : {},
3174
+ ...input.cwd && input.extensionEdit ? { extensionEdit: true } : {}
3175
+ });
3176
+ if (input.cwd && input.skillEdit) {
3177
+ patchSessionMetadata(
3178
+ row2.id,
3179
+ editSessionMetadata({ kind: "skill", name: input.skillEdit.name, dir: input.cwd }),
3180
+ { bumpUpdatedAt: false }
3181
+ );
3182
+ announceSessionsTouch(row2.id);
3183
+ }
3184
+ const sidebar = await buildSidebarRow(row2.id);
3185
+ if (!sidebar) {
3186
+ throw new Error(`Failed to create session "${row2.id}".`);
3187
+ }
3188
+ return sidebar;
3189
+ }
4658
3190
  const id = randomUUID();
4659
3191
  const agentId = input.agentId ?? "build";
4660
3192
  const seededChain = input.providerKey && input.modelId ? modelChainMetadata(
4661
3193
  input.providerKey,
4662
3194
  input.modelId,
4663
- sessionModelFallbacks(
4664
- { modelChain: loadHostState().lastModelChain },
4665
- { providerKey: input.providerKey, modelId: input.modelId },
4666
- () => true
4667
- ).map((e) => ({ providerKey: e.provider, modelId: e.model }))
3195
+ sessionModelFallbacks({
3196
+ modelChain: loadHostState().lastModelChain,
3197
+ providerKey: input.providerKey,
3198
+ modelId: input.modelId
3199
+ })
4668
3200
  ) : void 0;
4669
3201
  const extraMetadata = {
4670
3202
  ...seededChain ? { modelChain: seededChain } : {},
@@ -4691,44 +3223,67 @@ function registerChatIpc() {
4691
3223
  }
4692
3224
  return row;
4693
3225
  });
3226
+ const assertNotMain = (id, what) => {
3227
+ const meta = getSidebarMeta(id);
3228
+ if (meta && isMainSession(meta.metadata)) {
3229
+ throw new Error(`The Main session cannot ${what}.`);
3230
+ }
3231
+ };
4694
3232
  ipcMain.handle("sessions:setTitle", (_e, id, title) => {
3233
+ assertNotMain(id, "be renamed");
4695
3234
  patchSessionMetadata(id, { title }, { bumpUpdatedAt: false });
3235
+ announceSessionsTouch(id);
4696
3236
  });
4697
3237
  ipcMain.handle("sessions:setArchived", (_e, id, archived) => {
4698
3238
  patchSessionMetadata(id, { archived });
3239
+ announceSessionsTouch(id);
4699
3240
  });
4700
- ipcMain.handle("sessions:setAgentId", (_e, id, agentId) => {
3241
+ ipcMain.handle("sessions:setAgentId", async (_e, id, agentId) => {
3242
+ const daemon = getDaemonClient();
3243
+ if (daemon) {
3244
+ try {
3245
+ await daemon.request("sessions.setAgentId", { sessionId: id, agentId });
3246
+ return;
3247
+ } catch {
3248
+ }
3249
+ }
4701
3250
  patchSessionScope(id, { agentId });
4702
- disposeSession(id);
3251
+ await disposeOrRebuild(id);
3252
+ announceSessionsTouch(id);
4703
3253
  });
4704
- ipcMain.handle("sessions:attachFolder", (_e, id, cwd) => {
3254
+ ipcMain.handle("sessions:attachFolder", async (_e, id, cwd) => {
4705
3255
  if (typeof cwd !== "string" || cwd.length === 0) {
4706
3256
  throw new Error("attachFolder requires a folder path.");
4707
3257
  }
3258
+ assertNotMain(id, "be bound to a folder");
4708
3259
  patchSessionMetadata(id, { cwd });
4709
3260
  patchSessionScope(id, { projectRoot: resolveProjectRoot(cwd) });
4710
- disposeSession(id);
3261
+ await disposeOrRebuild(id);
3262
+ announceSessionsTouch(id);
4711
3263
  invalidateGitRepoCache();
4712
3264
  });
4713
- ipcMain.handle("sessions:detachFolder", (_e, id) => {
3265
+ ipcMain.handle("sessions:detachFolder", async (_e, id) => {
4714
3266
  patchSessionMetadata(id, { cwd: "" });
4715
3267
  patchSessionScope(id, { projectRoot: "" });
4716
- disposeSession(id);
3268
+ await disposeOrRebuild(id);
3269
+ announceSessionsTouch(id);
4717
3270
  invalidateGitRepoCache();
4718
3271
  });
4719
3272
  ipcMain.handle("sessions:setEffort", (_e, id, effort) => {
4720
3273
  patchSessionMetadata(id, { effort });
3274
+ announceSessionsTouch(id);
4721
3275
  });
4722
3276
  ipcMain.handle(
4723
3277
  "sessions:setModel",
4724
- (_e, id, providerKey, modelId, fallbacks) => {
3278
+ async (_e, id, providerKey, modelId, fallbacks) => {
4725
3279
  patchSessionMetadata(id, {
4726
3280
  providerKey,
4727
3281
  modelId,
4728
3282
  modelOptions: {},
4729
3283
  modelChain: modelChainMetadata(providerKey, modelId, fallbacks)
4730
3284
  });
4731
- disposeSession(id);
3285
+ await disposeOrRebuild(id);
3286
+ announceSessionsTouch(id);
4732
3287
  }
4733
3288
  );
4734
3289
  ipcMain.handle("sessions:setModelOptions", async (_e, id, options) => {
@@ -4739,6 +3294,7 @@ function registerChatIpc() {
4739
3294
  modelOptions: enabledModelOptions(options)
4740
3295
  })
4741
3296
  });
3297
+ announceSessionsTouch(id);
4742
3298
  });
4743
3299
  ipcMain.handle("sessions:listModels", async (_e, cwd) => {
4744
3300
  applyAuthEnv();
@@ -4804,6 +3360,7 @@ function registerChatIpc() {
4804
3360
  if (Object.keys(inheritedMetadata).length > 0) {
4805
3361
  patchSessionMetadata(newId, inheritedMetadata);
4806
3362
  }
3363
+ announceSessionsTouch(newId);
4807
3364
  return newId;
4808
3365
  }
4809
3366
  );
@@ -4816,6 +3373,7 @@ function registerChatIpc() {
4816
3373
  return data.turns.find((t) => t.id === turnId) ?? null;
4817
3374
  });
4818
3375
  ipcMain.handle("sessions:deleteTurn", async (_e, id, turnId) => {
3376
+ await assertDaemonNotRunning(id, "delete the turn");
4819
3377
  const store2 = getSessionStore();
4820
3378
  const data = await store2.load(id);
4821
3379
  if (!data) {
@@ -4826,9 +3384,11 @@ function registerChatIpc() {
4826
3384
  throw new Error(`Turn "${turnId}" not found in session "${id}".`);
4827
3385
  }
4828
3386
  replaceTurns(id, next);
4829
- disposeSession(id);
3387
+ await disposeOrRebuild(id);
3388
+ announceSessionsTouch(id);
4830
3389
  });
4831
3390
  ipcMain.handle("sessions:editTurnText", async (_e, id, turnId, text) => {
3391
+ await assertDaemonNotRunning(id, "edit the turn");
4832
3392
  const store2 = getSessionStore();
4833
3393
  const data = await store2.load(id);
4834
3394
  if (!data) {
@@ -4839,14 +3399,17 @@ function registerChatIpc() {
4839
3399
  throw new Error(`Turn "${turnId}" has no editable text blocks.`);
4840
3400
  }
4841
3401
  replaceTurns(id, next);
4842
- disposeSession(id);
3402
+ await disposeOrRebuild(id);
3403
+ announceSessionsTouch(id);
4843
3404
  });
4844
3405
  ipcMain.handle("sessions:delete", async (_e, id) => {
4845
- disposeSession(id);
3406
+ await disposeOrRebuild(id);
4846
3407
  const store2 = getSessionStore();
4847
3408
  await store2.delete(id);
3409
+ announceSessionsTouch(id);
4848
3410
  });
4849
3411
  ipcMain.handle("sessions:generateTitle", async (_e, id) => {
3412
+ assertNotMain(id, "be renamed");
4850
3413
  const store2 = getSessionStore();
4851
3414
  const data = await store2.load(id);
4852
3415
  if (!data) {
@@ -4857,6 +3420,7 @@ function registerChatIpc() {
4857
3420
  const model = descriptor.defaultModel ?? "claude-opus-4-8";
4858
3421
  const title = await generateSessionTitle({ provider, model, turns: data.turns });
4859
3422
  patchSessionMetadata(id, { title });
3423
+ announceSessionsTouch(id);
4860
3424
  return title;
4861
3425
  });
4862
3426
  ipcMain.handle("sessions:compact", async (_e, id) => {
@@ -4968,6 +3532,22 @@ function registerChatIpc() {
4968
3532
  };
4969
3533
  });
4970
3534
  ipcMain.handle("sessions:contextBreakdown", (_e, id) => getContextBreakdown(id));
3535
+ ipcMain.handle("sessions:systemMd", (_e, id) => getSessionSystemMd(id));
3536
+ ipcMain.handle("daemon:health", () => getDaemonHealth());
3537
+ ipcMain.handle("sessions:contextSegments", (_e, id) => getSessionContextSegments(id));
3538
+ ipcMain.handle("instructions:createSystemOverride", async (_e, sessionId) => {
3539
+ const result = await createSessionSystemOverride(sessionId);
3540
+ await openFileInEditor(result.path);
3541
+ return result;
3542
+ });
3543
+ ipcMain.handle("instructions:openInEditor", async (_e, sessionId, path) => {
3544
+ const report = await getSessionContextSegments(sessionId);
3545
+ const allowed = new Set((report?.segments ?? []).flatMap((seg) => seg.path ? [seg.path] : []));
3546
+ if (!allowed.has(path)) {
3547
+ throw new Error("Not an instruction file for this session");
3548
+ }
3549
+ await openFileInEditor(path);
3550
+ });
4971
3551
  ipcMain.handle("interactions:list", (_e, sessionId) => listPendingInteractions(sessionId));
4972
3552
  ipcMain.handle(
4973
3553
  "interactions:respond",
@@ -4980,11 +3560,7 @@ function registerChatIpc() {
4980
3560
  ipcMain.handle("interactions:rehydrate", async (_e, sessionId) => {
4981
3561
  await rehydratePendingInteractions(sessionId);
4982
3562
  });
4983
- ipcMain.handle("chat:send", async (_e, opts) => {
4984
- const commandResult = await runSlashCommand(opts);
4985
- if (commandResult.ran) {
4986
- return { runId: commandResult.runId ?? randomUUID() };
4987
- }
3563
+ ipcMain.handle("chat:send", (_e, opts) => {
4988
3564
  return sendPrompt(opts);
4989
3565
  });
4990
3566
  ipcMain.handle("chat:interrupt", (_e, sessionId) => interruptChat(sessionId));
@@ -4994,6 +3570,7 @@ function registerChatIpc() {
4994
3570
  if (!data) {
4995
3571
  throw new Error(`Unknown session "${sessionId}".`);
4996
3572
  }
3573
+ await assertDaemonNotRunning(sessionId, "run the shell command");
4997
3574
  const cwd = resolveSessionCwd(data);
4998
3575
  const { runId } = startShellRun({
4999
3576
  sessionId,
@@ -5007,7 +3584,7 @@ function registerChatIpc() {
5007
3584
  * compaction's `replaceTurns` rewrite the turns table from that
5008
3585
  * snapshot, so a raw store append it never saw would be
5009
3586
  * silently erased by the next full save. Resolved per append,
5010
- * not per run \u2014 an agent can materialize while the shell
3587
+ * not per run — an agent can materialize while the shell
5011
3588
  * command is still streaming.
5012
3589
  */
5013
3590
  appendTurns: async (turns) => {
@@ -5017,6 +3594,16 @@ function registerChatIpc() {
5017
3594
  return;
5018
3595
  }
5019
3596
  await store2.appendTurns(sessionId, turns);
3597
+ const daemon = getDaemonClient();
3598
+ if (daemon) {
3599
+ announceSessionsTouch(sessionId);
3600
+ await daemon.request("chat.rebuildAgent", { sessionId }).catch((err) => {
3601
+ guiLog.warn("chat.rebuildAgent after `!` append failed", {
3602
+ scope: "daemon",
3603
+ error: err?.message ?? String(err)
3604
+ });
3605
+ });
3606
+ }
5020
3607
  }
5021
3608
  }
5022
3609
  });
@@ -5045,8 +3632,8 @@ function registerChatIpc() {
5045
3632
  const valid = ["all", "30d", "7d"];
5046
3633
  return getUsageSummary(valid.includes(range) ? range : "all");
5047
3634
  });
5048
- ipcMain.handle("todos:get", (_e, sessionId) => {
5049
- const state = getTodosSnapshot(sessionId);
3635
+ ipcMain.handle("todos:get", async (_e, sessionId) => {
3636
+ const state = await getTodosSnapshot(sessionId);
5050
3637
  if (!state) {
5051
3638
  return null;
5052
3639
  }
@@ -5058,23 +3645,130 @@ function registerChatIpc() {
5058
3645
  tally: state.tally
5059
3646
  };
5060
3647
  });
3648
+ ipcMain.handle("todos:set", async (_e, sessionId, items) => {
3649
+ const applied = await setSessionTodos(sessionId, items);
3650
+ if (applied) {
3651
+ return applied;
3652
+ }
3653
+ const session = await loadSession(getSessionStore(), sessionId);
3654
+ if (!session) {
3655
+ return null;
3656
+ }
3657
+ const runId = selectActiveTodos(session).runId;
3658
+ if (!runId) {
3659
+ return null;
3660
+ }
3661
+ setTodosForRun(session, runId, sanitizeTodoItems(items, DEFAULT_MAX_TODO_ITEMS), { clearArchive: true });
3662
+ await session.save();
3663
+ return toTodosSnapshot(selectActiveTodos(session));
3664
+ });
3665
+ ipcMain.handle("usage:fetchAll", async (_e, cwd, opts) => {
3666
+ return fetchAllProviderUsage(userDataDir(), await providersFor(cwd), opts ?? {});
3667
+ });
3668
+ ipcMain.handle("usage:fetch", async (_e, providerKey, cwd, opts) => {
3669
+ const descriptor = descriptorFor(providerKey, await providersFor(cwd));
3670
+ if (!descriptor) {
3671
+ return null;
3672
+ }
3673
+ return fetchProviderUsage(userDataDir(), descriptor, opts ?? {});
3674
+ });
5061
3675
  ipcMain.handle("chat:steer", (_e, sessionId, message) => steerSession(sessionId, message));
5062
3676
  ipcMain.handle("chat:followUp", (_e, sessionId, message) => followUpSession(sessionId, message));
5063
- ipcMain.handle("chat:pushQueued", async (_e, sessionId, message, activatedSkills) => {
5064
- if (isSessionRunning(sessionId)) {
5065
- steerSession(sessionId, message);
5066
- return { delivered: "steer" };
3677
+ ipcMain.handle("chat:pushQueued", (_e, sessionId, message, activatedSkills) => {
3678
+ const daemon = getDaemonClient();
3679
+ if (daemon) {
3680
+ return daemon.request("chat.pushQueued", {
3681
+ sessionId,
3682
+ message,
3683
+ ...activatedSkills ? { activatedSkills } : {}
3684
+ });
5067
3685
  }
5068
- const command = await runSlashCommand({ sessionId, prompt: message });
5069
- if (command.ran) {
5070
- return { delivered: "command" };
3686
+ return getChatHost().pushQueued(sessionId, message, activatedSkills);
3687
+ });
3688
+ ipcMain.handle("drafts:get", async (_e, sessionId) => {
3689
+ const daemon = getDaemonClient();
3690
+ if (!daemon) {
3691
+ return { text: "" };
5071
3692
  }
5072
- await sendPrompt({
5073
- sessionId,
5074
- prompt: message,
5075
- ...activatedSkills ? { activatedSkills } : {}
3693
+ try {
3694
+ return await daemon.request("drafts.get", { sessionId });
3695
+ } catch {
3696
+ return { text: "" };
3697
+ }
3698
+ });
3699
+ ipcMain.handle("drafts:set", (_e, sessionId, text, shell2) => {
3700
+ getDaemonClient()?.notify("drafts.set", { sessionId, text, ...shell2 !== void 0 ? { shell: shell2 } : {} });
3701
+ });
3702
+ ipcMain.handle("drafts:setAttachments", (_e, sessionId, attachments) => {
3703
+ getDaemonClient()?.notify("drafts.setAttachments", { sessionId, attachments });
3704
+ });
3705
+ ipcMain.handle("search:set", (_e, sessionId, active, query) => {
3706
+ getDaemonClient()?.notify("search.set", { sessionId, active, query });
3707
+ });
3708
+ ipcMain.handle("queue:list", (_e, sessionId) => {
3709
+ const daemon = getDaemonClient();
3710
+ if (daemon) {
3711
+ return daemon.request("queue.list", { sessionId });
3712
+ }
3713
+ return getChatHost().queueList(sessionId);
3714
+ });
3715
+ ipcMain.handle(
3716
+ "queue:add",
3717
+ (_e, sessionId, text, activatedSkills, attachments) => {
3718
+ const daemon = getDaemonClient();
3719
+ if (daemon) {
3720
+ return daemon.request("queue.add", {
3721
+ sessionId,
3722
+ text,
3723
+ ...activatedSkills ? { activatedSkills } : {},
3724
+ ...attachments ? { attachments } : {}
3725
+ });
3726
+ }
3727
+ return getChatHost().queueAdd(sessionId, text, activatedSkills, attachments);
3728
+ }
3729
+ );
3730
+ ipcMain.handle("queue:remove", (_e, sessionId, id) => {
3731
+ const daemon = getDaemonClient();
3732
+ if (daemon) {
3733
+ return daemon.request("queue.remove", { sessionId, id });
3734
+ }
3735
+ return getChatHost().queueRemove(sessionId, id);
3736
+ });
3737
+ ipcMain.handle("queue:pushNow", (_e, sessionId, id) => {
3738
+ const daemon = getDaemonClient();
3739
+ if (daemon) {
3740
+ return daemon.request("queue.pushNow", { sessionId, id });
3741
+ }
3742
+ return getChatHost().queuePushNow(sessionId, id);
3743
+ });
3744
+ ipcMain.handle("presence:list", async () => {
3745
+ const daemon = getDaemonClient();
3746
+ if (!daemon) {
3747
+ return [];
3748
+ }
3749
+ try {
3750
+ return await daemon.request("presence.list", {});
3751
+ } catch {
3752
+ return [];
3753
+ }
3754
+ });
3755
+ ipcMain.handle("history:searchSession", async (_e, sessionId, query, limit) => {
3756
+ const daemon = getDaemonClient();
3757
+ if (!daemon) {
3758
+ return [];
3759
+ }
3760
+ return daemon.request("history.searchSession", { sessionId, query, ...limit !== void 0 ? { limit } : {} });
3761
+ });
3762
+ ipcMain.handle("history:searchAll", async (_e, query, sessionIds, excerptLimit) => {
3763
+ const daemon = getDaemonClient();
3764
+ if (!daemon) {
3765
+ return {};
3766
+ }
3767
+ return daemon.request("history.searchAll", {
3768
+ query,
3769
+ sessionIds,
3770
+ ...excerptLimit !== void 0 ? { excerptLimit } : {}
5076
3771
  });
5077
- return { delivered: "send" };
5078
3772
  });
5079
3773
  ipcMain.handle("safeMode:resolve", (_e, id, decision) => resolveApproval(id, decision));
5080
3774
  ipcMain.handle("safeMode:denyAll", (_e, sessionId) => denyAllPending(sessionId));
@@ -5082,14 +3776,38 @@ function registerChatIpc() {
5082
3776
  ipcMain.handle("files:list", async (_e, cwd) => {
5083
3777
  return listProjectFiles({ cwd: scopeCwd(cwd) });
5084
3778
  });
5085
- ipcMain.handle("commands:list", (_e, cwd) => listCommands(scopeCwd(cwd)));
5086
- ipcMain.handle(
5087
- "commands:completeArgs",
5088
- (_e, cwd, name, argsPrefix) => completeCommandArgs(scopeCwd(cwd), name, argsPrefix)
5089
- );
3779
+ ipcMain.handle("commands:list", (_e, cwd) => {
3780
+ const daemon = getDaemonClient();
3781
+ if (daemon) {
3782
+ return daemon.request("commands.list", { cwd: scopeCwd(cwd) });
3783
+ }
3784
+ return getChatHost().listCommands(scopeCwd(cwd));
3785
+ });
3786
+ ipcMain.handle("commands:completeArgs", (_e, cwd, name, argsPrefix) => {
3787
+ const daemon = getDaemonClient();
3788
+ if (daemon) {
3789
+ return daemon.request("commands.completeArgs", { cwd: scopeCwd(cwd), name, argsPrefix });
3790
+ }
3791
+ return getChatHost().completeCommandArgs(scopeCwd(cwd), name, argsPrefix);
3792
+ });
5090
3793
  ipcMain.handle("skills:list", async (_e, cwd) => {
5091
3794
  return discoverProjectSkills({ cwd: scopeCwd(cwd), prefix: "claude", ...foreignConfigFlags() });
5092
3795
  });
3796
+ ipcMain.handle("plugins:list", async (_e, cwd) => {
3797
+ const config2 = getResolvedConfig();
3798
+ const { plugins } = await discoverProjectPlugins({ cwd: scopeCwd(cwd), prefix: config2.prefix });
3799
+ return plugins.map((entry) => ({
3800
+ name: entry.name,
3801
+ source: entry.source,
3802
+ path: entry.path,
3803
+ ok: entry.plugin.ok,
3804
+ description: entry.plugin.manifest?.description ?? null,
3805
+ version: entry.plugin.manifest?.version ?? null,
3806
+ skillCount: entry.plugin.skills.length,
3807
+ mcpCount: entry.plugin.mcpServers.length
3808
+ }));
3809
+ });
3810
+ ipcMain.handle("orchestration:main", () => ensureMainSession());
5093
3811
  ipcMain.handle("skills:install", async (e, cwd, req) => {
5094
3812
  const result = await installSkill({
5095
3813
  cwd,
@@ -5265,8 +3983,21 @@ function registerChatIpc() {
5265
3983
  );
5266
3984
  ipcMain.handle(
5267
3985
  "autocomplete:inline",
5268
- async (_e, cwd, text, cursor) => {
3986
+ async (_e, cwd, text, cursor, sessionId) => {
5269
3987
  const scoped = scopeCwd(cwd);
3988
+ const daemon = getDaemonClient();
3989
+ if (daemon && sessionId) {
3990
+ const seq = (inlineSuggestSeqs.get(sessionId) ?? 0) + 1;
3991
+ inlineSuggestSeqs.set(sessionId, seq);
3992
+ try {
3993
+ const result = await daemon.request("suggest.resolve", { sessionId, text, caret: cursor, seq });
3994
+ if (result.candidates && result.candidates.length > 0) {
3995
+ return result.candidates;
3996
+ }
3997
+ return result.suggestion !== null ? [result.suggestion] : null;
3998
+ } catch {
3999
+ }
4000
+ }
5270
4001
  const config2 = await getRuntimeConfig(cwd);
5271
4002
  inlineAutocompleteControllers.get(scoped)?.abort();
5272
4003
  const controller = new AbortController();
@@ -5306,21 +4037,7 @@ function registerChatIpc() {
5306
4037
  ipcMain.handle("auth:hasAny", () => hasAnyAuth());
5307
4038
  ipcMain.handle("auth:detect", async (_e, cwd) => {
5308
4039
  const providers = await providersFor(cwd);
5309
- const results = detectAuth(userDataDir(), providers);
5310
- return results.map((r) => {
5311
- const desc = descriptorFor(r.key, providers);
5312
- const customFields = customFieldsForDescriptor(desc);
5313
- const configuredFields = configuredFieldsForDescriptor(desc);
5314
- return {
5315
- key: r.key,
5316
- label: r.label,
5317
- available: r.available,
5318
- hasApiKey: r.methods.some((m) => m.source === "apikey"),
5319
- hasOAuth: r.methods.some((m) => m.source === "oauth"),
5320
- ...customFields ? { customFields } : {},
5321
- ...configuredFields ? { configuredFields } : {}
5322
- };
5323
- });
4040
+ return detectAuth(userDataDir(), providers).map((r) => toAuthStatus(r, providers));
5324
4041
  });
5325
4042
  ipcMain.handle("auth:setApiKey", async (_e, provider, key, cwd) => {
5326
4043
  const desc = descriptorFor(provider, await providersFor(cwd));
@@ -5372,18 +4089,68 @@ function registerChatIpc() {
5372
4089
  removeProviderCredential(userDataDir(), desc);
5373
4090
  applyAuthEnv();
5374
4091
  });
4092
+ ipcMain.handle(
4093
+ "auth:setPreferredCredential",
4094
+ async (_e, provider, source, cwd) => {
4095
+ const providers = await providersFor(cwd);
4096
+ const desc = descriptorFor(provider, providers);
4097
+ if (!desc) {
4098
+ throw new Error(`Unknown provider: ${provider}`);
4099
+ }
4100
+ const outcome = setPreferredCredential(userDataDir(), desc, source);
4101
+ if (outcome === "not-stored") {
4102
+ throw new Error(`no stored ${source} credential for ${desc.label} — sign in with it first`);
4103
+ }
4104
+ applyAuthEnv();
4105
+ return detectAuth(userDataDir(), providers).map((r) => toAuthStatus(r, providers));
4106
+ }
4107
+ );
5375
4108
  ipcMain.handle("auth:startOAuth", (_e, provider) => startOAuth(provider));
5376
4109
  ipcMain.handle("auth:cancelOAuth", (_e, requestId) => cancelOAuth(requestId));
5377
- ipcMain.handle("settings:get", () => readSettings());
5378
- ipcMain.handle("settings:set", (_e, patch) => {
4110
+ ipcMain.handle("settings:get", () => {
4111
+ return readSettings();
4112
+ });
4113
+ ipcMain.handle("settings:set", async (_e, patch) => {
4114
+ const daemon = getDaemonClient();
4115
+ if (daemon) {
4116
+ try {
4117
+ const next2 = await daemon.request("settings.set", { patch });
4118
+ const changedKey = (key) => key in patch;
4119
+ if (changedKey("enabledExtensions") || changedKey("loadProjectExtensions")) {
4120
+ invalidateExtensionsAndNotify();
4121
+ invalidateConfig();
4122
+ shutdownChat();
4123
+ } else if (changedKey("enabledMcps") || changedKey("disabledMcpTools") || changedKey("enabledSkills") || // The plugin gate runs at agent-BUILD time in the shared host, so a
4124
+ // teardown suffices (no registry invalidation) — but without it a
4125
+ // disabled plugin keeps contributing skills and keeps its stdio MCP
4126
+ // servers configured on every live agent.
4127
+ changedKey("enabledPlugins")) {
4128
+ shutdownChat();
4129
+ }
4130
+ if (changedKey("useDaemon")) {
4131
+ shutdownChat();
4132
+ refreshDaemonClient();
4133
+ }
4134
+ return next2;
4135
+ } catch {
4136
+ }
4137
+ }
5379
4138
  const { next, changed } = writeSettingsPatch(patch);
4139
+ if (changed.has("interactionMode") && next.interactionMode === "skip") {
4140
+ getChatHost().interactions.resolveAutomatically();
4141
+ }
5380
4142
  if (changed.has("enabledExtensions") || changed.has("loadProjectExtensions")) {
5381
4143
  invalidateExtensionsAndNotify();
5382
4144
  invalidateConfig();
5383
4145
  shutdownChat();
5384
- } else if (changed.has("enabledMcps") || changed.has("disabledMcpTools") || changed.has("enabledSkills")) {
4146
+ } else if (changed.has("enabledMcps") || changed.has("disabledMcpTools") || changed.has("enabledSkills") || // Same reason as the daemon branch above.
4147
+ changed.has("enabledPlugins")) {
5385
4148
  shutdownChat();
5386
4149
  }
4150
+ if (changed.has("useDaemon")) {
4151
+ shutdownChat();
4152
+ refreshDaemonClient();
4153
+ }
5387
4154
  return next;
5388
4155
  });
5389
4156
  ipcMain.handle("folder:getLastUsed", () => settingsRepo.get(LAST_FOLDER_KEY));
@@ -5393,6 +4160,8 @@ function registerChatIpc() {
5393
4160
  ipcMain.handle("keybindings:save", (_e, map) => saveKeybindings(map));
5394
4161
  ipcMain.handle("keybindings:path", () => keybindingsFilePath());
5395
4162
  ipcMain.handle("keybindings:openInEditor", () => openKeybindingsInEditor());
4163
+ ipcMain.handle("logs:list", () => getLogRecords());
4164
+ installLogBroadcast((record) => sendToAllWindows("logs:record", record, { bufferedElsewhere: true }));
5396
4165
  ipcMain.handle("safelist:list", () => listSafelist());
5397
4166
  ipcMain.handle("safelist:remove", (_e, project, entry) => removeSafelistEntry(project, entry));
5398
4167
  ipcMain.handle("claudeImport:detect", (_e, cwd) => {
@@ -5412,7 +4181,7 @@ function registerChatIpc() {
5412
4181
  })
5413
4182
  );
5414
4183
  ipcMain.handle("agents:list", async (_e, cwd) => {
5415
- const config2 = await getRuntimeConfig(cwd);
4184
+ const config2 = await getRuntimeConfig(scopeCwd(cwd));
5416
4185
  return Object.values(config2.agents).map((a) => ({
5417
4186
  id: a.id,
5418
4187
  label: a.label,
@@ -5505,7 +4274,6 @@ app.whenReady().then(() => {
5505
4274
  }
5506
4275
  applyAuthEnv();
5507
4276
  registerIpc();
5508
- rehydratePendingApprovals();
5509
4277
  createWindow();
5510
4278
  app.on("activate", () => {
5511
4279
  if (BrowserWindow.getAllWindows().length === 0) {