zcode-app-cli 3.14.3-27 → 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/README.md CHANGED
@@ -304,6 +304,11 @@ picker to return to input selection, then `Esc` again to close rewind.
304
304
  /status inspect detailed runtime and session status
305
305
  /rename <title> rename the current session
306
306
  /activity inspect every active tool and open task
307
+ /queue reorder, delete or edit queued drafts
308
+ /queue pause|resume pause or resume automatic draft submission
309
+ /edit-message rewind to an earlier question and edit it
310
+ /retry rewind to an earlier question and send it again
311
+ /workflows inspect workflow progress, artifacts and recovery
307
312
  /tasks inspect and manage background tasks
308
313
  /tasks message <id> <text> send guidance to a running background agent
309
314
  /tasks resume <id> [text] resume a stopped or failed background agent
@@ -320,6 +325,19 @@ picker to return to input selection, then `Esc` again to close rewind.
320
325
  runtime's own `/clear` is an alias of `/new` and starts a fresh session, so it
321
326
  is forwarded to the runtime unchanged.
322
327
 
328
+ `/queue` manages local next-turn drafts and pauses automatic sending while its
329
+ picker is open. Inputs already accepted by the runtime cannot be edited here.
330
+ `/queue pause` persists across turns until `/queue resume`. Moving a draft to
331
+ the editor preserves its original text; Tab queues the edited draft again.
332
+
333
+ `/edit-message` and `/retry` require an idle conversation and ask before removing
334
+ later turns. Both use conversation-only rewind and keep workspace files as they
335
+ are. Editing restores the selected question to the editor; retry sends it again
336
+ with the current model. Existing `/fork` remains available for checkpoint-based
337
+ branches that preserve the original conversation.
338
+ These actions restore question text only; original image attachments are not
339
+ resent. Use `/edit-message` and reattach images when they are needed.
340
+
323
341
  The task center keeps autonomous task output out of the foreground transcript.
324
342
  The main conversation receives only compact completion, reply and failure
325
343
  notices; select the task to inspect its output and task-scoped activity. Agent
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-27",
3
+ "version": "3.14.4-29",
4
4
  "description": "Unofficial terminal client for the ZCode agent runtime",
5
5
  "keywords": [
6
6
  "agent",
@@ -70,7 +70,7 @@
70
70
  "test:node": "node --test test/node/*.test.cjs",
71
71
  "test:tui": "bun run test:tui:component && bun run test:tui:e2e",
72
72
  "test:tui:component": "bun test test/tui/scenario-http.test.ts test/tui/scenario-runtime.test.ts test/tui/scenario-shell.test.ts test/tui/scenario-workspace.test.ts test/tui/terminal-screen.test.ts",
73
- "test:tui:e2e": "bun test test/tui/allowlisted-shell.test.ts test/tui/http-mock.test.ts test/tui/model-resume.test.ts test/tui/permission-request-queue.test.ts test/tui/run-scenario.test.ts test/tui/session-rename.test.ts test/tui/terminal-session.test.ts test/tui/write-and-diff.test.ts",
73
+ "test:tui:e2e": "bun test test/tui/allowlisted-shell.test.ts test/tui/dynamic-workflows.test.ts test/tui/http-mock.test.ts test/tui/input-actions.test.ts test/tui/model-resume.test.ts test/tui/permission-request-queue.test.ts test/tui/run-scenario.test.ts test/tui/runtime-refresh.test.ts test/tui/session-rename.test.ts test/tui/terminal-session.test.ts test/tui/write-and-diff.test.ts",
74
74
  "test:tui:host": "bun test test/tui/scenario-mountx.test.ts",
75
75
  "test:tui:manual": "bun scripts/tui-scenario.ts --manual",
76
76
  "test:tui-scenario": "bun scripts/tui-scenario.ts",
@@ -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;
@@ -87,6 +88,559 @@ function assertSessionModelReady(options) {
87
88
  if (state.issue) throw new Error(`${state.issue.message} Resume interactively with zcode --resume ${options.sessionId} and use /model to choose a replacement. No model request was sent.`);
88
89
  }
89
90
  //#endregion
91
+ //#region src/runtime-tui-bridge.ts
92
+ const maximumTaskMessageLength = 2e4;
93
+ const maximumTaskSummaryLength = 200;
94
+ function taskDetail(task) {
95
+ const running = task.status === "running";
96
+ const kind = task.taskType ?? task.type;
97
+ return {
98
+ taskId: task.taskId,
99
+ taskKind: kind,
100
+ agentId: task.agentId,
101
+ agentType: task.agentType,
102
+ childSessionId: task.childSessionId,
103
+ parentSessionId: task.parentSessionId,
104
+ parentToolCallId: task.parentToolCallId,
105
+ turnId: task.turnId,
106
+ prompt: task.prompt,
107
+ error: running ? null : task.error instanceof Error ? task.error.message : typeof task.error === "string" ? task.error : void 0,
108
+ outputPath: task.outputFile,
109
+ status: task.status,
110
+ description: task.description,
111
+ startedAt: task.startedAt,
112
+ completedAt: running ? null : task.completedAt,
113
+ cancelRequestedAt: running ? null : task.cancelRequestedAt,
114
+ blocked: running ? null : task.blocked,
115
+ blockedReason: running ? null : task.blockedReason,
116
+ cancellable: kind === "local_agent" ? running : task.cancellable
117
+ };
118
+ }
119
+ async function readTuiRuntimeProjection(app, bridge) {
120
+ const executionState = await app.readExecutionState();
121
+ await bridge.$zRestorePersistedBackgroundTasks?.(app);
122
+ const projection = await app.runtime?.getProjection?.();
123
+ if (!projection) return null;
124
+ const details = Object.values(app.runtime?.runtimeTaskRegistry?.all?.() ?? {}).filter((task) => task.isBackgrounded === true).map(taskDetail);
125
+ const tasks = Array.isArray(projection.backgroundTasks) ? projection.backgroundTasks.slice() : [];
126
+ for (const detail of details) {
127
+ const index = tasks.findIndex((existing) => existing.taskId === detail.taskId);
128
+ if (index < 0) tasks.push(detail);
129
+ else tasks[index] = {
130
+ ...tasks[index],
131
+ ...Object.fromEntries(Object.entries(detail).filter(([, value]) => value !== void 0))
132
+ };
133
+ }
134
+ return {
135
+ ...projection,
136
+ ...executionState && typeof executionState === "object" ? executionState : {},
137
+ backgroundTasks: tasks,
138
+ backgroundTaskDetails: details,
139
+ restoredBackgroundTasks: Array.isArray(app.$zRestoredBackgroundTasksLog) ? app.$zRestoredBackgroundTasksLog : []
140
+ };
141
+ }
142
+ async function sendTuiBackgroundTaskMessage(app, bridge, input) {
143
+ await bridge.$zRestorePersistedBackgroundTasks?.(app);
144
+ const runtime = app.runtime;
145
+ let task = runtime?.runtimeTaskRegistry?.get?.(input?.taskId);
146
+ if (!task && typeof app.sessionId === "string") {
147
+ app.$zRestoredBackgroundTasksSession = void 0;
148
+ await bridge.$zRestorePersistedBackgroundTasks?.(app);
149
+ task = runtime?.runtimeTaskRegistry?.get?.(input?.taskId);
150
+ }
151
+ if (!runtime?.subagentPort?.sendMessage) throw new Error("Background agent messaging is unavailable in this runtime.");
152
+ if (!task || (task.type ?? task.taskType) !== "local_agent") throw new Error("The selected task is not a local agent.");
153
+ if (typeof input?.message !== "string" || !input.message.trim()) throw new Error("Enter a message for the background agent.");
154
+ const message = input.message.trim().slice(0, maximumTaskMessageLength);
155
+ const summary = (typeof input.summary === "string" ? input.summary : message).replace(/\s+/g, " ").trim().slice(0, maximumTaskSummaryLength);
156
+ if (input.restart === true && task.status === "running") {
157
+ if (!runtime.subagentPort.stopTask) throw new Error("Background agent restart is unavailable in this runtime.");
158
+ await runtime.subagentPort.stopTask(input.taskId);
159
+ task = runtime.runtimeTaskRegistry?.get?.(input.taskId);
160
+ if (!task) throw new Error("The background agent stopped but could not be restored.");
161
+ }
162
+ return await runtime.subagentPort.sendMessage({
163
+ sessionId: task.parentSessionId ?? runtime.getSessionId?.(),
164
+ turnId: task.turnId ?? "tui-task-message",
165
+ parentToolCallId: task.parentToolCallId ?? "tui-task-message",
166
+ to: task.agentId ?? input.taskId,
167
+ summary,
168
+ message,
169
+ workingDirectory: task.workingDirectory ?? runtime.workingDirectory,
170
+ workspaceRoot: task.workspaceRoot ?? runtime.workingDirectory,
171
+ trace: task.traceContext ?? runtime.rootTraceContext
172
+ });
173
+ }
174
+ //#endregion
175
+ //#region src/runtime-background-restore.ts
176
+ const maximumReminderLength = 4e3;
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
+ }));
236
+ }
237
+ async function restore(app, queries) {
238
+ const runtime = app.runtime;
239
+ const registry = runtime?.runtimeTaskRegistry;
240
+ const sessionId = app.sessionId;
241
+ if (!registry?.register || typeof sessionId !== "string" || sessionId === app.$zRestoredBackgroundTasksSession) return;
242
+ app.$zRestoredBackgroundTasksLog = [];
243
+ try {
244
+ const tasks = await restoreSessionChildren(app, sessionId, queries);
245
+ if (app.sessionId !== sessionId || app.runtime !== runtime) return;
246
+ const restored = [];
247
+ for (const task of tasks) {
248
+ if (registry.get?.(task.taskId)) continue;
249
+ registry.register(task);
250
+ restored.push(task);
251
+ }
252
+ app.$zRestoredBackgroundTasksSession = sessionId;
253
+ if (restored.length === 0) return;
254
+ const taskIds = restored.slice(-32).map((task) => `- ${task.taskId} (${task.status})`).join("\n").slice(0, maximumReminderLength);
255
+ runtime?.messageHistory?.addAttachment?.("task_status", `Background agent tasks from this resumed session have been restored and are available again.
256
+ Earlier TaskOutput errors saying "No task found" occurred before restoration and are stale.
257
+ Use TaskOutput to collect results or SendMessage to continue a task. Do not assume these tasks were lost.
258
+ Restored task IDs:\n${taskIds}`);
259
+ app.$zRestoredBackgroundTasksLog = [...app.$zRestoredBackgroundTasksLog ?? [], ...restored].slice(-64);
260
+ } catch {
261
+ if (app.sessionId === sessionId) app.$zRestoredBackgroundTasksSession = void 0;
262
+ }
263
+ }
264
+ const pendingRestores = /* @__PURE__ */ new WeakMap();
265
+ async function restoreTuiBackgroundTasks(app, queries) {
266
+ const pending = pendingRestores.get(app);
267
+ if (pending) {
268
+ await pending;
269
+ return restoreTuiBackgroundTasks(app, queries);
270
+ }
271
+ const operation = restore(app, queries);
272
+ pendingRestores.set(app, operation);
273
+ try {
274
+ await operation;
275
+ } finally {
276
+ pendingRestores.delete(app);
277
+ }
278
+ }
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
90
644
  //#region src/runtime-config-bridge.ts
91
645
  function record(value) {
92
646
  return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
@@ -204,7 +758,13 @@ async function migrateLegacyProviders(options) {
204
758
  }
205
759
  //#endregion
206
760
  exports.assertSessionModelReady = assertSessionModelReady;
761
+ exports.installSqliteWriteRecovery = installSqliteWriteRecovery;
207
762
  exports.mergeDesktopSettings = mergeDesktopSettings;
208
763
  exports.migrateLegacyProviders = migrateLegacyProviders;
209
764
  exports.providerMigrationNeeded = providerMigrationNeeded;
765
+ exports.pruneSqliteUsage = pruneSqliteUsage;
210
766
  exports.readSessionModelState = readSessionModelState;
767
+ exports.readTuiRuntimeProjection = readTuiRuntimeProjection;
768
+ exports.restoreTuiBackgroundTasks = restoreTuiBackgroundTasks;
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-23T02:17:40.060Z",
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": {
@@ -101,6 +101,11 @@
101
101
  }
102
102
  },
103
103
  "runtimePatches": [
104
+ {
105
+ "id": "tui-workflow-reducer",
106
+ "requirement": "optional",
107
+ "status": "applied"
108
+ },
104
109
  {
105
110
  "id": "tui-execution-state",
106
111
  "requirement": "required",
@@ -171,6 +176,11 @@
171
176
  "requirement": "required",
172
177
  "status": "applied"
173
178
  },
179
+ {
180
+ "id": "sqlite-write-recovery",
181
+ "requirement": "required",
182
+ "status": "applied"
183
+ },
174
184
  {
175
185
  "id": "oauth-http-errors",
176
186
  "requirement": "optional",