zcode-app-cli 3.14.3-28 → 3.14.4-29

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/bin/zcode.js CHANGED
@@ -6,6 +6,7 @@ import { basename, dirname, join, posix, resolve, sep, win32 } from "node:path";
6
6
  import { fileURLToPath } from "node:url";
7
7
  import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
8
8
  import { access, chmod, link, mkdir, mkdtemp, open, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
9
+ import { AsyncLocalStorage } from "node:async_hooks";
9
10
  import { StringDecoder } from "node:string_decoder";
10
11
  import { createInterface } from "node:readline/promises";
11
12
  import { parseArgs } from "node:util";
@@ -327,6 +328,7 @@ async function markSetupPending(env = process.env) {
327
328
  async function clearSetupPending(env = process.env) {
328
329
  await rm(setupPendingPath(env), { force: true }).catch(() => {});
329
330
  }
331
+ new AsyncLocalStorage();
330
332
  //#endregion
331
333
  //#region src/runtime-config-bridge.ts
332
334
  function providerMigrationNeeded(env = process.env) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "zcode-app-cli",
3
- "version": "3.14.3-28",
3
+ "version": "3.14.4-29",
4
4
  "description": "Unofficial terminal client for the ZCode agent runtime",
5
5
  "keywords": [
6
6
  "agent",
@@ -4,6 +4,7 @@ let node_fs_promises = require("node:fs/promises");
4
4
  let node_path = require("node:path");
5
5
  let node_crypto = require("node:crypto");
6
6
  let node_os = require("node:os");
7
+ let node_async_hooks = require("node:async_hooks");
7
8
  //#region src/config-paths.ts
8
9
  function cliSettingsPath(env = process.env, platform = process.platform, fallbackHome = (0, node_os.homedir)()) {
9
10
  const path = platform === "win32" ? node_path.win32 : node_path.posix;
@@ -173,102 +174,82 @@ async function sendTuiBackgroundTaskMessage(app, bridge, input) {
173
174
  //#endregion
174
175
  //#region src/runtime-background-restore.ts
175
176
  const maximumReminderLength = 4e3;
176
- function record$1(value) {
177
- return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
178
- }
179
- function text(value) {
180
- return typeof value === "string" && value.length > 0 ? value : void 0;
181
- }
182
- function parseSpawn(output, input) {
183
- try {
184
- const parsed = record$1(JSON.parse(output));
185
- if (parsed) return parsed;
186
- } catch {}
187
- if (!output.includes("Async agent launched successfully.")) return void 0;
188
- const agentId = /(?:^|\n)agentId:\s*([^\s(]+)/u.exec(output)?.[1];
189
- if (!agentId) return void 0;
190
- return {
191
- status: "async_launched",
192
- agentId,
193
- agentType: text(input?.subagent_type) ?? text(input?.agentType),
194
- childSessionId: `sess_subagent_${agentId}`,
195
- description: text(input?.description),
196
- prompt: text(input?.prompt),
197
- outputFile: /(?:^|\n)output_file:\s*([^\r\n]+)/u.exec(output)?.[1]?.trim()
198
- };
199
- }
200
- async function readMetadata(outputFile) {
201
- if (!text(outputFile)) return void 0;
202
- try {
203
- return record$1(JSON.parse(await (0, node_fs_promises.readFile)((0, node_path.join)((0, node_path.dirname)(outputFile), "metadata.json"), "utf8")));
204
- } catch {
205
- return;
206
- }
207
- }
208
- function enrichSpawn(spawn, metadata, sessionId) {
209
- if (!metadata || typeof metadata.agentId === "string" && metadata.agentId !== spawn.agentId || typeof metadata.parentSessionId === "string" && metadata.parentSessionId !== sessionId) return spawn;
210
- return {
211
- ...spawn,
212
- agentType: text(metadata.profileId) ?? spawn.agentType,
213
- childSessionId: text(metadata.childSessionId) ?? spawn.childSessionId,
214
- description: text(metadata.description) ?? spawn.description,
215
- outputFile: text(metadata.outputFile) ?? spawn.outputFile,
216
- prompt: text(metadata.prompt) ?? spawn.prompt,
217
- error: text(metadata.error) ?? spawn.error
218
- };
177
+ async function restoreSessionChildren(app, sessionId, queries) {
178
+ const store = app.runtime?.sessionStore;
179
+ const eventStore = app.runtime?.getSessionEventStore?.();
180
+ if (!store || !eventStore) return [];
181
+ const parentSession = await store.getSession(sessionId);
182
+ if (!parentSession) return [];
183
+ const [messages, parentEvents, parentProjection] = await Promise.all([
184
+ store.messages({ sessionID: sessionId }),
185
+ eventStore.getEvents(sessionId),
186
+ app.runtime?.getProjection?.()
187
+ ]);
188
+ const ids = [...new Set(queries.collectChildSessionIds(parentSession, messages, parentEvents))];
189
+ const valid = (await Promise.all(ids.map(async (id) => {
190
+ const session = await store.getSession(id);
191
+ if (!session || session.parentID !== sessionId || session.taskType !== "subagent_child") return null;
192
+ const [messages, events] = await Promise.all([store.messages({ sessionID: id }), eventStore.getEvents(id)]);
193
+ return {
194
+ session,
195
+ messages,
196
+ projection: events.length ? queries.projectChildEvents(events) : void 0
197
+ };
198
+ }))).filter((child) => child !== null);
199
+ const projection = queries.projectSubagents({
200
+ revision: 0,
201
+ parentSession,
202
+ messages,
203
+ parentEvents,
204
+ parentProjection,
205
+ childSessionsById: new Map(valid.map((child) => [child.session.id, child.session])),
206
+ childMessagesById: new Map(valid.map((child) => [child.session.id, child.messages])),
207
+ childProjectionsById: new Map(valid.flatMap((child) => child.projection ? [[child.session.id, child.projection]] : []))
208
+ });
209
+ return [...projection.running, ...projection.ended].map((agent) => ({
210
+ taskId: agent.agentId ?? agent.toolCallId,
211
+ agentId: agent.agentId ?? agent.toolCallId,
212
+ agentType: agent.subagentType,
213
+ childSessionId: agent.childSessionId,
214
+ description: agent.title,
215
+ isBackgrounded: true,
216
+ parentSessionId: sessionId,
217
+ parentToolCallId: agent.toolCallId,
218
+ startedAt: agent.startedAt,
219
+ completedAt: agent.endedAt,
220
+ status: [
221
+ "running",
222
+ "waiting",
223
+ "blocked"
224
+ ].includes(agent.status) ? "running" : agent.status === "success" ? "completed" : agent.status === "failed" ? "failed" : "stopped",
225
+ error: agent.status === "failed" ? agent.summary : void 0,
226
+ output: agent.status === "success" && agent.summary ? {
227
+ status: "completed",
228
+ content: [{
229
+ type: "text",
230
+ text: agent.summary
231
+ }]
232
+ } : void 0,
233
+ taskType: "local_agent",
234
+ type: "local_agent"
235
+ }));
219
236
  }
220
- async function restore(app) {
237
+ async function restore(app, queries) {
221
238
  const runtime = app.runtime;
222
239
  const registry = runtime?.runtimeTaskRegistry;
223
240
  const sessionId = app.sessionId;
224
241
  if (!registry?.register || typeof sessionId !== "string" || sessionId === app.$zRestoredBackgroundTasksSession) return;
225
- app.$zRestoredBackgroundTasksSession = sessionId;
226
242
  app.$zRestoredBackgroundTasksLog = [];
227
243
  try {
228
- const messages = await app.loadSessionTranscript?.() ?? [];
244
+ const tasks = await restoreSessionChildren(app, sessionId, queries);
245
+ if (app.sessionId !== sessionId || app.runtime !== runtime) return;
229
246
  const restored = [];
230
- for (const messageValue of messages) {
231
- const parts = record$1(messageValue)?.parts;
232
- if (!Array.isArray(parts)) continue;
233
- for (const value of parts) {
234
- const part = record$1(value);
235
- if (part?.type !== "tool") continue;
236
- const tool = (typeof part.toolName === "string" ? part.toolName : typeof part.tool === "string" ? part.tool : "").trim().toLowerCase();
237
- if (![
238
- "agent",
239
- "subagent",
240
- "task"
241
- ].includes(tool)) continue;
242
- const state = record$1(part.state);
243
- const output = typeof part.output === "string" ? part.output : state?.output;
244
- if (typeof output !== "string" || !output.trim()) continue;
245
- let spawn = parseSpawn(output, record$1(part.input ?? state?.input));
246
- if (!spawn || !["async_launched", "backgrounded"].includes(String(spawn.status)) || !text(spawn.agentId)) continue;
247
- const metadata = await readMetadata(spawn.outputFile);
248
- spawn = enrichSpawn(spawn, metadata, sessionId);
249
- const agentId = spawn.agentId;
250
- if (registry.get?.(agentId)) continue;
251
- const task = {
252
- taskId: agentId,
253
- agentId,
254
- agentType: text(spawn.agentType) ?? "general-purpose",
255
- childSessionId: text(spawn.childSessionId) ?? `sess_subagent_${agentId}`,
256
- description: text(spawn.description),
257
- error: text(spawn.error),
258
- isBackgrounded: true,
259
- outputFile: text(spawn.outputFile),
260
- parentToolCallId: text(part.toolCallId) ?? text(part.callID),
261
- parentSessionId: sessionId,
262
- prompt: text(spawn.prompt),
263
- startedAt: record$1(state?.time)?.start,
264
- status: metadata?.status === "completed" ? "completed" : metadata?.status === "failed" ? "failed" : "stopped",
265
- taskType: "local_agent",
266
- type: "local_agent"
267
- };
268
- registry.register(task);
269
- restored.push(task);
270
- }
247
+ for (const task of tasks) {
248
+ if (registry.get?.(task.taskId)) continue;
249
+ registry.register(task);
250
+ restored.push(task);
271
251
  }
252
+ app.$zRestoredBackgroundTasksSession = sessionId;
272
253
  if (restored.length === 0) return;
273
254
  const taskIds = restored.slice(-32).map((task) => `- ${task.taskId} (${task.status})`).join("\n").slice(0, maximumReminderLength);
274
255
  runtime?.messageHistory?.addAttachment?.("task_status", `Background agent tasks from this resumed session have been restored and are available again.
@@ -277,14 +258,17 @@ Use TaskOutput to collect results or SendMessage to continue a task. Do not assu
277
258
  Restored task IDs:\n${taskIds}`);
278
259
  app.$zRestoredBackgroundTasksLog = [...app.$zRestoredBackgroundTasksLog ?? [], ...restored].slice(-64);
279
260
  } catch {
280
- app.$zRestoredBackgroundTasksSession = void 0;
261
+ if (app.sessionId === sessionId) app.$zRestoredBackgroundTasksSession = void 0;
281
262
  }
282
263
  }
283
264
  const pendingRestores = /* @__PURE__ */ new WeakMap();
284
- async function restoreTuiBackgroundTasks(app) {
265
+ async function restoreTuiBackgroundTasks(app, queries) {
285
266
  const pending = pendingRestores.get(app);
286
- if (pending) return pending;
287
- const operation = restore(app);
267
+ if (pending) {
268
+ await pending;
269
+ return restoreTuiBackgroundTasks(app, queries);
270
+ }
271
+ const operation = restore(app, queries);
288
272
  pendingRestores.set(app, operation);
289
273
  try {
290
274
  await operation;
@@ -293,6 +277,370 @@ async function restoreTuiBackgroundTasks(app) {
293
277
  }
294
278
  }
295
279
  //#endregion
280
+ //#region src/runtime-sqlite-connection.ts
281
+ const sqliteOperationScope = new node_async_hooks.AsyncLocalStorage();
282
+ function isSqliteBusyError(error) {
283
+ if (!error || typeof error !== "object" || !("errcode" in error)) return false;
284
+ const code = error.errcode;
285
+ return typeof code === "number" && Number.isInteger(code) && (code & 255) === 5;
286
+ }
287
+ const guardedConnections = /* @__PURE__ */ new WeakSet();
288
+ const statementExecutors = /* @__PURE__ */ new Set([
289
+ "run",
290
+ "get",
291
+ "all"
292
+ ]);
293
+ /** Apply short waits only inside an audited operation, without changing other clients of the connection. */
294
+ function installSqliteConnectionWait(db) {
295
+ if (guardedConnections.has(db)) return;
296
+ const execute = db.exec.bind(db);
297
+ const prepare = db.prepare.bind(db);
298
+ const readTimeout = prepare("pragma busy_timeout");
299
+ const call = (operation) => {
300
+ const scope = sqliteOperationScope.getStore();
301
+ if (!scope?.active || scope.db !== db || scope.nativeBusyMs === void 0) return operation();
302
+ const previous = readTimeout.get().timeout;
303
+ const timeout = Math.min(previous, scope.nativeBusyMs, Math.max(0, Math.floor(scope.deadline - performance.now())));
304
+ if (timeout === previous) return operation();
305
+ execute(`pragma busy_timeout = ${timeout}`);
306
+ let failed = false;
307
+ try {
308
+ return operation();
309
+ } catch (error) {
310
+ failed = true;
311
+ throw error;
312
+ } finally {
313
+ try {
314
+ execute(`pragma busy_timeout = ${previous}`);
315
+ } catch (error) {
316
+ if (!failed) throw error;
317
+ }
318
+ }
319
+ };
320
+ db.exec = (sql) => call(() => execute(sql));
321
+ db.prepare = (sql) => {
322
+ const statement = call(() => prepare(sql));
323
+ return new Proxy(statement, { get(target, key) {
324
+ const value = Reflect.get(target, key, target);
325
+ if (typeof value !== "function") return value;
326
+ return statementExecutors.has(key) ? (...args) => call(() => Reflect.apply(value, target, args)) : value.bind(target);
327
+ } });
328
+ };
329
+ guardedConnections.add(db);
330
+ }
331
+ //#endregion
332
+ //#region src/runtime-sqlite-usage.ts
333
+ const sqliteUsageCleanupIntervalMs = 5 * 6e4;
334
+ const sqliteUsageCleanupRetryMs = 1e3;
335
+ const nextCleanup = /* @__PURE__ */ new WeakMap();
336
+ const expiredUsageQuery = `select
337
+ exists(select 1 from model_usage where started_at < ?) or
338
+ exists(select 1 from turn_usage where started_at < ?) or
339
+ exists(select 1 from tool_usage where started_at < ?) as expired`;
340
+ /** The native function still supplies the cutoff and owns the cleanup transaction. */
341
+ function pruneSqliteUsage(db, options, beforeTime, prune) {
342
+ if (options.beforeTime !== void 0) {
343
+ prune();
344
+ return;
345
+ }
346
+ const now = performance.now();
347
+ if (now < (nextCleanup.get(db) ?? 0)) return;
348
+ if (db.isTransaction) {
349
+ nextCleanup.set(db, now + sqliteUsageCleanupRetryMs);
350
+ return;
351
+ }
352
+ try {
353
+ if (db.prepare(expiredUsageQuery).get(beforeTime, beforeTime, beforeTime).expired) prune();
354
+ nextCleanup.set(db, performance.now() + sqliteUsageCleanupIntervalMs);
355
+ } catch (error) {
356
+ if (!isSqliteBusyError(error) || db.isTransaction) throw error;
357
+ nextCleanup.set(db, performance.now() + sqliteUsageCleanupRetryMs);
358
+ }
359
+ }
360
+ //#endregion
361
+ //#region src/runtime-sqlite-recovery.ts
362
+ const sqliteWriteRecoveryPolicy = {
363
+ nativeBusyMs: 25,
364
+ writeBudgetMs: 3e4,
365
+ usageBudgetMs: 3e4,
366
+ initialDelayMs: 10,
367
+ maximumDelayMs: 200
368
+ };
369
+ const sqliteReplayableWrites = [
370
+ "createSession",
371
+ "updateSession",
372
+ "createForkedSessionWithMetadata",
373
+ "commitForkBundle",
374
+ "commitSharedContextImportBundle",
375
+ "transitionSharedContextImport",
376
+ "saveMessage",
377
+ "removeMessage",
378
+ "savePart",
379
+ "removePart",
380
+ "saveSessionEntry",
381
+ "saveSessionInput",
382
+ "updateSessionInputs",
383
+ "promoteSessionInput",
384
+ "markSessionInputPromoted",
385
+ "settleSessionInput",
386
+ "commitPermissionFullAccess",
387
+ "updateTodos",
388
+ "recordInputHistory",
389
+ "saveProjectPermission",
390
+ "setRevert",
391
+ "clearRevert"
392
+ ];
393
+ const usageWrites = [
394
+ "recordModelUsage",
395
+ "upsertTurnUsage",
396
+ "upsertToolUsage"
397
+ ];
398
+ const orderedWrites = [
399
+ "setTarget",
400
+ "cloneTargetForFork",
401
+ "createTarget",
402
+ "updateTargetStatus",
403
+ "startTargetRun",
404
+ "heartbeatTargetRun",
405
+ "finishTargetRun",
406
+ "recoverInterruptedTargetRun",
407
+ "accountTargetUsage",
408
+ "updateTargetSummaryTitle",
409
+ "clearTarget",
410
+ "claimLegacySessionWorkspace",
411
+ "repairLegacyRemoteSessionWorkspace",
412
+ "repairRemoteSessionPaths",
413
+ "upsertScriptWorkflowDefinition",
414
+ "createScriptWorkflowRun",
415
+ "updateScriptWorkflowRun",
416
+ "createScriptWorkflowActivity",
417
+ "updateScriptWorkflowActivity",
418
+ "appendScriptWorkflowEvent",
419
+ "createSessionTaskLink",
420
+ "pruneUsage"
421
+ ];
422
+ const queues = /* @__PURE__ */ new Map();
423
+ const installed = /* @__PURE__ */ new WeakMap();
424
+ const activeConnections = /* @__PURE__ */ new WeakMap();
425
+ var SqliteWriteRecoveryError = class extends Error {
426
+ operation;
427
+ attempts;
428
+ elapsedMs;
429
+ code = "ERR_SQLITE_ERROR";
430
+ errcode;
431
+ constructor(cause, operation, attempts, elapsedMs) {
432
+ super(`${cause.message}; SQLite ${operation} exhausted recovery after ${attempts} attempts (${elapsedMs} ms)`, { cause });
433
+ this.operation = operation;
434
+ this.attempts = attempts;
435
+ this.elapsedMs = elapsedMs;
436
+ this.name = "SqliteWriteRecoveryError";
437
+ this.errcode = cause.errcode;
438
+ }
439
+ };
440
+ function sqliteRecoveryStats(store) {
441
+ const stats = installed.get(store)?.stats;
442
+ return stats ? {
443
+ ...stats,
444
+ ...stats.lastRecovery ? { lastRecovery: { ...stats.lastRecovery } } : {}
445
+ } : void 0;
446
+ }
447
+ function queueKey(store) {
448
+ const path = store.getDatabasePath();
449
+ if (path === ":memory:") return store.db;
450
+ try {
451
+ return (0, node_fs.realpathSync)(path);
452
+ } catch {
453
+ return (0, node_path.resolve)(path);
454
+ }
455
+ }
456
+ function delay(ms, signal) {
457
+ if (signal.aborted) return Promise.reject(signal.reason);
458
+ return new Promise((resolve, reject) => {
459
+ const finish = () => {
460
+ signal.removeEventListener("abort", abort);
461
+ resolve();
462
+ };
463
+ const timer = setTimeout(finish, ms);
464
+ const abort = () => {
465
+ clearTimeout(timer);
466
+ signal.removeEventListener("abort", abort);
467
+ reject(signal.reason);
468
+ };
469
+ signal.addEventListener("abort", abort, { once: true });
470
+ });
471
+ }
472
+ async function drain(queue, key) {
473
+ queue.active = true;
474
+ try {
475
+ while (queue.jobs.length) {
476
+ const preferred = queue.jobs.findIndex((job) => job.priority === "conversation");
477
+ const [job] = queue.jobs.splice(preferred < 0 ? 0 : preferred, 1);
478
+ try {
479
+ job.resolve(await job.run());
480
+ } catch (error) {
481
+ job.reject(error);
482
+ }
483
+ }
484
+ } finally {
485
+ queue.active = false;
486
+ if (queue.users === 0) queues.delete(key);
487
+ }
488
+ }
489
+ async function serviceConversationWrites(queue) {
490
+ let index;
491
+ while ((index = queue.jobs.findIndex((job) => job.priority === "conversation")) >= 0) {
492
+ const [job] = queue.jobs.splice(index, 1);
493
+ try {
494
+ job.resolve(await job.run());
495
+ } catch (error) {
496
+ job.reject(error);
497
+ }
498
+ }
499
+ }
500
+ /** Install once, after migration; do not replace SQL or the native transaction owner. */
501
+ function installSqliteWriteRecovery(store, options = {}) {
502
+ if (installed.has(store)) return;
503
+ const methods = store;
504
+ const originals = [
505
+ ...sqliteReplayableWrites.map((name) => ({
506
+ name,
507
+ retry: true,
508
+ priority: "conversation"
509
+ })),
510
+ ...usageWrites.map((name) => ({
511
+ name,
512
+ retry: true,
513
+ priority: "usage"
514
+ })),
515
+ ...orderedWrites.map((name) => ({
516
+ name,
517
+ retry: false,
518
+ priority: name === "pruneUsage" ? "usage" : "conversation"
519
+ }))
520
+ ].map((spec) => {
521
+ const method = methods[spec.name];
522
+ if (typeof method !== "function") throw new Error(`SQLite recovery requires native ${spec.name}.`);
523
+ return {
524
+ ...spec,
525
+ method
526
+ };
527
+ });
528
+ const key = queueKey(store);
529
+ const queue = queues.get(key) ?? {
530
+ jobs: [],
531
+ active: false,
532
+ users: 0
533
+ };
534
+ const recovery = {
535
+ controller: new AbortController(),
536
+ stats: {
537
+ recoveredWrites: 0,
538
+ retries: 0,
539
+ exhaustedWrites: 0
540
+ }
541
+ };
542
+ installSqliteConnectionWait(store.db);
543
+ queue.users++;
544
+ queues.set(key, queue);
545
+ installed.set(store, recovery);
546
+ const close = store.close.bind(store);
547
+ store.close = () => {
548
+ if (!recovery.controller.signal.aborted) {
549
+ const reason = /* @__PURE__ */ new Error("SQLite session store closed while waiting for a write.");
550
+ recovery.controller.abort(reason);
551
+ const cancelled = queue.jobs.filter((job) => job.owner === recovery);
552
+ queue.jobs = queue.jobs.filter((job) => job.owner !== recovery);
553
+ for (const job of cancelled) job.reject(reason);
554
+ queue.users--;
555
+ if (!queue.active && queue.users === 0) queues.delete(key);
556
+ }
557
+ close();
558
+ };
559
+ for (const { name, method, retry, priority } of originals) methods[name] = (...args) => {
560
+ const signal = recovery.controller.signal;
561
+ if (signal.aborted) return Promise.reject(signal.reason);
562
+ const scope = sqliteOperationScope.getStore();
563
+ if (scope?.active && scope.db === store.db) return method.apply(store, args);
564
+ if (store.db.isTransaction && !activeConnections.has(store.db)) return method.apply(store, args);
565
+ const startedAt = performance.now();
566
+ const budget = priority === "usage" ? options.usageBudgetMs ?? sqliteWriteRecoveryPolicy.usageBudgetMs : options.writeBudgetMs ?? sqliteWriteRecoveryPolicy.writeBudgetMs;
567
+ return new Promise((resolve, reject) => {
568
+ queue.jobs.push({
569
+ owner: recovery,
570
+ priority,
571
+ resolve,
572
+ reject,
573
+ run: () => runWrite({
574
+ store,
575
+ recovery,
576
+ operation: name,
577
+ retry,
578
+ startedAt,
579
+ deadline: startedAt + budget,
580
+ nativeBusyMs: options.nativeBusyMs ?? sqliteWriteRecoveryPolicy.nativeBusyMs,
581
+ ...priority === "usage" ? { serviceConversation: () => serviceConversationWrites(queue) } : {},
582
+ call: () => method.apply(store, args)
583
+ })
584
+ });
585
+ if (!queue.active) drain(queue, key);
586
+ });
587
+ };
588
+ }
589
+ async function runWrite(input) {
590
+ const { store, recovery, operation, startedAt, deadline } = input;
591
+ const signal = recovery.controller.signal;
592
+ let attempts = 0;
593
+ let backoff = sqliteWriteRecoveryPolicy.initialDelayMs;
594
+ let lastBusy;
595
+ while (true) {
596
+ if (signal.aborted) throw signal.reason;
597
+ if (performance.now() >= deadline) {
598
+ recovery.stats.exhaustedWrites++;
599
+ const elapsed = Math.round(performance.now() - startedAt);
600
+ if (lastBusy) throw new SqliteWriteRecoveryError(lastBusy, operation, attempts, elapsed);
601
+ throw new Error(`SQLite ${operation} waited ${elapsed} ms for preceding writes; no write was attempted.`);
602
+ }
603
+ if (store.db.isTransaction) {
604
+ await delay(Math.min(backoff, deadline - performance.now()), signal);
605
+ backoff = Math.min(sqliteWriteRecoveryPolicy.maximumDelayMs, backoff * 2);
606
+ await input.serviceConversation?.();
607
+ continue;
608
+ }
609
+ attempts++;
610
+ const scope = {
611
+ db: store.db,
612
+ active: true,
613
+ deadline,
614
+ ...input.retry ? { nativeBusyMs: input.nativeBusyMs } : {}
615
+ };
616
+ activeConnections.set(store.db, scope);
617
+ try {
618
+ const result = await sqliteOperationScope.run(scope, input.call);
619
+ if (attempts > 1) {
620
+ recovery.stats.recoveredWrites++;
621
+ recovery.stats.lastRecovery = {
622
+ operation,
623
+ attempts,
624
+ elapsedMs: Math.round(performance.now() - startedAt)
625
+ };
626
+ }
627
+ return result;
628
+ } catch (error) {
629
+ if (!input.retry || !isSqliteBusyError(error) || store.db.isTransaction) throw error;
630
+ lastBusy = error;
631
+ } finally {
632
+ scope.active = false;
633
+ activeConnections.delete(store.db);
634
+ }
635
+ recovery.stats.retries++;
636
+ const remaining = deadline - performance.now();
637
+ if (remaining <= 0) continue;
638
+ await delay(Math.min(remaining, backoff * (.5 + Math.random() * .5)), signal);
639
+ await input.serviceConversation?.();
640
+ backoff = Math.min(sqliteWriteRecoveryPolicy.maximumDelayMs, backoff * 2);
641
+ }
642
+ }
643
+ //#endregion
296
644
  //#region src/runtime-config-bridge.ts
297
645
  function record(value) {
298
646
  return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
@@ -410,10 +758,13 @@ async function migrateLegacyProviders(options) {
410
758
  }
411
759
  //#endregion
412
760
  exports.assertSessionModelReady = assertSessionModelReady;
761
+ exports.installSqliteWriteRecovery = installSqliteWriteRecovery;
413
762
  exports.mergeDesktopSettings = mergeDesktopSettings;
414
763
  exports.migrateLegacyProviders = migrateLegacyProviders;
415
764
  exports.providerMigrationNeeded = providerMigrationNeeded;
765
+ exports.pruneSqliteUsage = pruneSqliteUsage;
416
766
  exports.readSessionModelState = readSessionModelState;
417
767
  exports.readTuiRuntimeProjection = readTuiRuntimeProjection;
418
768
  exports.restoreTuiBackgroundTasks = restoreTuiBackgroundTasks;
419
769
  exports.sendTuiBackgroundTaskMessage = sendTuiBackgroundTaskMessage;
770
+ exports.sqliteRecoveryStats = sqliteRecoveryStats;
@@ -1,9 +1,9 @@
1
1
  {
2
- "appVersion": "3.14.3",
2
+ "appVersion": "3.14.4",
3
3
  "cliVersion": "0.16.9",
4
- "extractedAt": "2026-09-24T22:18:54.425Z",
5
- "sha512": "VDYryL9bIYjM3uxRNJ8sRw5S5z9LBmRvvW1amQ9wEnhJBMc3Rlb2g8JvxWv04CPn0GgKHEJEZmWmLZuI6EYg1g==",
6
- "source": "https://cdn-zcode.z.ai/zcode/electron/releases/3.14.3/linux-x64/ZCode-3.14.3-linux-x64.deb",
4
+ "extractedAt": "2026-09-29T12:47:36.709Z",
5
+ "sha512": "CMaAUbHehEEGuClDJeJI30ufA0zAgzfXgzV4ES200EuGDt0yYhEpzvtjayxvE/ag9T9ThnDg1eP4o3j9HkCHKg==",
6
+ "source": "https://cdn-zcode.z.ai/zcode/electron/releases/3.14.4/linux-x64/ZCode-3.14.4-linux-x64.deb",
7
7
  "runtimeCapabilities": {
8
8
  "schemaVersion": 1,
9
9
  "cli": {
@@ -176,6 +176,11 @@
176
176
  "requirement": "required",
177
177
  "status": "applied"
178
178
  },
179
+ {
180
+ "id": "sqlite-write-recovery",
181
+ "requirement": "required",
182
+ "status": "applied"
183
+ },
179
184
  {
180
185
  "id": "oauth-http-errors",
181
186
  "requirement": "optional",
@@ -170599,12 +170599,6 @@ var ZCodeTui = class {
170599
170599
  priority: 20
170600
170600
  });
170601
170601
  }
170602
- const backgroundCount = this.runtimeProjection?.backgroundJobs.filter(isActiveBackgroundJob).length ?? 0;
170603
- if (backgroundCount > 0) fields.push({
170604
- text: this.theme.accent(`${backgroundCount} in background`),
170605
- compactText: this.theme.accent(`bg ${backgroundCount}`),
170606
- priority: 80
170607
- });
170608
170602
  const search = this.transcript.searchStatus();
170609
170603
  if (search) fields.push({
170610
170604
  text: this.theme.accent(`find ${search.current}/${search.total}: ${search.query}`),
@@ -170660,7 +170654,8 @@ var ZCodeTui = class {
170660
170654
  if (this.turnStartedAt !== void 0) this.turnElapsedMilliseconds = Math.max(0, performance.now() - this.turnStartedAt);
170661
170655
  const showElapsed = this.turnStartedAt !== void 0 || !this.activity && this.turnTimingVisible;
170662
170656
  const text = turnStatusText(this.activity, this.turnElapsedMilliseconds, showElapsed, this.turnStartedAt !== void 0 && this.animateTurnTimer, this.turnStartedAt === void 0 && this.turnTimingVisible) ?? "";
170663
- const left = text ? this.activity ? this.theme.accent(text) : this.theme.muted(text) : "";
170657
+ const backgroundCount = this.runtimeProjection?.backgroundJobs.filter(isActiveBackgroundJob).length ?? 0;
170658
+ const left = [text ? this.activity ? this.theme.accent(text) : this.theme.muted(text) : "", backgroundCount > 0 ? this.theme.accent(`${backgroundCount} in background`) : ""].filter(Boolean).join(this.theme.muted(" · "));
170664
170659
  const goalText = goalStatusText(this.goal);
170665
170660
  const goalLabel = goalStatusLabel(this.goal);
170666
170661
  const goalStyle = this.goal?.status === "complete" ? this.theme.success : this.goal?.status === "paused" || this.goal?.status === "budget_limited" ? this.theme.warning : this.theme.accent;
@@ -170712,7 +170707,7 @@ var ZCodeTui = class {
170712
170707
  totalTokens: projection.totalTokenCount,
170713
170708
  turnCount: projection.turnCount
170714
170709
  }, Boolean(this.options.readSessionUsage));
170715
- this.updateRuntimeActivity(false);
170710
+ this.updateTurnStatus(false);
170716
170711
  }
170717
170712
  /**
170718
170713
  * Surface tasks the persisted background-agent restore bridge re-registered.
@@ -87460,7 +87460,7 @@ var ZCODE_CUA_HELPER_BUILD_ID;
87460
87460
  var init_cua_version = __esm({
87461
87461
  "src/broker/shared/cua-version.ts"() {
87462
87462
  "use strict";
87463
- ZCODE_CUA_HELPER_BUILD_ID = true ? "pipeline-293504-ab4d5e6b" : "";
87463
+ ZCODE_CUA_HELPER_BUILD_ID = true ? "pipeline-298526-10bbcea5" : "";
87464
87464
  }
87465
87465
  });
87466
87466
  var init_shared = __esm({