zcode-app-cli 3.14.3-27 → 3.14.3-28

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/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.3-28",
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",
@@ -87,6 +87,212 @@ function assertSessionModelReady(options) {
87
87
  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
88
  }
89
89
  //#endregion
90
+ //#region src/runtime-tui-bridge.ts
91
+ const maximumTaskMessageLength = 2e4;
92
+ const maximumTaskSummaryLength = 200;
93
+ function taskDetail(task) {
94
+ const running = task.status === "running";
95
+ const kind = task.taskType ?? task.type;
96
+ return {
97
+ taskId: task.taskId,
98
+ taskKind: kind,
99
+ agentId: task.agentId,
100
+ agentType: task.agentType,
101
+ childSessionId: task.childSessionId,
102
+ parentSessionId: task.parentSessionId,
103
+ parentToolCallId: task.parentToolCallId,
104
+ turnId: task.turnId,
105
+ prompt: task.prompt,
106
+ error: running ? null : task.error instanceof Error ? task.error.message : typeof task.error === "string" ? task.error : void 0,
107
+ outputPath: task.outputFile,
108
+ status: task.status,
109
+ description: task.description,
110
+ startedAt: task.startedAt,
111
+ completedAt: running ? null : task.completedAt,
112
+ cancelRequestedAt: running ? null : task.cancelRequestedAt,
113
+ blocked: running ? null : task.blocked,
114
+ blockedReason: running ? null : task.blockedReason,
115
+ cancellable: kind === "local_agent" ? running : task.cancellable
116
+ };
117
+ }
118
+ async function readTuiRuntimeProjection(app, bridge) {
119
+ const executionState = await app.readExecutionState();
120
+ await bridge.$zRestorePersistedBackgroundTasks?.(app);
121
+ const projection = await app.runtime?.getProjection?.();
122
+ if (!projection) return null;
123
+ const details = Object.values(app.runtime?.runtimeTaskRegistry?.all?.() ?? {}).filter((task) => task.isBackgrounded === true).map(taskDetail);
124
+ const tasks = Array.isArray(projection.backgroundTasks) ? projection.backgroundTasks.slice() : [];
125
+ for (const detail of details) {
126
+ const index = tasks.findIndex((existing) => existing.taskId === detail.taskId);
127
+ if (index < 0) tasks.push(detail);
128
+ else tasks[index] = {
129
+ ...tasks[index],
130
+ ...Object.fromEntries(Object.entries(detail).filter(([, value]) => value !== void 0))
131
+ };
132
+ }
133
+ return {
134
+ ...projection,
135
+ ...executionState && typeof executionState === "object" ? executionState : {},
136
+ backgroundTasks: tasks,
137
+ backgroundTaskDetails: details,
138
+ restoredBackgroundTasks: Array.isArray(app.$zRestoredBackgroundTasksLog) ? app.$zRestoredBackgroundTasksLog : []
139
+ };
140
+ }
141
+ async function sendTuiBackgroundTaskMessage(app, bridge, input) {
142
+ await bridge.$zRestorePersistedBackgroundTasks?.(app);
143
+ const runtime = app.runtime;
144
+ let task = runtime?.runtimeTaskRegistry?.get?.(input?.taskId);
145
+ if (!task && typeof app.sessionId === "string") {
146
+ app.$zRestoredBackgroundTasksSession = void 0;
147
+ await bridge.$zRestorePersistedBackgroundTasks?.(app);
148
+ task = runtime?.runtimeTaskRegistry?.get?.(input?.taskId);
149
+ }
150
+ if (!runtime?.subagentPort?.sendMessage) throw new Error("Background agent messaging is unavailable in this runtime.");
151
+ if (!task || (task.type ?? task.taskType) !== "local_agent") throw new Error("The selected task is not a local agent.");
152
+ if (typeof input?.message !== "string" || !input.message.trim()) throw new Error("Enter a message for the background agent.");
153
+ const message = input.message.trim().slice(0, maximumTaskMessageLength);
154
+ const summary = (typeof input.summary === "string" ? input.summary : message).replace(/\s+/g, " ").trim().slice(0, maximumTaskSummaryLength);
155
+ if (input.restart === true && task.status === "running") {
156
+ if (!runtime.subagentPort.stopTask) throw new Error("Background agent restart is unavailable in this runtime.");
157
+ await runtime.subagentPort.stopTask(input.taskId);
158
+ task = runtime.runtimeTaskRegistry?.get?.(input.taskId);
159
+ if (!task) throw new Error("The background agent stopped but could not be restored.");
160
+ }
161
+ return await runtime.subagentPort.sendMessage({
162
+ sessionId: task.parentSessionId ?? runtime.getSessionId?.(),
163
+ turnId: task.turnId ?? "tui-task-message",
164
+ parentToolCallId: task.parentToolCallId ?? "tui-task-message",
165
+ to: task.agentId ?? input.taskId,
166
+ summary,
167
+ message,
168
+ workingDirectory: task.workingDirectory ?? runtime.workingDirectory,
169
+ workspaceRoot: task.workspaceRoot ?? runtime.workingDirectory,
170
+ trace: task.traceContext ?? runtime.rootTraceContext
171
+ });
172
+ }
173
+ //#endregion
174
+ //#region src/runtime-background-restore.ts
175
+ 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
+ };
219
+ }
220
+ async function restore(app) {
221
+ const runtime = app.runtime;
222
+ const registry = runtime?.runtimeTaskRegistry;
223
+ const sessionId = app.sessionId;
224
+ if (!registry?.register || typeof sessionId !== "string" || sessionId === app.$zRestoredBackgroundTasksSession) return;
225
+ app.$zRestoredBackgroundTasksSession = sessionId;
226
+ app.$zRestoredBackgroundTasksLog = [];
227
+ try {
228
+ const messages = await app.loadSessionTranscript?.() ?? [];
229
+ 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
+ }
271
+ }
272
+ if (restored.length === 0) return;
273
+ const taskIds = restored.slice(-32).map((task) => `- ${task.taskId} (${task.status})`).join("\n").slice(0, maximumReminderLength);
274
+ runtime?.messageHistory?.addAttachment?.("task_status", `Background agent tasks from this resumed session have been restored and are available again.
275
+ Earlier TaskOutput errors saying "No task found" occurred before restoration and are stale.
276
+ Use TaskOutput to collect results or SendMessage to continue a task. Do not assume these tasks were lost.
277
+ Restored task IDs:\n${taskIds}`);
278
+ app.$zRestoredBackgroundTasksLog = [...app.$zRestoredBackgroundTasksLog ?? [], ...restored].slice(-64);
279
+ } catch {
280
+ app.$zRestoredBackgroundTasksSession = void 0;
281
+ }
282
+ }
283
+ const pendingRestores = /* @__PURE__ */ new WeakMap();
284
+ async function restoreTuiBackgroundTasks(app) {
285
+ const pending = pendingRestores.get(app);
286
+ if (pending) return pending;
287
+ const operation = restore(app);
288
+ pendingRestores.set(app, operation);
289
+ try {
290
+ await operation;
291
+ } finally {
292
+ pendingRestores.delete(app);
293
+ }
294
+ }
295
+ //#endregion
90
296
  //#region src/runtime-config-bridge.ts
91
297
  function record(value) {
92
298
  return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
@@ -208,3 +414,6 @@ exports.mergeDesktopSettings = mergeDesktopSettings;
208
414
  exports.migrateLegacyProviders = migrateLegacyProviders;
209
415
  exports.providerMigrationNeeded = providerMigrationNeeded;
210
416
  exports.readSessionModelState = readSessionModelState;
417
+ exports.readTuiRuntimeProjection = readTuiRuntimeProjection;
418
+ exports.restoreTuiBackgroundTasks = restoreTuiBackgroundTasks;
419
+ exports.sendTuiBackgroundTaskMessage = sendTuiBackgroundTaskMessage;
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "appVersion": "3.14.3",
3
3
  "cliVersion": "0.16.9",
4
- "extractedAt": "2026-09-23T02:17:40.060Z",
4
+ "extractedAt": "2026-09-24T22:18:54.425Z",
5
5
  "sha512": "VDYryL9bIYjM3uxRNJ8sRw5S5z9LBmRvvW1amQ9wEnhJBMc3Rlb2g8JvxWv04CPn0GgKHEJEZmWmLZuI6EYg1g==",
6
6
  "source": "https://cdn-zcode.z.ai/zcode/electron/releases/3.14.3/linux-x64/ZCode-3.14.3-linux-x64.deb",
7
7
  "runtimeCapabilities": {
@@ -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",
@@ -162650,6 +162650,9 @@ var InputQueue = class {
162650
162650
  pendingResolutions = /* @__PURE__ */ new Map();
162651
162651
  completedTurnIds = /* @__PURE__ */ new Set();
162652
162652
  autoSendEnabled = true;
162653
+ pausedByUser = false;
162654
+ nextId = 1;
162655
+ ids = /* @__PURE__ */ new WeakMap();
162653
162656
  constructor(callbacks) {
162654
162657
  this.callbacks = callbacks;
162655
162658
  }
@@ -162675,6 +162678,43 @@ var InputQueue = class {
162675
162678
  hasFollowUps() {
162676
162679
  return this.queuedFollowUps.length > 0;
162677
162680
  }
162681
+ entries() {
162682
+ return this.queuedFollowUps.map((submission) => {
162683
+ let id = this.ids.get(submission);
162684
+ if (id === void 0) {
162685
+ id = this.nextId++;
162686
+ this.ids.set(submission, id);
162687
+ }
162688
+ return {
162689
+ id,
162690
+ displayInput: submission.displayInput,
162691
+ editable: !submission.pendingInputIds?.length
162692
+ };
162693
+ });
162694
+ }
162695
+ remove(id) {
162696
+ const index = this.queuedFollowUps.findIndex((submission) => this.ids.get(submission) === id);
162697
+ if (index < 0 || this.queuedFollowUps[index]?.pendingInputIds?.length) return void 0;
162698
+ const [submission] = this.queuedFollowUps.splice(index, 1);
162699
+ this.syncView();
162700
+ return submission;
162701
+ }
162702
+ move(id, offset) {
162703
+ const index = this.queuedFollowUps.findIndex((submission) => this.ids.get(submission) === id);
162704
+ const next = index + offset;
162705
+ if (index < 0 || next < 0 || next >= this.queuedFollowUps.length) return false;
162706
+ if (this.queuedFollowUps[index]?.pendingInputIds?.length || this.queuedFollowUps[next]?.pendingInputIds?.length) return false;
162707
+ [this.queuedFollowUps[index], this.queuedFollowUps[next]] = [this.queuedFollowUps[next], this.queuedFollowUps[index]];
162708
+ this.syncView();
162709
+ return true;
162710
+ }
162711
+ get paused() {
162712
+ return this.pausedByUser;
162713
+ }
162714
+ set paused(value) {
162715
+ this.pausedByUser = value;
162716
+ this.syncView();
162717
+ }
162678
162718
  hasPendingSteers() {
162679
162719
  return this.pendingSteers.length > 0;
162680
162720
  }
@@ -162682,7 +162722,7 @@ var InputQueue = class {
162682
162722
  return this.pendingSteers.flatMap(({ admitted, pendingInputId }) => admitted && pendingInputId ? [pendingInputId] : []);
162683
162723
  }
162684
162724
  get autoSend() {
162685
- return this.autoSendEnabled;
162725
+ return this.autoSendEnabled && !this.pausedByUser;
162686
162726
  }
162687
162727
  set autoSend(value) {
162688
162728
  this.autoSendEnabled = value;
@@ -162852,7 +162892,8 @@ var InputQueue = class {
162852
162892
  syncView() {
162853
162893
  this.callbacks.onStateChanged({
162854
162894
  pendingSteers: this.pendingSteers.map(({ submission }) => submission.displayInput),
162855
- queuedInputs: this.queuedFollowUps.map((submission) => submission.displayInput)
162895
+ queuedInputs: this.queuedFollowUps.map((submission) => submission.displayInput),
162896
+ ...this.pausedByUser ? { paused: true } : {}
162856
162897
  });
162857
162898
  }
162858
162899
  };
@@ -162869,12 +162910,14 @@ var QueuedInputView = class {
162869
162910
  theme;
162870
162911
  pendingSteers = [];
162871
162912
  queuedInputs = [];
162913
+ paused = false;
162872
162914
  constructor(theme) {
162873
162915
  this.theme = theme;
162874
162916
  }
162875
162917
  setState(state) {
162876
162918
  this.pendingSteers = state.pendingSteers.map(oneLine$1).filter(Boolean);
162877
162919
  this.queuedInputs = state.queuedInputs.map(oneLine$1).filter(Boolean);
162920
+ this.paused = state.paused === true;
162878
162921
  }
162879
162922
  render(width) {
162880
162923
  if (this.pendingSteers.length === 0 && this.queuedInputs.length === 0) return [];
@@ -162897,7 +162940,7 @@ var QueuedInputView = class {
162897
162940
  const hidden = Math.max(0, this.queuedInputs.length - maxVisibleInputs);
162898
162941
  const visible = this.queuedInputs.slice(-3);
162899
162942
  const summary = `${this.queuedInputs.length} ${this.queuedInputs.length === 1 ? "input" : "inputs"}`;
162900
- lines.push(` ${this.theme.bold("Queued next turn")} ${this.theme.muted(`· ${summary}`)}`, ...visible.map((input) => ` ${this.theme.muted("↳")} ${this.theme.bold(input)}`));
162943
+ lines.push(` ${this.theme.bold(this.paused ? "Queue paused" : "Queued next turn")} ${this.theme.muted(`· ${summary}`)}`, ...visible.map((input) => ` ${this.theme.muted("↳")} ${this.theme.bold(input)}`));
162901
162944
  if (hidden > 0) lines.splice(sectionStart + 1, 0, this.theme.muted(` … ${hidden} earlier`));
162902
162945
  lines.push(firstFitting([
162903
162946
  " Alt+Up / Shift+Left edit last",
@@ -163156,29 +163199,33 @@ function normalizeRuntimeProjection(value) {
163156
163199
  } : void 0
163157
163200
  };
163158
163201
  }
163159
- /** Enrich the stable local projection from persisted messages, without runtime internals. */
163160
- function mergeProjectionContextCache(projection, messages) {
163161
- const usage = projection?.contextUsage;
163162
- if (!projection || !usage) return projection;
163202
+ /** Retain token statistics only; tool output and message bodies stay in storage. */
163203
+ function contextCacheUsage(messages) {
163163
163204
  const trend = extractContextCacheTrend(messages);
163164
- if (trend.wholeTree.requests === 0) return projection;
163205
+ if (trend.wholeTree.requests === 0) return void 0;
163165
163206
  const latest = trend.turns.findLast((turn) => turn.inputTokens !== void 0);
163166
163207
  const summary = trend.wholeTree;
163208
+ return {
163209
+ inputTokens: latest?.inputTokens,
163210
+ cacheReadTokens: latest?.cacheReadTokens,
163211
+ cacheWriteTokens: latest?.cacheWriteTokens,
163212
+ latestHitRate: latest?.hitRate,
163213
+ hitRate: summary.hitRate,
163214
+ hitRateRequestCount: summary.requests,
163215
+ totalInputTokens: summary.inputTokens,
163216
+ totalCacheReadTokens: summary.cacheReadTokens,
163217
+ totalCacheWriteTokens: summary.cacheWriteTokens
163218
+ };
163219
+ }
163220
+ function mergeProjectionContextSummary(projection, cache) {
163221
+ if (!projection?.contextUsage || !cache) return projection;
163167
163222
  return {
163168
163223
  ...projection,
163169
163224
  contextUsage: {
163170
- ...usage,
163225
+ ...projection.contextUsage,
163171
163226
  cache: {
163172
- ...usage.cache,
163173
- inputTokens: latest?.inputTokens ?? usage.cache?.inputTokens,
163174
- cacheReadTokens: latest?.cacheReadTokens ?? usage.cache?.cacheReadTokens,
163175
- cacheWriteTokens: latest?.cacheWriteTokens ?? usage.cache?.cacheWriteTokens,
163176
- latestHitRate: latest?.hitRate ?? usage.cache?.latestHitRate,
163177
- hitRate: summary.hitRate ?? usage.cache?.hitRate,
163178
- hitRateRequestCount: summary.requests,
163179
- totalInputTokens: summary.inputTokens,
163180
- totalCacheReadTokens: summary.cacheReadTokens,
163181
- totalCacheWriteTokens: summary.cacheWriteTokens
163227
+ ...projection.contextUsage.cache,
163228
+ ...Object.fromEntries(Object.entries(cache).filter(([, value]) => value !== void 0))
163182
163229
  }
163183
163230
  }
163184
163231
  };
@@ -163274,6 +163321,172 @@ var RuntimeActivityView = class {
163274
163321
  }
163275
163322
  };
163276
163323
  //#endregion
163324
+ //#region packages/zcode-tui/src/dynamic-workflows.ts
163325
+ const maximumRuns = 20;
163326
+ const maximumBufferedEvents = 2e3;
163327
+ var DynamicWorkflows = class {
163328
+ adapter;
163329
+ state;
163330
+ summaries = [];
163331
+ epoch = 0;
163332
+ loading;
163333
+ buffered = [];
163334
+ watermarks = /* @__PURE__ */ new Map();
163335
+ lastEvents = /* @__PURE__ */ new Map();
163336
+ incomplete = false;
163337
+ error;
163338
+ constructor(adapter) {
163339
+ this.adapter = adapter;
163340
+ }
163341
+ reset() {
163342
+ this.epoch++;
163343
+ this.state = void 0;
163344
+ this.summaries = [];
163345
+ this.loading = void 0;
163346
+ this.buffered = [];
163347
+ this.watermarks.clear();
163348
+ this.lastEvents.clear();
163349
+ this.error = void 0;
163350
+ this.incomplete = false;
163351
+ }
163352
+ runs() {
163353
+ const runs = isRecord(this.state) && Array.isArray(this.state.runs) ? this.state.runs.filter(isRecord) : [];
163354
+ const byId = new Map(runs.map((run) => [run.runId, run]));
163355
+ return [...this.summaries.map((summary) => {
163356
+ const run = byId.get(summary.runId);
163357
+ byId.delete(summary.runId);
163358
+ return run ? {
163359
+ ...run,
163360
+ label: summary.label,
163361
+ updatedAt: summary.updatedAt
163362
+ } : summary;
163363
+ }), ...byId.values()].slice(0, maximumRuns).map((run) => this.incomplete ? {
163364
+ ...run,
163365
+ progressIncomplete: true
163366
+ } : run);
163367
+ }
163368
+ accept(event) {
163369
+ if (!isRecord(event) || typeof event.runId !== "string" || typeof event.eventType !== "string") return false;
163370
+ if (this.loading) {
163371
+ if (this.buffered.length < maximumBufferedEvents) this.buffered.push(event);
163372
+ else {
163373
+ this.incomplete = true;
163374
+ this.error = "Some workflow progress was omitted. Live runs cannot be fully replayed in this process; use /dwf list for runtime status.";
163375
+ }
163376
+ return false;
163377
+ }
163378
+ return this.apply(event);
163379
+ }
163380
+ apply(event) {
163381
+ if (!this.adapter.reduceWorkflowRuns) return false;
163382
+ const id = String(event.runId);
163383
+ const sequence = typeof event.sequence === "number" ? event.sequence : void 0;
163384
+ const watermark = this.watermarks.get(id) ?? -1;
163385
+ const fingerprint = JSON.stringify(event);
163386
+ if (sequence !== void 0 && (sequence < watermark || sequence === watermark && this.lastEvents.get(id) === fingerprint)) return false;
163387
+ try {
163388
+ const state = this.adapter.reduceWorkflowRuns(this.state, event);
163389
+ if (sequence !== void 0) this.watermarks.set(id, sequence);
163390
+ this.lastEvents.set(id, fingerprint);
163391
+ if (!state) return false;
163392
+ this.state = state;
163393
+ if (isRecord(state) && Array.isArray(state.runs)) {
163394
+ const ids = new Set(state.runs.filter(isRecord).map((run) => String(run.runId)));
163395
+ for (const key of this.watermarks.keys()) if (!ids.has(key)) {
163396
+ this.watermarks.delete(key);
163397
+ this.lastEvents.delete(key);
163398
+ }
163399
+ }
163400
+ return true;
163401
+ } catch (error) {
163402
+ this.error = `Workflow progress could not be read: ${error instanceof Error ? error.message : String(error)}`;
163403
+ return false;
163404
+ }
163405
+ }
163406
+ hydrate() {
163407
+ if (this.loading) return this.loading;
163408
+ const epoch = this.epoch;
163409
+ if (!this.incomplete) this.error = void 0;
163410
+ const operation = Promise.resolve().then(async () => {
163411
+ const results = await Promise.allSettled([this.adapter.replayWorkflowRuns?.({ excludeRunIds: /* @__PURE__ */ new Set() }), this.adapter.listWorkflowRuns?.()]);
163412
+ if (epoch !== this.epoch) return;
163413
+ const [replay, summaries] = results;
163414
+ if (replay.status === "fulfilled" && Array.isArray(replay.value)) {
163415
+ for (const event of replay.value) if (isRecord(event)) this.apply(event);
163416
+ }
163417
+ if (summaries.status === "fulfilled" && Array.isArray(summaries.value)) this.summaries = summaries.value.filter((value) => isRecord(value) && typeof value.runId === "string").slice(0, maximumRuns);
163418
+ for (const result of results) if (result.status === "rejected") this.error = `Workflow history could not be loaded: ${result.reason instanceof Error ? result.reason.message : String(result.reason)}. Run /workflows to retry.`;
163419
+ }).finally(() => {
163420
+ if (epoch !== this.epoch) return;
163421
+ this.loading = void 0;
163422
+ for (const event of this.buffered) this.apply(event);
163423
+ this.buffered = [];
163424
+ });
163425
+ this.loading = operation;
163426
+ return operation;
163427
+ }
163428
+ };
163429
+ function safe(value) {
163430
+ return sanitizeTerminalText(typeof value === "string" ? value : "", { preserveSgr: false }).slice(0, 2e3);
163431
+ }
163432
+ function workflowRunDetail(run) {
163433
+ const nodes = Array.isArray(run.nodes) ? run.nodes.filter(isRecord) : void 0;
163434
+ const actors = Array.isArray(run.actors) ? run.actors.filter(isRecord) : [];
163435
+ const artifacts = Array.isArray(run.artifacts) ? run.artifacts.filter(isRecord) : [];
163436
+ const usage = isRecord(run.usage) ? run.usage : void 0;
163437
+ const lines = [safe(run.label) || safe(run.runId), `Status: ${safe(run.status) || "unknown"}${run.stopReason ? ` · ${safe(run.stopReason)}` : ""}`];
163438
+ if (run.progressIncomplete === true) lines.push("Progress is incomplete. Use /dwf list for runtime status.");
163439
+ if (nodes) lines.push(`Steps: ${nodes.filter((node) => node.phase === "settled").length}/${nodes.length} observed steps settled`);
163440
+ if (typeof usage?.spentTokens === "number") lines.push(`Tokens: ${usage.spentTokens.toLocaleString()}`);
163441
+ if (run.resumable === true) lines.push("This run can be resumed.");
163442
+ if (actors.length) lines.push("", "Agents", ...actors.slice(0, 12).map((actor) => `${safe(actor.name) || safe(actor.sessionId) || "Agent"} · ${safe(actor.status)}`));
163443
+ if (artifacts.length) lines.push("", "Artifacts", ...artifacts.slice(0, 12).map((artifact) => safe(artifact.title) || safe(artifact.artifactId) || safe(artifact.id)));
163444
+ if (asString(run.error)) lines.push("", `Error: ${safe(run.error)}`);
163445
+ if (asString(run.resultPreview)) lines.push("", safe(run.resultPreview));
163446
+ return lines.join("\n");
163447
+ }
163448
+ //#endregion
163449
+ //#region packages/zcode-tui/src/runtime-context-cache.ts
163450
+ /** A session-scoped, invalidatable summary of persisted request usage. */
163451
+ var RuntimeContextCache = class {
163452
+ sessionId;
163453
+ revision = 0;
163454
+ loadedRevision = -1;
163455
+ usage;
163456
+ pending;
163457
+ invalidate() {
163458
+ this.revision++;
163459
+ }
163460
+ reset() {
163461
+ this.invalidate();
163462
+ this.usage = void 0;
163463
+ this.loadedRevision = -1;
163464
+ this.pending = void 0;
163465
+ }
163466
+ async read(sessionId, loadMessages) {
163467
+ if (sessionId !== this.sessionId) {
163468
+ this.reset();
163469
+ this.sessionId = sessionId;
163470
+ }
163471
+ if (this.loadedRevision === this.revision) return this.usage;
163472
+ if (this.pending?.revision === this.revision) return this.pending.promise;
163473
+ const revision = this.revision;
163474
+ const promise = Promise.resolve().then(loadMessages).then((messages) => {
163475
+ if (revision !== this.revision) return void 0;
163476
+ this.usage = contextCacheUsage(messages);
163477
+ this.loadedRevision = revision;
163478
+ return this.usage;
163479
+ }).finally(() => {
163480
+ if (this.pending?.revision === revision) this.pending = void 0;
163481
+ });
163482
+ this.pending = {
163483
+ revision,
163484
+ promise
163485
+ };
163486
+ return promise;
163487
+ }
163488
+ };
163489
+ //#endregion
163277
163490
  //#region packages/zcode-tui/src/runtime-poll.ts
163278
163491
  const ACTIVE_RUNTIME_POLL_INTERVAL_MS = 1e3;
163279
163492
  const IDLE_RUNTIME_POLL_INTERVAL_MS = 5e3;
@@ -163290,6 +163503,28 @@ function runtimeRefreshNeeded(event) {
163290
163503
  if (event.type === "part.delta") return false;
163291
163504
  return event.kind !== "text_delta" && event.kind !== "reasoning_delta" && event.kind !== "tool_input_delta";
163292
163505
  }
163506
+ const contextChangeEvents = /* @__PURE__ */ new Set([
163507
+ "model_complete",
163508
+ "model.complete",
163509
+ "turn_complete",
163510
+ "turn.completed",
163511
+ "turn_error",
163512
+ "turn.failed",
163513
+ "session_created",
163514
+ "session_resumed",
163515
+ "session_forked",
163516
+ "session_compacted",
163517
+ "compact_boundary",
163518
+ "rewind_triggered",
163519
+ "rewind.triggered"
163520
+ ]);
163521
+ function runtimeContextRefreshNeeded(event) {
163522
+ return event.type !== void 0 && contextChangeEvents.has(event.type);
163523
+ }
163524
+ /** Polling also notices completed work from runtimes without session events. */
163525
+ function runtimeContextChanged(current, next) {
163526
+ return current?.sessionId !== next?.sessionId || current?.turnCount !== next?.turnCount || current?.totalTokenCount !== next?.totalTokenCount || current?.contextUsage?.used !== next?.contextUsage?.used;
163527
+ }
163293
163528
  //#endregion
163294
163529
  //#region packages/zcode-tui/src/selection-command.ts
163295
163530
  const apiKeyLoginPattern = /^(\/login\s+(?:zai|bigmodel)-coding-plan-api-key)(?:\s+([\s\S]*))?$/iu;
@@ -166065,6 +166300,9 @@ var ZCodeTui = class {
166065
166300
  turnWork = new TurnWorkTracker();
166066
166301
  backgroundCoordinatorMessageIds = /* @__PURE__ */ new Set();
166067
166302
  workflowPanel;
166303
+ dynamicWorkflows;
166304
+ dynamicWorkflowView;
166305
+ selectedDynamicWorkflow;
166068
166306
  workflowView;
166069
166307
  workflowRefreshInFlight = false;
166070
166308
  permissionRequests = new PermissionRequestQueue();
@@ -166099,6 +166337,7 @@ var ZCodeTui = class {
166099
166337
  usageRefreshInFlight = false;
166100
166338
  usageRefreshPending = false;
166101
166339
  runtimeProjection;
166340
+ runtimeContextCache = new RuntimeContextCache();
166102
166341
  todos = [];
166103
166342
  todoGroups = [];
166104
166343
  runtimeRefreshInFlight = false;
@@ -166112,6 +166351,7 @@ var ZCodeTui = class {
166112
166351
  removeStreamErrorGuards;
166113
166352
  constructor(options) {
166114
166353
  this.options = options;
166354
+ this.dynamicWorkflows = new DynamicWorkflows(options);
166115
166355
  this.animateTurnTimer = turnTimerAnimationEnabled();
166116
166356
  this.colorsEnabled = !options.noColor && !process.env.NO_COLOR;
166117
166357
  this.themePreference = themePreference(options.theme);
@@ -166244,6 +166484,7 @@ var ZCodeTui = class {
166244
166484
  if (this.options.subscribeSessionEvents) this.unsubscribeSession = this.options.subscribeSessionEvents((event) => {
166245
166485
  this.onSessionEvent(event);
166246
166486
  }) ?? void 0;
166487
+ this.dynamicWorkflows.hydrate().then(() => this.renderDynamicWorkflow());
166247
166488
  if (this.options.subscribeWorkflowEvents) this.unsubscribeWorkflow = this.options.subscribeWorkflowEvents((event) => {
166248
166489
  this.debugEvent("workflow", event);
166249
166490
  this.refreshWorkflowFromEvent();
@@ -166684,6 +166925,23 @@ var ZCodeTui = class {
166684
166925
  name: "activity",
166685
166926
  description: "Inspect every active tool and open task"
166686
166927
  },
166928
+ {
166929
+ name: "queue",
166930
+ description: "Manage queued drafts",
166931
+ argumentHint: "[pause|resume]"
166932
+ },
166933
+ {
166934
+ name: "edit-message",
166935
+ description: "Restore an earlier question for editing"
166936
+ },
166937
+ {
166938
+ name: "retry",
166939
+ description: "Retry an earlier question from a conversation rewind"
166940
+ },
166941
+ {
166942
+ name: "workflows",
166943
+ description: "Inspect workflow progress, results and recovery"
166944
+ },
166687
166945
  {
166688
166946
  name: "tasks",
166689
166947
  description: "Inspect, message or recover background tasks",
@@ -166808,7 +167066,7 @@ var ZCodeTui = class {
166808
167066
  this.switchModel();
166809
167067
  return { consume: true };
166810
167068
  }
166811
- if (matchesKey(data, "tab") && this.turnAbortController && Boolean(this.editor.getText().trim()) && !this.editor.isShowingAutocomplete()) {
167069
+ if (matchesKey(data, "tab") && (this.turnAbortController || this.inputQueue.paused) && Boolean(this.editor.getText().trim()) && !this.editor.isShowingAutocomplete()) {
166812
167070
  this.queueCurrentEditorInput();
166813
167071
  return { consume: true };
166814
167072
  }
@@ -166896,6 +167154,7 @@ var ZCodeTui = class {
166896
167154
  if (input === "/cls") {
166897
167155
  this.clearTranscriptProjection();
166898
167156
  this.workflowView = void 0;
167157
+ this.dynamicWorkflowView = void 0;
166899
167158
  this.ui.requestRender(true);
166900
167159
  return;
166901
167160
  }
@@ -166928,6 +167187,25 @@ var ZCodeTui = class {
166928
167187
  await this.showActivityDetails();
166929
167188
  return;
166930
167189
  }
167190
+ if (input === "/queue" || input === "/queue list") {
167191
+ await this.manageInputQueue();
167192
+ return;
167193
+ }
167194
+ if (input === "/queue pause" || input === "/queue resume") {
167195
+ this.inputQueue.paused = input === "/queue pause";
167196
+ if (!this.inputQueue.paused) this.inputQueue.resetAutoSend();
167197
+ this.addNotice(this.inputQueue.paused ? "Queue paused. Use /queue resume to continue." : "Queue resumed.", "muted");
167198
+ this.drainInputAfterBackgroundHandoff();
167199
+ return;
167200
+ }
167201
+ if (input === "/edit-message" || input === "/retry") {
167202
+ await this.editOrRetryMessage(input === "/retry");
167203
+ return;
167204
+ }
167205
+ if ((input === "/workflows" || input === "/workflows list") && this.options.listWorkflowRuns) {
167206
+ await this.showDynamicWorkflows();
167207
+ return;
167208
+ }
166931
167209
  if (input === "/tasks" || input === "/tasks list") {
166932
167210
  await this.showBackgroundTasks();
166933
167211
  return;
@@ -167040,7 +167318,7 @@ var ZCodeTui = class {
167040
167318
  });
167041
167319
  return true;
167042
167320
  }
167043
- const attachments = !steering && !input.startsWith("/") ? [...this.pendingAttachments] : [];
167321
+ const attachments = !queuedSubmission && !steering && !input.startsWith("/") ? [...this.pendingAttachments] : [];
167044
167322
  if (steering && !this.options.sendInput) {
167045
167323
  this.inputQueue.queueFollowUp({
167046
167324
  ...submission,
@@ -167323,7 +167601,12 @@ var ZCodeTui = class {
167323
167601
  }
167324
167602
  async handleResult(result, renderResponse = true, settingTarget) {
167325
167603
  if (!isRecord(result)) return;
167604
+ this.runtimeContextCache.invalidate();
167326
167605
  if (result.resetSessionProjection === true) {
167606
+ this.dynamicWorkflows.reset();
167607
+ this.dynamicWorkflowView = void 0;
167608
+ this.selectedDynamicWorkflow = void 0;
167609
+ this.runtimeContextCache.reset();
167327
167610
  this.executionStateRevision++;
167328
167611
  this.clearTranscriptProjection();
167329
167612
  this.workflowView = void 0;
@@ -167373,13 +167656,17 @@ var ZCodeTui = class {
167373
167656
  this.updateMetadata();
167374
167657
  this.ui.requestRender();
167375
167658
  if (this.sessionModelIssue) await this.recoverSessionModel();
167659
+ this.dynamicWorkflows.hydrate().then(() => this.renderDynamicWorkflow());
167376
167660
  }
167661
+ this.scheduleRuntimeRefresh(0);
167377
167662
  }
167378
167663
  onEvent(value, turnEpoch) {
167379
167664
  this.debugEvent("session", value);
167380
167665
  if (turnEpoch !== void 0 && turnEpoch !== this.activeTurnEpoch) return;
167381
167666
  const event = normalizeEvent(value);
167382
167667
  if (!event || this.isForeignSessionEvent(event)) return;
167668
+ if (runtimeContextRefreshNeeded(event)) this.runtimeContextCache.invalidate();
167669
+ if (this.handleDynamicWorkflowEvent(value, event.type)) return;
167383
167670
  const taskScoped = this.backgroundTaskEvents.isTaskScoped(event);
167384
167671
  this.applyBackgroundTaskEvent(event);
167385
167672
  if (!taskScoped && event.kind && toolLifecycleEventKinds.has(event.kind)) this.turnHadWorkActivity = true;
@@ -167523,11 +167810,88 @@ var ZCodeTui = class {
167523
167810
  this.debugEvent("session-subscription", value);
167524
167811
  const event = normalizeEvent(value);
167525
167812
  if (!event || this.isForeignSessionEvent(event)) return;
167813
+ if (runtimeContextRefreshNeeded(event)) this.runtimeContextCache.invalidate();
167814
+ if (this.handleDynamicWorkflowEvent(value, event.type)) return;
167526
167815
  this.applyBackgroundTaskEvent(event);
167527
- this.scheduleRuntimeRefresh();
167816
+ if (runtimeRefreshNeeded(event)) this.scheduleRuntimeRefresh();
167528
167817
  }
167529
167818
  isForeignSessionEvent(event) {
167530
- return Boolean(this.sessionId && event.sessionId && event.sessionId !== this.sessionId);
167819
+ const sessionId = this.options.getMainSessionId?.() ?? this.sessionId;
167820
+ return Boolean(sessionId && event.sessionId && event.sessionId !== sessionId);
167821
+ }
167822
+ handleDynamicWorkflowEvent(value, type) {
167823
+ if (type !== "dynamic_workflow_run_progress" || !isRecord(value)) return false;
167824
+ if (this.dynamicWorkflows.accept(value.payload)) this.renderDynamicWorkflow();
167825
+ return true;
167826
+ }
167827
+ renderDynamicWorkflow() {
167828
+ if (!this.dynamicWorkflowView || !this.selectedDynamicWorkflow) return;
167829
+ const run = this.dynamicWorkflows.runs().find((run) => run.runId === this.selectedDynamicWorkflow);
167830
+ if (run) this.dynamicWorkflowView.setText(workflowRunDetail(run));
167831
+ this.ui.requestRender();
167832
+ }
167833
+ async showDynamicWorkflows() {
167834
+ if (!this.options.listWorkflowRuns) {
167835
+ this.addNotice("Workflow inspection is unavailable in this runtime.", "warning");
167836
+ return;
167837
+ }
167838
+ await this.dynamicWorkflows.hydrate();
167839
+ if (this.dynamicWorkflows.error) this.addNotice(this.dynamicWorkflows.error, "warning");
167840
+ const runs = this.dynamicWorkflows.runs();
167841
+ if (runs.length === 0) {
167842
+ this.addNotice("No workflow runs in this session.", "muted");
167843
+ return;
167844
+ }
167845
+ const choice = await this.showChoice({
167846
+ title: "Workflow runs",
167847
+ prompt: "Select a run to inspect its progress and results.",
167848
+ items: runs.map((run) => ({
167849
+ value: String(run.runId),
167850
+ label: asString(run.label) || String(run.runId),
167851
+ description: [run.status, run.resumable === true ? "resumable" : void 0].filter(Boolean).join(" · ")
167852
+ }))
167853
+ });
167854
+ if (!choice) return;
167855
+ this.selectedDynamicWorkflow = choice.value;
167856
+ const run = this.dynamicWorkflows.runs().find((run) => run.runId === choice.value);
167857
+ if (!run) {
167858
+ this.addNotice("This run is no longer in the current workflow list. Open /workflows again.", "muted");
167859
+ return;
167860
+ }
167861
+ this.dynamicWorkflowView = new Text(workflowRunDetail(run), 1, 0);
167862
+ this.transcript.addBlock(this.dynamicWorkflowView);
167863
+ this.ui.requestRender();
167864
+ const action = await this.showChoice({
167865
+ title: "Workflow actions",
167866
+ prompt: "Progress remains visible in the transcript.",
167867
+ items: [
167868
+ {
167869
+ value: "close",
167870
+ label: "Back to prompt"
167871
+ },
167872
+ ...["pending", "running"].includes(String(run.status)) ? [{
167873
+ value: "cancel",
167874
+ label: "Stop workflow"
167875
+ }] : [],
167876
+ ...run.resumable === true ? [{
167877
+ value: "resume",
167878
+ label: "Resume workflow"
167879
+ }] : []
167880
+ ]
167881
+ });
167882
+ if (!action || action.value === "close") return;
167883
+ if (!/^[A-Za-z0-9_.:-]+$/u.test(choice.value)) {
167884
+ this.addNotice("This workflow ID cannot be passed to the runtime command.", "error");
167885
+ return;
167886
+ }
167887
+ try {
167888
+ const result = await this.options.submitPrompt(`/dwf ${action.value} ${choice.value}`, {});
167889
+ await this.handleResult(result);
167890
+ await this.dynamicWorkflows.hydrate();
167891
+ this.renderDynamicWorkflow();
167892
+ } catch (error) {
167893
+ this.addNotice(error instanceof Error ? error.message : String(error), "error");
167894
+ }
167531
167895
  }
167532
167896
  isBackgroundCoordinatorReasoning(event) {
167533
167897
  if (!event.messageId || !this.backgroundCoordinatorMessageIds.has(event.messageId)) return false;
@@ -168274,10 +168638,147 @@ var ZCodeTui = class {
168274
168638
  queueCurrentEditorInput() {
168275
168639
  const input = this.editor.getText().trim();
168276
168640
  if (!input) return;
168641
+ if (this.pendingAttachments.length > 0) {
168642
+ this.addNotice("Send or remove pending images before queueing a text draft.", "warning");
168643
+ return;
168644
+ }
168277
168645
  this.editor.setText("");
168278
168646
  this.inputQueue.queueFollowUp(protectSubmission(input));
168279
168647
  }
168648
+ async manageInputQueue() {
168649
+ const wasPaused = this.inputQueue.paused;
168650
+ this.inputQueue.paused = true;
168651
+ try {
168652
+ while (true) {
168653
+ const entries = this.inputQueue.entries();
168654
+ if (!entries.length) {
168655
+ this.addNotice("No queued inputs.", "muted");
168656
+ return;
168657
+ }
168658
+ const selected = await this.showChoice({
168659
+ title: "Queued inputs",
168660
+ prompt: "Select a draft. Sending pauses while this panel is open.",
168661
+ items: entries.map((entry) => ({
168662
+ value: String(entry.id),
168663
+ label: entry.displayInput,
168664
+ description: entry.editable ? "Editable draft" : "Accepted by runtime · cannot edit here"
168665
+ }))
168666
+ });
168667
+ if (!selected) return;
168668
+ const entry = entries.find((entry) => String(entry.id) === selected.value);
168669
+ if (!entry?.editable) {
168670
+ this.addNotice("This input is already owned by the runtime.", "warning");
168671
+ continue;
168672
+ }
168673
+ const action = await this.showChoice({
168674
+ title: "Queued draft",
168675
+ prompt: "Choose an action.",
168676
+ items: [
168677
+ {
168678
+ value: "edit",
168679
+ label: "Move to editor"
168680
+ },
168681
+ {
168682
+ value: "up",
168683
+ label: "Move earlier"
168684
+ },
168685
+ {
168686
+ value: "down",
168687
+ label: "Move later"
168688
+ },
168689
+ {
168690
+ value: "delete",
168691
+ label: "Delete draft"
168692
+ },
168693
+ {
168694
+ value: "back",
168695
+ label: "Back"
168696
+ }
168697
+ ]
168698
+ });
168699
+ if (!action || action.value === "back") continue;
168700
+ if (action.value === "edit" && (this.editor.getText().trim() || this.pendingAttachments.length > 0)) {
168701
+ this.addNotice("Save or clear the current draft before editing a queued input.", "warning");
168702
+ return;
168703
+ }
168704
+ if (action.value === "up" || action.value === "down") {
168705
+ if (!this.inputQueue.move(entry.id, action.value === "up" ? -1 : 1)) this.addNotice("The draft cannot move further in that direction.", "muted");
168706
+ } else {
168707
+ const removed = this.inputQueue.remove(entry.id);
168708
+ if (!removed) {
168709
+ this.addNotice("The queued input changed. Select it again.", "warning");
168710
+ continue;
168711
+ }
168712
+ if (action.value === "edit") {
168713
+ this.editor.setText(removed.input);
168714
+ this.focusEditor();
168715
+ return;
168716
+ }
168717
+ }
168718
+ }
168719
+ } finally {
168720
+ this.inputQueue.paused = wasPaused;
168721
+ this.drainInputAfterBackgroundHandoff();
168722
+ }
168723
+ }
168724
+ async editOrRetryMessage(retry) {
168725
+ if (this.activeSubmissions > 0 || this.backgroundTaskEvents.hasActiveHandoffs()) {
168726
+ this.addNotice("Wait for the active turn before changing conversation history.", "warning");
168727
+ return;
168728
+ }
168729
+ if (this.editor.getText().trim() || this.pendingAttachments.length > 0) {
168730
+ this.addNotice("Save or clear the current draft before changing conversation history.", "warning");
168731
+ return;
168732
+ }
168733
+ if (!this.options.loadSessionTranscript) {
168734
+ this.addNotice("Message history is unavailable in this runtime.", "warning");
168735
+ return;
168736
+ }
168737
+ try {
168738
+ const targets = rewindTargets(await this.options.loadSessionTranscript());
168739
+ if (!targets.length) {
168740
+ this.addNotice("No earlier questions to select.", "muted");
168741
+ return;
168742
+ }
168743
+ const selected = await this.showChoice({
168744
+ title: retry ? "Retry a question" : "Edit an earlier question",
168745
+ prompt: "Select the question to return to.",
168746
+ items: targets.map((target) => ({
168747
+ value: target.messageId,
168748
+ label: rewindTargetLabel(target.text)
168749
+ }))
168750
+ });
168751
+ const target = targets.find((target) => target.messageId === selected?.value);
168752
+ if (!target) return;
168753
+ if ((await this.showChoice({
168754
+ title: retry ? "Retry this question?" : "Edit this question?",
168755
+ prompt: "Later conversation turns will be removed. Workspace files stay as they are. " + (retry ? "Only question text will be sent again; original images are not included." : "Only question text is restored; reattach any images before sending."),
168756
+ items: [{
168757
+ value: "cancel",
168758
+ label: "Cancel"
168759
+ }, {
168760
+ value: "confirm",
168761
+ label: retry ? "Rewind and send again" : "Rewind and move to editor"
168762
+ }]
168763
+ }))?.value !== "confirm") return;
168764
+ if (this.activeSubmissions > 0 || this.backgroundTaskEvents.hasActiveHandoffs()) {
168765
+ this.addNotice("The conversation became active. Wait for it to finish and select the question again.", "warning");
168766
+ return;
168767
+ }
168768
+ await this.applyConversationRewind(target, "conversation");
168769
+ if (retry) {
168770
+ this.editor.setText("");
168771
+ await this.submit(target.text);
168772
+ }
168773
+ } catch (error) {
168774
+ this.addNotice(error instanceof Error ? error.message : String(error), "error");
168775
+ }
168776
+ }
168280
168777
  editLatestQueuedFollowUp() {
168778
+ if (this.pendingAttachments.length > 0) {
168779
+ this.addNotice("Send or remove pending images before restoring a queued draft.", "warning");
168780
+ return;
168781
+ }
168281
168782
  const submission = this.inputQueue.editLatestFollowUp();
168282
168783
  if (!submission) return;
168283
168784
  this.editor.setText(submission.input);
@@ -170261,11 +170762,7 @@ var ZCodeTui = class {
170261
170762
  do {
170262
170763
  this.runtimeRefreshPending = false;
170263
170764
  const executionStateRevision = this.executionStateRevision;
170264
- const [projectionResult, todosResult, contextMessagesResult] = await Promise.allSettled([
170265
- this.options.readRuntimeProjection?.(),
170266
- this.options.readTodos?.(),
170267
- this.options.readRuntimeProjection && this.options.loadSessionContextMessages ? this.options.loadSessionContextMessages() : Promise.resolve(void 0)
170268
- ]);
170765
+ const [projectionResult, todosResult] = await Promise.allSettled([this.options.readRuntimeProjection?.(), this.options.readTodos?.()]);
170269
170766
  if (executionStateRevision !== this.executionStateRevision) {
170270
170767
  this.runtimeRefreshPending = true;
170271
170768
  continue;
@@ -170277,7 +170774,13 @@ var ZCodeTui = class {
170277
170774
  };
170278
170775
  if (projectionResult.status === "fulfilled" && projectionResult.value !== void 0) {
170279
170776
  const projection = normalizeRuntimeProjection(projectionResult.value);
170280
- next.projection = contextMessagesResult.status === "fulfilled" && contextMessagesResult.value !== void 0 ? mergeProjectionContextCache(projection, contextMessagesResult.value) ?? next.projection : projection ?? next.projection;
170777
+ if (runtimeContextChanged(this.runtimeProjection, projection)) this.runtimeContextCache.invalidate();
170778
+ const cache = this.options.loadSessionContextMessages ? await this.runtimeContextCache.read(projection?.sessionId ?? this.sessionId, this.options.loadSessionContextMessages).catch(() => void 0) : void 0;
170779
+ if (executionStateRevision !== this.executionStateRevision) {
170780
+ this.runtimeRefreshPending = true;
170781
+ continue;
170782
+ }
170783
+ next.projection = mergeProjectionContextSummary(projection, cache) ?? next.projection;
170281
170784
  if (isRecord(projectionResult.value) && Array.isArray(projectionResult.value.todoGroups)) next.todoGroups = normalizeTodoGroups(projectionResult.value);
170282
170785
  }
170283
170786
  if (todosResult.status === "fulfilled" && todosResult.value !== void 0) next.todos = normalizeTodos(todosResult.value);
package/vendor/zcode.cjs CHANGED
@@ -15414,8 +15414,8 @@ Commands:
15414
15414
  marketplace remove <name> Remove a configured marketplace
15415
15415
  marketplace update [name] Refresh one marketplace, or all when omitted
15416
15416
 
15417
- Scopes: user (default), project. \`zcode plugin\` is an alias of \`zcode plugins\`.`;r(Zei,"runPluginsCommand");r(nrc,"runPluginsListCommand");r(rrc,"runPluginsInstallCommand");r(orc,"runPluginsUpdateCommand");r(irc,"reportInstallOutcome");r(Yei,"runPluginsSetCommand");r(src,"runPluginsDisableCommand");r(arc,"runPluginsUninstallCommand");r(crc,"runPluginsValidateCommand")});function urc(e=process.env){let t=e.ZCODE_STORAGE_DIR?.trim()||(0,dse.join)((0,eti.homedir)(),".zcode");return(0,dse.join)(t,"clipboard")}function tti(e={}){let t=e.platform??process.platform,n=e.maxBytes??lrc,o=e.runCommand??mrc,s=e.tempDirectory??urc(e.processEnv);return async(a={})=>t==="darwin"?await drc({maxBytes:n,runCommand:o,signal:a.abortSignal,tempDirectory:s}):t==="linux"?await prc({maxBytes:n,runCommand:o,signal:a.abortSignal}):t==="win32"?await frc({maxBytes:n,runCommand:o,signal:a.abortSignal,tempDirectory:s}):null}async function drc(e){await(0,M4.mkdir)(e.tempDirectory,{recursive:!0});let t=await(0,M4.mkdtemp)((0,dse.join)(e.tempDirectory,"zcode-clipboard-")),n=(0,dse.join)(t,"clipboard.png");try{return(await e.runCommand("osascript",["-e","set png_data to (the clipboard as \xABclass PNGf\xBB)","-e",`set fp to open for access POSIX file ${hrc(n)} with write permission`,"-e","write png_data to fp","-e","close access fp"],{maxBytes:e.maxBytes,signal:e.signal})).exitCode!==0?null:await nti(n,"image/png",e.maxBytes)}finally{await(0,M4.rm)(t,{force:!0,recursive:!0})}}async function prc(e){let t=[{args:["--type","image/png"],file:"wl-paste",mediaType:"image/png"},{args:["--type","image/jpeg"],file:"wl-paste",mediaType:"image/jpeg"},{args:["--type","image/gif"],file:"wl-paste",mediaType:"image/gif"},{args:["--type","image/webp"],file:"wl-paste",mediaType:"image/webp"},{args:["-selection","clipboard","-t","image/png","-o"],file:"xclip",mediaType:"image/png"},{args:["-selection","clipboard","-t","image/jpeg","-o"],file:"xclip",mediaType:"image/jpeg"},{args:["-selection","clipboard","-t","image/gif","-o"],file:"xclip",mediaType:"image/gif"},{args:["-selection","clipboard","-t","image/webp","-o"],file:"xclip",mediaType:"image/webp"}];for(let n of t){let o=await e.runCommand(n.file,n.args,{maxBytes:e.maxBytes,signal:e.signal}),s=rti(o.stdout,n.mediaType,e.maxBytes);if(o.exitCode===0&&s)return s}return null}async function frc(e){await(0,M4.mkdir)(e.tempDirectory,{recursive:!0});let t=await(0,M4.mkdtemp)((0,dse.join)(e.tempDirectory,"zcode-clipboard-")),n=(0,dse.join)(t,"clipboard.png"),o=["Add-Type -AssemblyName System.Windows.Forms;","$img = Get-Clipboard -Format Image;","if ($null -eq $img) { exit 2 }",`$img.Save(${grc(n)}, [System.Drawing.Imaging.ImageFormat]::Png);`].join(" ");try{return(await e.runCommand("powershell.exe",["-NoProfile","-NonInteractive","-Command",o],{maxBytes:e.maxBytes,signal:e.signal})).exitCode!==0?null:await nti(n,"image/png",e.maxBytes)}finally{await(0,M4.rm)(t,{force:!0,recursive:!0})}}async function nti(e,t,n){let o=await(0,M4.readFile)(e);return rti(o,t,n)}function rti(e,t,n){return e.byteLength===0||e.byteLength>n?null:{dataUrl:`data:${t};base64,${e.toString("base64")}`,mediaType:t,sizeBytes:e.byteLength}}async function mrc(e,t,n){return await new Promise(o=>{let s;try{s=(0,Qei.spawn)(e,t,{signal:n.signal,stdio:["ignore","pipe","ignore"],windowsHide:!0})}catch{o({exitCode:-1,stdout:Buffer.alloc(0)});return}let a=[],l=0,u=!1,f=r(g=>{u||(u=!0,o(g))},"finish");s.stdout?.on("data",g=>{if(l+=g.byteLength,l>n.maxBytes){s.kill();return}a.push(g)}),s.on("error",()=>f({exitCode:-1,stdout:Buffer.alloc(0)})),s.on("close",(g,_)=>{f({exitCode:g,signal:_,stdout:Buffer.concat(a)})})})}function hrc(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function grc(e){return`'${e.replace(/'/g,"''")}'`}var Qei,M4,eti,dse,lrc,oti=Y(()=>{"use strict";Qei=require("node:child_process"),M4=require("node:fs/promises"),eti=require("node:os"),dse=require("node:path"),lrc=20*1024*1024;r(urc,"resolveDefaultClipboardDirectory");r(tti,"createNodeClipboardImageReader");r(drc,"readMacClipboardImage");r(prc,"readLinuxClipboardImage");r(frc,"readWindowsClipboardImage");r(nti,"readImageFile");r(rti,"bufferToClipboardImage");r(mrc,"runCommandBuffer");r(hrc,"appleScriptString");r(grc,"powershellString")});function sti(e={}){let t=e.maxBytes??_rc,n=e.platform??process.platform,o=e.runCommand??Irc;return async s=>{let a=Trc(s,t);if(a.byteLength===0)return;let l=wrc(e.stdout,a),u=await krc({input:s,platform:n,runCommand:o});if(!l&&!u)throw new Error("No text clipboard target accepted the selected text.")}}function wrc(e,t){if(!e)return!1;try{return e.write(`${vrc}${yrc};${t.toString("base64")}${brc}`),!0}catch{return!1}}async function krc(e){for(let t of xrc(e.platform))if((await e.runCommand(t.file,t.args,{input:e.input})).exitCode===0)return!0;return!1}function xrc(e){return e==="darwin"?[{args:[],file:"pbcopy"}]:e==="linux"?[{args:[],file:"wl-copy"},{args:["-selection","clipboard"],file:"xclip"},{args:["--clipboard","--input"],file:"xsel"}]:e==="win32"?[{args:["-NoProfile","-NonInteractive","-Command",Src],file:"powershell.exe"}]:[]}function Trc(e,t){let n=Buffer.from(e,"utf8");if(n.byteLength>t)throw new Error(`Clipboard text exceeds ${t} bytes.`);return n}async function Irc(e,t,n){return await new Promise(o=>{let s;try{s=(0,iti.spawn)(e,t,{stdio:["pipe","ignore","ignore"],windowsHide:!0})}catch{o({exitCode:-1});return}let a=!1,l=r(u=>{a||(a=!0,o(u))},"finish");s.stdin?.on("error",()=>{}),s.stdin?.end(n.input),s.on("error",()=>l({exitCode:-1})),s.on("close",(u,f)=>l({exitCode:u,signal:f}))})}var iti,_rc,yrc,vrc,brc,Src,ati=Y(()=>{"use strict";iti=require("node:child_process"),_rc=1024*1024,yrc="c",vrc="\x1B]52;",brc="\x07",Src="Set-Clipboard -Value ([Console]::In.ReadToEnd())";r(sti,"createNodeClipboardTextWriter");r(wrc,"writeOsc52");r(krc,"writeNativeClipboardText");r(xrc,"nativeClipboardCommands");r(Trc,"assertClipboardTextSize");r(Irc,"runCommandText")});async function BTt(e){let t=e.env??process.env,n=(e.cwd??process.cwd)();return e.listCustomCommands?await e.listCustomCommands({env:t,logger:e.logger,workingDirectory:n}):await(await Qg()).listZCodeCustomCommands({env:t,logger:e.logger,workingDirectory:n})}async function cti(e,t){let n=e.env??process.env,o=(e.cwd??process.cwd)();return e.loadCustomCommand?await e.loadCustomCommand({env:n,logger:e.logger,name:t,workingDirectory:o}):await(await Qg()).loadZCodeCustomCommand({env:n,logger:e.logger,name:t,workingDirectory:o})}async function lti(e){let t=e.env??process.env,n=(e.cwd??process.cwd)();return await(e.listSkills??(await Qg()).listZCodeSkills)({env:t,logger:e.logger,workingDirectory:n})}async function uti(e){let t=e.env??process.env,n=(e.cwd??process.cwd)();return(await(e.listSessions??(await Qg()).listZCodeSessions)({directory:n,env:t,limit:50})).map(a=>({directory:a.directory,id:a.id,parentId:a.parentID,title:a.title,updatedAt:a.time.updated}))}async function dti(e){try{return await e.getSessionMetadata?.()??{}}catch(t){if(Crc(t))throw t;return{}}}function Crc(e){return e instanceof Error?e.name==="SqliteSessionMigrationError":!1}var j2n=Y(()=>{"use strict";b9();r(BTt,"listCustomCommandsForTui");r(cti,"loadCustomCommandForTui");r(lti,"listSkillsForTui");r(uti,"listSessionsForTui");r(dti,"loadInitialTuiSessionMetadata");r(Crc,"isStartupGateError")});function pti(e){let t=new Set,n,o=r(()=>{n?.(),n=void 0},"detach"),s=r(()=>{if(o(),t.size===0)return;n=e.readSubscriber(e.currentRuntime())?.({onSessionEvent:r(l=>{for(let u of t)u(l)},"onSessionEvent")})},"reattach");return{addSink:r(a=>(t.add(a),t.size===1&&s(),()=>{t.delete(a),t.size===0&&o()}),"addSink"),reattach:s,detach:o,isAttached:r(()=>n!==void 0,"isAttached")}}var fti=Y(()=>{"use strict";r(pti,"createTuiSessionEventRelay")});var mti,hti=Y(()=>{"use strict";TTt();mti=r((e,t)=>{const $zTuiBridge=e,$zTuiGetApp=t;$zTuiBridge.loadSessionTranscript=async()=>await(await $zTuiGetApp()).loadSessionTranscript?.()??[],$zTuiBridge.loadSessionContextMessages=async()=>await(await $zTuiGetApp()).loadSessionContextMessages?.()??[],$zTuiBridge.readGoal=async()=>await(await $zTuiGetApp()).readTarget?.()??null,$zTuiBridge.readTodos=async()=>await(await $zTuiGetApp()).readTodos?.()??[],$zTuiBridge.readRuntimeProjection=async()=>{let $zRuntimeProjectionBridge=await $zTuiGetApp();let $zExecutionState=await $zRuntimeProjectionBridge.readExecutionState();await $zTuiBridge.$zRestorePersistedBackgroundTasks?.($zRuntimeProjectionBridge);let t=await $zRuntimeProjectionBridge.runtime?.getProjection?.();if(!t)return null;let r=Object.values($zRuntimeProjectionBridge.runtime?.runtimeTaskRegistry?.all?.()??{}).filter(o=>o.isBackgrounded===!0).map(o=>({taskId:o.taskId,taskKind:o.taskType??o.type,agentId:o.agentId,agentType:o.agentType,childSessionId:o.childSessionId,parentSessionId:o.parentSessionId,parentToolCallId:o.parentToolCallId,turnId:o.turnId,prompt:o.prompt,error:o.status==="running"?null:o.error instanceof Error?o.error.message:typeof o.error==="string"?o.error:void 0,outputPath:o.outputFile,status:o.status,description:o.description,startedAt:o.startedAt,completedAt:o.status==="running"?null:o.completedAt,cancelRequestedAt:o.status==="running"?null:o.cancelRequestedAt,blocked:o.status==="running"?null:o.blocked,blockedReason:o.status==="running"?null:o.blockedReason,cancellable:(o.taskType??o.type)==="local_agent"?o.status==="running":o.cancellable}));let s=Array.isArray(t.backgroundTasks)?t.backgroundTasks.slice():[];for(let $zDetail of r){let $zIndex=s.findIndex($zExisting=>$zExisting.taskId===$zDetail.taskId);if($zIndex<0)s.push($zDetail);else s[$zIndex]={...s[$zIndex],...Object.fromEntries(Object.entries($zDetail).filter(([,v])=>v!==void 0))}}return{...t,...$zExecutionState,backgroundTasks:s,backgroundTaskDetails:r,restoredBackgroundTasks:Array.isArray($zRuntimeProjectionBridge.$zRestoredBackgroundTasksLog)?$zRuntimeProjectionBridge.$zRestoredBackgroundTasksLog:[]}},$zTuiBridge.$zRestorePersistedBackgroundTasks=async $zApp=>{let $zRuntime=$zApp?.runtime,$zRegistry=$zRuntime?.runtimeTaskRegistry;if(!$zRegistry?.register||typeof $zApp?.sessionId!="string"||$zApp.sessionId===$zApp.$zRestoredBackgroundTasksSession)return;$zApp.$zRestoredBackgroundTasksSession=$zApp.sessionId,$zApp.$zRestoredBackgroundTasksLog=[];try{let $zMessages=await $zApp.loadSessionTranscript?.()??[],$zRestored=[];for(let $zMessage of $zMessages){let $zParts=Array.isArray($zMessage?.parts)?$zMessage.parts:[];for(let $zPart of $zParts){if($zPart?.type!=="tool")continue;let $zToolName=typeof $zPart.toolName==="string"?$zPart.toolName:typeof $zPart.tool==="string"?$zPart.tool:"";$zToolName=$zToolName.trim().toLowerCase();if($zToolName!=="agent"&&$zToolName!=="subagent"&&$zToolName!=="task")continue;let $zInput=$zPart.input??$zPart.state?.input,$zOutput=typeof $zPart.output==="string"?$zPart.output:$zPart.state?.output;if(typeof $zOutput!=="string"||$zOutput.trim().length===0)continue;let $zSpawn;try{$zSpawn=JSON.parse($zOutput)}catch{}if(!$zSpawn||typeof $zSpawn!=="object"||Array.isArray($zSpawn)){if(!$zOutput.includes("Async agent launched successfully."))continue;let $zAgentId=/(?:^|\n)agentId:\s*([^\s(]+)/u.exec($zOutput)?.[1],$zOutputFile=/(?:^|\n)output_file:\s*([^\r\n]+)/u.exec($zOutput)?.[1]?.trim();if(typeof $zAgentId!=="string"||$zAgentId.length===0)continue;$zSpawn={status:"async_launched",agentId:$zAgentId,agentType:typeof $zInput?.subagent_type==="string"&&$zInput.subagent_type.length>0?$zInput.subagent_type:typeof $zInput?.agentType==="string"&&$zInput.agentType.length>0?$zInput.agentType:void 0,childSessionId:"sess_subagent_"+$zAgentId,description:typeof $zInput?.description==="string"&&$zInput.description.length>0?$zInput.description:void 0,prompt:typeof $zInput?.prompt==="string"&&$zInput.prompt.length>0?$zInput.prompt:void 0,...$zOutputFile?{outputFile:$zOutputFile}:{}}}if(($zSpawn.status!=="async_launched"&&$zSpawn.status!=="backgrounded")||typeof $zSpawn.agentId!=="string"||$zSpawn.agentId.length===0)continue;let $zMetadata;if(typeof $zSpawn.outputFile==="string"&&$zSpawn.outputFile.length>0)try{let $zBuiltin=process.getBuiltinModule;if(typeof $zBuiltin==="function"){let $zFs=$zBuiltin.call(process,"node:fs"),$zPath=$zBuiltin.call(process,"node:path");$zMetadata=JSON.parse($zFs.readFileSync($zPath.join($zPath.dirname($zSpawn.outputFile),"metadata.json"),"utf8"))}}catch{}if($zMetadata&&typeof $zMetadata==="object"&&!Array.isArray($zMetadata)&&(typeof $zMetadata.agentId!=="string"||$zMetadata.agentId===$zSpawn.agentId)&&(typeof $zMetadata.parentSessionId!=="string"||$zMetadata.parentSessionId===$zApp.sessionId))$zSpawn={...$zSpawn,agentType:typeof $zMetadata.profileId==="string"&&$zMetadata.profileId.length>0?$zMetadata.profileId:$zSpawn.agentType,childSessionId:typeof $zMetadata.childSessionId==="string"&&$zMetadata.childSessionId.length>0?$zMetadata.childSessionId:$zSpawn.childSessionId,description:typeof $zMetadata.description==="string"&&$zMetadata.description.length>0?$zMetadata.description:$zSpawn.description,outputFile:typeof $zMetadata.outputFile==="string"&&$zMetadata.outputFile.length>0?$zMetadata.outputFile:$zSpawn.outputFile,prompt:typeof $zMetadata.prompt==="string"&&$zMetadata.prompt.length>0?$zMetadata.prompt:$zSpawn.prompt,error:typeof $zMetadata.error==="string"&&$zMetadata.error.length>0?$zMetadata.error:$zSpawn.error};if(typeof $zSpawn.childSessionId!=="string"||$zSpawn.childSessionId.length===0)$zSpawn.childSessionId="sess_subagent_"+$zSpawn.agentId;if($zRegistry.get?.($zSpawn.agentId))continue;let $zStatus="stopped";if($zMetadata?.status==="completed")$zStatus="completed";else if($zMetadata?.status==="failed")$zStatus="failed";let $zTask={taskId:$zSpawn.agentId,agentId:$zSpawn.agentId,agentType:typeof $zSpawn.agentType==="string"&&$zSpawn.agentType.length>0?$zSpawn.agentType:"general-purpose",childSessionId:$zSpawn.childSessionId,description:typeof $zSpawn.description==="string"&&$zSpawn.description.length>0?$zSpawn.description:void 0,error:typeof $zSpawn.error==="string"&&$zSpawn.error.length>0?$zSpawn.error:void 0,isBackgrounded:!0,outputFile:typeof $zSpawn.outputFile==="string"&&$zSpawn.outputFile.length>0?$zSpawn.outputFile:void 0,parentToolCallId:typeof $zPart.toolCallId==="string"&&$zPart.toolCallId.length>0?$zPart.toolCallId:typeof $zPart.callID==="string"&&$zPart.callID.length>0?$zPart.callID:void 0,parentSessionId:$zApp.sessionId,prompt:typeof $zSpawn.prompt==="string"&&$zSpawn.prompt.length>0?$zSpawn.prompt:void 0,startedAt:$zPart.state?.time?.start,status:$zStatus,taskType:"local_agent",type:"local_agent"};$zRegistry.register($zTask),$zRestored.push($zTask)}}if($zRestored.length>0){let $zTaskIds=$zRestored.slice(-32).map($zTask=>"- "+$zTask.taskId+" ("+$zTask.status+")").join("\n").slice(0,4e3);$zRuntime?.messageHistory?.addAttachment?.("task_status","Background agent tasks from this resumed session have been restored and are available again.\nEarlier TaskOutput errors saying \"No task found\" occurred before restoration and are stale.\nUse TaskOutput to collect results or SendMessage to continue a task. Do not assume these tasks were lost.\nRestored task IDs:\n"+$zTaskIds),$zApp.$zRestoredBackgroundTasksLog=[...($zApp.$zRestoredBackgroundTasksLog??[]),...$zRestored].slice(-64)}}catch{$zApp.$zRestoredBackgroundTasksSession=void 0}},$zTuiBridge.readSessionUsage=async()=>await(await $zTuiGetApp()).readSessionUsage?.()??null,$zTuiBridge.cancelBackgroundTask=async e=>await(await $zTuiGetApp()).cancelBackgroundTask?.(e)??null,$zTuiBridge.previewFileRewind=async e=>{let t=await $zTuiGetApp();return await t.runtime?.previewWorkspaceFileRewind?.({targetMessageIds:e})??null},$zTuiBridge.applyFileRewind=async e=>{let t=await $zTuiGetApp();return await t.runtime?.applyWorkspaceFileRewind?.({targetMessageIds:e})??null},$zTuiBridge.setCustomSessionTitle=async e=>{let t=await $zTuiGetApp();let r=t.runtime?.setCustomSessionTitle?.bind(t.runtime)??t.setCustomSessionTitle?.bind(t);if(!r)throw new Error("Session renaming is unavailable in this runtime.");return await r({title:e.title,traceContext:e.traceContext??t.runtime?.rootTraceContext})},$zTuiBridge.readCustomSessionTitle=async()=>{let t=await $zTuiGetApp(),o=t.sessionStore??t.runtime?.sessionStore,r=await o?.getSession?.(t.sessionId);return r?.titleSource==="custom"&&typeof r.title==="string"?r.title:void 0},$zTuiBridge.setMode=async e=>{return await(await $zTuiGetApp()).setMode(e)},$zTuiBridge.readExecutionState=async()=>await(await $zTuiGetApp()).readExecutionState(),$zTuiBridge.setPlanEnabled=async e=>await(await $zTuiGetApp()).setPlanEnabled(e),$zTuiBridge.setTransientModel=async e=>{if(e==="main"){e=await $zTuiBridge.readDefaultModel();if(!e)throw new Error("No default model is configured.")}let t=await $zTuiGetApp(),r=await t.setModel(e);return{...r,thoughtLevel:t.getThoughtLevel(),effortOptions:t.listThoughtLevels()}},$zTuiBridge.readSessionModel=async()=>{let $zSessionModelApp=await $zTuiGetApp(),s=await $zSessionModelApp.readSessionModelState();if(s?.selection&&!s.issue)await $zSessionModelApp.setModel(s.selection,{transient:!0});return s},$zTuiBridge.sendBackgroundTaskMessage=async e=>{let t=await $zTuiGetApp();await $zTuiBridge.$zRestorePersistedBackgroundTasks?.(t);let r=t.runtime,o=r?.runtimeTaskRegistry?.get?.(e?.taskId);if(!o&&typeof t.sessionId==="string"){t.$zRestoredBackgroundTasksSession=void 0;await $zTuiBridge.$zRestorePersistedBackgroundTasks?.(t);o=r?.runtimeTaskRegistry?.get?.(e?.taskId)}if(!r?.subagentPort?.sendMessage)throw new Error("Background agent messaging is unavailable in this runtime.");if(!o||(o.type??o.taskType)!=="local_agent")throw new Error("The selected task is not a local agent.");if(typeof e?.message!=="string"||!e.message.trim())throw new Error("Enter a message for the background agent.");let n=e.message.trim().slice(0,2e4),i=(typeof e.summary==="string"?e.summary:n).replace(/\s+/g," ").trim().slice(0,200);if(e?.restart===!0&&o.status==="running"){if(!r.subagentPort.stopTask)throw new Error("Background agent restart is unavailable in this runtime.");await r.subagentPort.stopTask(e.taskId),o=r.runtimeTaskRegistry?.get?.(e.taskId);if(!o)throw new Error("The background agent stopped but could not be restored.")}return await r.subagentPort.sendMessage({sessionId:o.parentSessionId??r.getSessionId?.(),turnId:o.turnId??"tui-task-message",parentToolCallId:o.parentToolCallId??"tui-task-message",to:o.agentId??e.taskId,summary:i,message:n,workingDirectory:o.workingDirectory??r.workingDirectory,workspaceRoot:o.workspaceRoot??r.workingDirectory,trace:o.traceContext??r.rootTraceContext})},$zTuiBridge.interruptTurn=async e=>{let t=await $zTuiGetApp(),r=e?.reservationId??"tui-steer-interrupt",o=(Array.isArray(e?.pendingInputIds)?e.pendingInputIds:[]).filter(Boolean),n=[],i=async()=>{for(let a of n)await t.releaseQueueItemReservation?.(a,r);n=[]};try{if(t.reserveQueueItem&&t.releaseQueueItemReservation)for(let a of o)if(await t.reserveQueueItem(a,r))n.push(a);else{await i();break}let a=t.runtime?.stopActiveForegroundExecution?.({preserveQueueAutoDrainOnCancel:o.length>0&&n.length===o.length,reason:e?.reason??"TUI steer interrupt"})??{kind:"unsupported"};if(a.kind==="stopped"&&e?.waitForIdle===!0&&t.runtime?.getActiveForegroundExecutionId){let u=Date.now()+5e3;for(;t.runtime.getActiveForegroundExecutionId()!==void 0;){if(Date.now()>=u)throw new Error("Timed out waiting for background result processing to stop.");await new Promise(l=>setTimeout(l,25))}}return a.kind!=="stopped"&&await i(),a}catch(a){await i();throw a}},$zTuiBridge.promoteQueuedInput=async(e,t,r)=>{let o=await $zTuiGetApp(),n=r?.pendingInputReservationId??r?.queryId??r?.inputId??"tui-promotion",i=(Array.isArray(t)?t:[t]).filter(Boolean);if(i.length===0||!o.reserveQueueItem||!o.markQueueItemPromoting||!o.releaseQueueItemReservation||!o.removeQueueItem)return $zTuiBridge.sendInput(e,{...r,delivery:"start_turn"});let a=[],u=!1;try{for(let l of i){if(await o.markQueueItemPromoting(l,n)){a.push(l);continue}if(!await o.reserveQueueItem(l,n))throw new Error("TUI queued input is already reserved: "+l);a.push(l);if(!await o.markQueueItemPromoting(l,n))throw new Error("TUI queued input promotion failed: "+l)}let c=await $zTuiBridge.sendInput(e,{...r,delivery:"start_turn"});if(c?.kind==="rejected")return c;u=!0;for(let l of a)if(!await o.removeQueueItem(l,{reason:"promoted",reservationId:n}))throw new Error("TUI queued input promotion commit failed: "+l);return c}finally{if(!u)for(let l of a)await o.releaseQueueItemReservation(l,n)}},$zTuiBridge.$zSendInputWithoutBackgroundRestore=$zTuiBridge.sendInput,$zTuiBridge.sendInput=async(...$zArgs)=>{let $zApp=await $zTuiGetApp();await $zTuiBridge.$zRestorePersistedBackgroundTasks?.($zApp);return await $zTuiBridge.$zSendInputWithoutBackgroundRestore.apply($zTuiBridge,$zArgs)},e.recallPreviousInput=async n=>await(await t()).recallPreviousInputHistory?.(n)??null,e.getSessionMetadata=async()=>{let n=await t();return{locale:n.getLocale?.(),model:n.getModel?.(),theme:n.getTheme?.(),thoughtLevel:n.getThoughtLevel?.()}},e.reloadModelOptions=async()=>await(await t()).reloadModels(),e.readDefaultModel=async()=>{await t();let $zSelection=await(await e.$zReadProviderRegistryRuntime()).modelSelectionConfigRepository.read();return $zSelection?$zSelection.providerId+"/"+$zSelection.modelId:void 0},e.setDefaultModel=async $zModel=>{let $zApp=await t(),$zIndex=$zModel.indexOf("/"),$zSelection={providerId:$zModel.slice(0,$zIndex),modelId:$zModel.slice($zIndex+1)};if($zIndex<=0||!$zApp.getModelOption($zSelection))throw new Error("Unknown default model: "+$zModel);await(await e.$zReadProviderRegistryRuntime()).modelSelectionConfigRepository.saveConfiguredDefault($zSelection);return await e.setTransientModel($zModel)},e.listModelOptions=async()=>(await t()).listModels?.()??[],e.listEffortOptions=async()=>{let n=await t();return await j3e(n)??[]},e.listMcpServers=async()=>(await t()).listMcpServers?.()??{},e.listWorkflowRuns=async()=>await(await t()).listDynamicWorkflowRuns?.({})??[],e.replayWorkflowRuns=async n=>await(await t()).replayDynamicWorkflowRuns?.(n)??[]},"attachTuiAppQueries")});async function _ti(e,t,n,o){let s=e.env??process.env,a=(e.cwd??process.cwd)(),l=(e.loadDotenv??rA)({cwd:a,env:s});if(l.error)throw new Error(`Failed to load environment file: ${l.path}`,{cause:l.error});let u=await OTt(n,a,s,e),f=e.createZCodeApp?void 0:await Qg(),g=e.createZCodeApp??f?.createZCodeApp;if(!g)throw new Error("ZCode app factory is unavailable.");let _=e.prepareZCodeTelemetryEnv??f?.prepareZCodeTelemetryEnv;_&&(o.shutdownTelemetry=e.shutdownZCodeTelemetry??f?.shutdownZCodeTelemetry);let b=_?await _(s,{cliVersion:t,productVersion:s.ZCODE_APP_VERSION}):s,w=e.startProcessProviderRegistryRuntime??f?.startProcessProviderRegistryRuntime;if(!w)throw new Error("Provider Registry runtime is unavailable.");o.providerRegistryRuntimePromise??=w(b,e.skipUserConfig?{}:{standalone:{...gPe(),...e.userConfigPath?{legacyCliUserConfigFilePath:e.userConfigPath}:{}}});let T=await o.providerRegistryRuntimePromise,I=T?.modelSelectionConfigRepository?await T.modelSelectionConfigRepository.read():T?.configuredDefaultModelSelection,E=e.createProviderEndpointRoutingPort??f?.createDefaultProviderEndpointRoutingPort;return o.providerEndpointRoutingPort??=E?.({appVersion:t,env:s,projectConfigPath:e.projectConfigPath,skipUserConfig:e.skipUserConfig,userConfigPath:e.userConfigPath,workingDirectory:a}),{appEnv:b,configuredDefaultModelSelection:I,createAppFactory:g,providerRegistryRuntime:T,sessionId:u,workingDirectory:a}}var gti,yti=Y(()=>{"use strict";b9();jQ();NXe();A2n();gti=r(()=>({providerEndpointRoutingPort:void 0,providerRegistryRuntimePromise:void 0,shutdownTelemetry:void 0}),"createTuiProcessRuntimeState");r(_ti,"prepareTuiAppRuntime")});async function vti(e,t){let n=e.env??process.env,o=(e.cwd??process.cwd)(),s=(e.loadDotenv??rA)({cwd:o,env:n});if(s.error)throw new Error(`Failed to load environment file: ${s.path}`,{cause:s.error});return await(e.loginZCodeCli??(await Qg()).loginZCodeCli)({abortSignal:t?.abortSignal,env:n,onAuthorizeUrl:t?.onAuthorizeUrl})}async function bti(e,t){let n=e.env??process.env,o=(e.cwd??process.cwd)(),s=(e.loadDotenv??rA)({cwd:o,env:n});if(s.error)throw new Error(`Failed to load environment file: ${s.path}`,{cause:s.error});return await(e.loginBigmodelCodingPlan??(await Qg()).loginBigmodelCodingPlan)({abortSignal:t?.abortSignal,env:n,onAuthorizeUrl:t?.onAuthorizeUrl})}async function Sti(e,t){return await(e.configureCodingPlanApiKey??(await Qg()).configureCodingPlanApiKey)({apiKey:t.apiKey,env:e.env??process.env,providerId:t.providerId})}async function wti(e){let t=e.env??process.env,n=(e.cwd??process.cwd)(),o=(e.loadDotenv??rA)({cwd:n,env:t});if(o.error)throw new Error(`Failed to load environment file: ${o.path}`,{cause:o.error});return await(e.logoutZCodeCli??(await Qg()).logoutZCodeCli)({env:t})}var kti=Y(()=>{"use strict";b9();jQ();r(vti,"loginForTui");r(bti,"loginBigmodelForTui");r(Sti,"configureApiKeyForTui");r(wti,"logoutForTui")});var xti,Tti,XK,B2n=Y(()=>{"use strict";xti={},Tti=r(e=>({current:e,override:e}),"createCliModeState"),XK=r(e=>e.current??e.override??"build","currentCliMode")});function U2n(e,t,n){return{kind:"started_turn",result:{...e,locale:e.locale??t.getLocale?.(),mode:n,model:e.model??t.getModel?.(),theme:e.theme??t.getTheme?.(),thoughtLevel:e.thoughtLevel??t.getThoughtLevel?.()}}}var Iti=Y(()=>{"use strict";r(U2n,"withTuiMetadata")});function Cti(e,t,n,o={continueSession:!1},s,a,l=Myt,u,f=!1,g,_){let b,w=s,T=gti(),I,E=new WeakMap,R=new WeakMap,L,U=Math.max(1,Math.trunc(e.shutdownCleanupTimeoutMs??nGe)),B={requestPermission:r(async(Pe,Tt)=>{let Ye=L;return Ye?await Ye(Pe,Tt):{decision:"deny",reason:`No interactive approval handler configured for ${Pe.toolName}`,resolvedAt:new Date}},"requestPermission")},z=r(async(Pe=b)=>{if(!Pe)return;let Tt=Pe,Ye=E.get(Tt);Ye||(Ye=(async()=>{await FL(async()=>Pe.close?.(),U),await FL(async()=>R.get(Tt)?.close(),U)})(),E.set(Tt,Ye)),await Ye},"closeApp"),$=pti({currentRuntime:r(()=>b?.runtime,"currentRuntime"),readSubscriber:RTt}),J=r(async Pe=>{let Tt=b,Ye=await Pe();return b=Ye,Tt&&Tt!==Ye&&await z(Tt),$.reattach(),t.current=b.getMode?.()??XK(t),b},"replaceApp"),q=r(async Pe=>{if(I)throw new Error("TUI prompt handler is closed");let{appEnv:Tt,configuredDefaultModelSelection:Ye,createAppFactory:Fe,providerRegistryRuntime:St,sessionId:kt,workingDirectory:st}=await _ti(e,n,Pe,T),$e=T.providerEndpointRoutingPort,jt=ATt({browserExecutable:_,browserUse:g},e),Je;try{Je=await Fe({browserControlPort:jt?.browserControlPort,env:Tt,projectConfigPath:e.projectConfigPath,...$e?{providerEndpointRoutingPort:$e}:{},providerRegistry:St.runtime.registryService,configuredDefaultModelSelection:Ye,...St.providerRuntimeHeadersPort?{providerRuntimeHeadersPort:St.providerRuntimeHeadersPort}:{},resume:kt!==void 0,runtimeConfig:{...t.override?{mode:t.override}:{},...u?{toolDisallowlist:u}:{},...f?{midConversationSystem:{mode:"force"}}:{},modelStreaming:"on",titleGeneration:xti,workingDirectory:st},permissionBroker:B,sessionId:kt,skipUserConfig:e.skipUserConfig,uiDetectedLocale:a,uiLocale:w,userConfigPath:e.userConfigPath,version:n})}catch(Xe){throw await FL(async()=>jt?.close(),U),Xe}if(jt&&R.set(Je,jt),I)throw await z(Je),new Error("TUI prompt handler is closed");return t.current=Je.getMode?.()??t.override??t.current??"build",Je},"createApp"),ie=r(async()=>(b??=await q(o),t.current=b.getMode?.()??XK(t),b),"getApp"),ae=r(async Pe=>await J(async()=>await q(Pe?{continueSession:!1,resumeSessionId:Pe}:{continueSession:!0})),"resumeApp"),Ce=r(async()=>await J(async()=>await q({continueSession:!1})),"newApp"),pe=r(async Pe=>{if(t.override=Pe,b){let Tt=b;if(Tt.setMode){let Ye=await Tt.setMode(Pe);return t.current=Ye.mode,Ye.mode}Tt.runtime.updateConfig({mode:Pe})}return t.current=Pe,Pe},"setCliMode"),ze=$3e({forkApp:r(async Pe=>{let Ye=await(await ie()).forkFromCheckpoint?.({targetCheckpointId:Pe});if(!Ye)throw new Error("Forking is not available in this client.");return await J(async()=>await q({continueSession:!1,resumeSessionId:Ye.forkedSessionId})),{copiedMessageCount:Ye.copiedMessageCount,forkedSessionId:Ye.forkedSessionId,response:`${Ye.response}
15418
- Switched to forked session ${Ye.forkedSessionId}.`,restoredFileCount:Ye.restoredFileCount??Ye.restoredFiles?.length??0}},"forkApp"),getApp:ie,getMode:r(()=>XK(t),"getMode"),getLocale:r(()=>b?.getLocale?.()??YRn(w,a)??l,"getLocale"),hasConfiguredCodingPlanAccess:k2n(e),listCustomCommands:r(()=>BTt(e),"listCustomCommands"),listSessions:r(()=>uti(e),"listSessions"),listSkills:r(()=>lti(e),"listSkills"),configureApiKey:r(Pe=>Sti(e,Pe),"configureApiKey"),login:r(Pe=>vti(e,Pe),"login"),loginBigmodel:r(Pe=>bti(e,Pe),"loginBigmodel"),loadCustomCommand:r(Pe=>cti(e,Pe),"loadCustomCommand"),newApp:Ce,recordInputHistory:r(async(Pe,Tt)=>{await b?.recordInputHistory?.(Pe,Tt)},"recordInputHistory"),resumeApp:ae,logout:r(()=>wti(e),"logout"),setLocale:r(async Pe=>{if(b?.setLocale){let Ye=await b.setLocale(Pe);return w=Pe,Ye}return w=Pe,{configPath:(await yOe(e.userConfigPath??U7(),Pe)).path,locale:YRn(Pe,a)??"en-US",requestedLocale:Pe}},"setLocale"),setMode:pe}),rt=r(async(Pe,Tt)=>{let Ye=L;L=Tt.requestPermission;try{return await ze(Pe,Tt)}finally{L=Ye}},"submitPrompt");return rt.setMode=async Pe=>({mode:await pe(Pe)}),rt.sendInput=async(Pe,Tt)=>{let Ye=L;L=Tt?.requestPermission;try{let Fe=await ie();if(Fe.sendInput){let St=await Fe.sendInput(Pe,Tt);return St.kind!=="started_turn"?St:U2n(await(St.result??St.completion),Fe,XK(t))}return U2n(await Fe.submitPrompt(Pe,Tt),Fe,XK(t))}finally{L=Ye}},rt.listSkills=async()=>await lti(e),rt.$zReadProviderRegistryRuntime=()=>T.providerRegistryRuntimePromise,mti(rt,ie),rt.subscribeSessionEvents=Pe=>{let Tt=$.addSink(Pe);return ie().then(()=>$.reattach(),()=>{}),Tt},rt.getMainSessionId=()=>{let Tt=b?.runtime?.getSessionId?.();return typeof Tt=="string"&&Tt.length>0?Tt:void 0},rt.close=async()=>{I??=(async()=>{await z(),await FL(async()=>T.shutdownTelemetry?.(),U),(await T.providerRegistryRuntimePromise)?.dispose()})(),await I},rt}var Eti=Y(()=>{"use strict";vw();eN();ETt();XRn();I2n();DTt();fti();hti();yti();Tde();kti();j2n();B2n();CTt();Iti();r(Cti,"createTuiSubmitPrompt")});var Ati,Pti,Y1,QK,cP,Rti,Dti,Erc,Arc,Oti,Mti,Prc,Rrc,Drc,Orc,Mrc,Nrc,Nti=Y(()=>{"use strict";Ati=require("node:crypto"),Pti=require("node:fs"),Y1=require("node:fs/promises"),QK=require("node:os"),cP=require("node:path"),Rti=require("node:url"),Dti="zcode-tui-runtime/",Erc=`${Dti}manifest.json`,Arc="node_modules/@zcode/tui/dist/index.js",Oti="manifest.json",Mti=r(async()=>{let e=await import("node:sea");if(!e.isSea())return await import("@zcode/tui");let t=await Prc(e);return await import((0,Rti.pathToFileURL)((0,cP.join)(t,Arc)).href)},"loadTuiRuntime"),Prc=r(async e=>{let t=Rrc(e),n=(0,cP.join)(Orc(),"0.16.9",t.target,t.hash),o=(0,cP.join)(n,Oti);if(await Drc(o,t))return n;let s=`${n}.tmp-${process.pid}-${Date.now()}`;await(0,Y1.rm)(s,{force:!0,recursive:!0}),await(0,Y1.mkdir)(s,{recursive:!0});for(let a of t.files){let l=e.getRawAsset(`${Dti}${a.path}`),u=Buffer.from(l);if((0,Ati.createHash)("sha256").update(u).digest("hex")!==a.sha256)throw new Error(`SEA TUI asset hash mismatch for ${a.path}`);let g=(0,cP.join)(s,a.path);await(0,Y1.mkdir)((0,cP.dirname)(g),{recursive:!0}),await(0,Y1.writeFile)(g,u),await(0,Y1.chmod)(g,a.mode??Nrc(a.path))}return await(0,Y1.writeFile)(Mrc(s),JSON.stringify(t,null,2)),await(0,Y1.rm)(n,{force:!0,recursive:!0}),await(0,Y1.mkdir)((0,cP.dirname)(n),{recursive:!0}),await(0,Y1.rename)(s,n),n},"ensureSeaTuiRuntime"),Rrc=r(e=>{let t=e.getAsset(Erc,"utf8"),n=JSON.parse(t);if(n.version!==1||!n.hash||!Array.isArray(n.files))throw new Error("Invalid SEA TUI runtime manifest.");return n},"readManifest"),Drc=r(async(e,t)=>{if(!(0,Pti.existsSync)(e))return!1;try{let n=JSON.parse(await(0,Y1.readFile)(e,"utf8"));return n.hash===t.hash&&n.target===t.target}catch{return!1}},"isCacheCurrent"),Orc=r(()=>{let e=(0,QK.homedir)();return(0,QK.platform)()==="darwin"&&e?(0,cP.join)(e,"Library","Caches","zcode","sea-assets"):(0,QK.platform)()==="win32"?(0,cP.join)(process.env.LOCALAPPDATA??(0,cP.join)(e||(0,QK.tmpdir)(),"AppData","Local"),"zcode","Cache","sea-assets"):(0,cP.join)(process.env.XDG_CACHE_HOME??(0,cP.join)(e||(0,QK.tmpdir)(),".cache"),"zcode","sea-assets")},"cacheBaseDirectory"),Mrc=r(e=>(0,cP.join)(e,Oti),"markerPathForDirectory"),Nrc=r(e=>/\.(?:dll|dylib|node|so)$/i.test(e)?493:420,"modeForPath")});function Lti({deps:e,options:t,workingDirectory:n}){let o=K0({cliOverrides:Lrc(t.locale),env:e.env??process.env,projectConfigPath:e.projectConfigPath,skipUserConfig:e.skipUserConfig,userConfigPath:e.userConfigPath,workingDirectory:n});return e8(o.config.ui.locale,t.detectedLocale)}var Lrc,Fti=Y(()=>{"use strict";vw();eN();Lrc=r(e=>e?{ui:{locale:e}}:void 0,"localeCliOverrides");r(Lti,"resolveTuiStartupLocale")});function Bti(e){let t=e.fileSystemPort??hH(),n=(0,pN.resolve)(e.workspaceDirectory);return async o=>{let s=zrc(o.token);if(!s)return{items:[],truncated:!1};let a=(0,pN.resolve)(n,s.directoryToken);if(!Vrc(n,a))return{items:[],truncated:!1};try{let u=(await t.listDirectory({path:a},{signal:o.abortSignal})).entries.flatMap(g=>{if(g.kind!=="directory"&&g.kind!=="file")return[];if(g.kind==="directory"&&Urc.has(g.name))return[];if(!s.query.startsWith(".")&&g.name.startsWith("."))return[];if(!$rc(g.name,s.query))return[];let _=Wrc(n,g.path);return _?[{kind:g.kind,path:g.kind==="directory"?`${_}/`:_}]:[]}).sort((g,_)=>qrc(g,_,s.query)),f=Math.max(1,Math.floor(o.limit??Frc));return{items:u.slice(0,f),truncated:u.length>f}}catch{return{items:[],truncated:!1}}}}function zrc(e){let t=e.replace(/^@/u,"");if(t.startsWith("/")||t.startsWith("\\")||(0,pN.isAbsolute)(t)||Brc.test(t))return;let n=t.replace(jrc,"/");if(n.split("/").some(s=>s===".."))return;let o=n.lastIndexOf("/");return o<0?{directoryToken:"",query:n}:{directoryToken:n.slice(0,o+1),query:n.slice(o+1)}}function $rc(e,t){return t.length===0?!0:e.toLowerCase().includes(t.toLowerCase())}function qrc(e,t,n){if(e.kind!==t.kind)return e.kind==="directory"?-1:1;let o=jti(e.path),s=jti(t.path),a=n.toLowerCase(),l=o.toLowerCase().startsWith(a),u=s.toLowerCase().startsWith(a);return l!==u?l?-1:1:e.path.localeCompare(t.path)}function jti(e){let t=e.endsWith("/")?e.slice(0,-1):e,n=t.lastIndexOf("/");return n<0?t:t.slice(n+1)}function Wrc(e,t){let n=(0,pN.relative)(e,t);if(!(!n||n.startsWith("..")||(0,pN.isAbsolute)(n)))return n.split(pN.sep).join("/")}function Vrc(e,t){let n=(0,pN.relative)(e,t);return n===""||!n.startsWith("..")&&!(0,pN.isAbsolute)(n)}var pN,Frc,jrc,Brc,Urc,Uti=Y(()=>{"use strict";yme();pN=require("node:path"),Frc=50,jrc=/[\\/]+/gu,Brc=/^[a-zA-Z]:[\\/]/u,Urc=new Set([".bzr",".git",".hg",".jj",".sl",".svn","node_modules"]);r(Bti,"createWorkspacePathSuggestionProvider");r(zrc,"parseWorkspacePathToken");r($rc,"matchesPathQuery");r(qrc,"compareWorkspacePathSuggestion");r(jti,"basenameFromSuggestion");r(Wrc,"toWorkspaceRelativePath");r(Vrc,"isPathInside")});async function $ti(e){let t=e.maxOutputBytes??Krc,n=e.timeoutMs??Jrc,s=await(e.runCommand??Yrc)(Hrc,["-C",e.workspaceDirectory,...Grc],{maxOutputBytes:t,timeoutMs:n}).catch(()=>({exitCode:-1,stdout:""}));if(s.exitCode!==0)return;let a=s.stdout.trim().split(/\r?\n/,1)[0]?.trim();if(!(!a||a===Zrc))return a}async function Yrc(e,t,n){return await new Promise(o=>{let s;try{s=(0,zti.spawn)(e,t,{stdio:["ignore","pipe","ignore"],windowsHide:!0})}catch{o({exitCode:-1,stdout:""});return}let a="",l=!1,u=setTimeout(()=>{s.kill(),f({exitCode:-1,stdout:a})},n.timeoutMs),f=r(g=>{l||(l=!0,clearTimeout(u),o(g))},"finish");s.stdout?.on("data",g=>{a+=g.toString("utf8"),Buffer.byteLength(a,"utf8")>n.maxOutputBytes&&(s.kill(),f({exitCode:-1,stdout:a}))}),s.on("error",()=>f({exitCode:-1,stdout:a})),s.on("close",g=>f({exitCode:g,stdout:a}))})}var zti,Hrc,Grc,Jrc,Krc,Zrc,qti=Y(()=>{"use strict";zti=require("node:child_process"),Hrc="git",Grc=["symbolic-ref","--quiet","--short","HEAD"],Jrc=750,Krc=512,Zrc="HEAD";r($ti,"resolveWorkspaceGitBranch");r(Yrc,"runGitCommand")});var Wti,Vti=Y(()=>{"use strict";ms();oti();ati();ETt();Tde();j2n();CTt();Eti();Nti();Fti();Uti();qti();B2n();Wti=r(async(e,t,n,o,s,a,l,u=!1)=>{try{let f=Tti(s),g=n.runTui??(await Mti()).runTui,_=(n.cwd??process.cwd)(),b=n.env??process.env,w=OCe(b)==="development",T=await(n.resolveWorkspaceGitBranch??$ti)({workspaceDirectory:_}).catch(()=>{}),I=Lti({deps:n,options:t,workingDirectory:_}),E=Cti(n,f,o,a,t.locale,t.detectedLocale,I,l,u,t.browserUse,t.browserExecutable),R=rGe({cleanup:r(async()=>{await E.close?.()},"cleanup"),cleanupTimeoutMs:n.shutdownCleanupTimeoutMs,exitProcess:n.exitProcess,process:n.shutdownProcess});try{let L=await fei(n),U=L?{locale:I}:await dti(E),B=L||!U.model?[]:await E.listModelOptions?.().catch(()=>[]),z=L||!U.model?[]:await E.listEffortOptions?.().catch(()=>[]),$=await BTt(n).catch(()=>{});return await g({initialMode:XK(f),initialModel:U.model,initialThoughtLevel:U.thoughtLevel,loginRequired:L,locale:U.locale??I,theme:U.theme??"auto",developerMode:w,version:o,workspaceDirectory:_,workspaceGitBranch:T,noColor:t.noColor,readClipboardImage:n.readClipboardImage??tti(),effortOptions:z,modelOptions:B,listWorkspacePathSuggestions:Bti({workspaceDirectory:_}),listMcpServers:E.listMcpServers,listWorkflowRuns:E.listWorkflowRuns,replayWorkflowRuns:E.replayWorkflowRuns,getMainSessionId:E.getMainSessionId,writeClipboardText:n.writeClipboardText??sti({stdout:e.stdout}),stderr:e.stderr,stdin:e.stdin,stdout:e.stdout,loadSessionTranscript:E.loadSessionTranscript,loadSessionContextMessages:E.loadSessionContextMessages,readGoal:E.readGoal,readTodos:E.readTodos,readRuntimeProjection:E.readRuntimeProjection,readSessionUsage:E.readSessionUsage,cancelBackgroundTask:E.cancelBackgroundTask,previewFileRewind:E.previewFileRewind,applyFileRewind:E.applyFileRewind,setCustomSessionTitle:E.setCustomSessionTitle,readCustomSessionTitle:E.readCustomSessionTitle,interruptTurn:E.interruptTurn,promoteQueuedInput:E.promoteQueuedInput,listSkills:E.listSkills,readDefaultModel:E.readDefaultModel,setDefaultModel:E.setDefaultModel,reloadModelOptions:E.reloadModelOptions,listModelOptions:E.listModelOptions,readExecutionState:E.readExecutionState,setPlanEnabled:E.setPlanEnabled,setTransientModel:E.setTransientModel,readSessionModel:E.readSessionModel,sendBackgroundTaskMessage:E.sendBackgroundTaskMessage,recallPreviousInput:E.recallPreviousInput,sendInput:E.sendInput,setMode:E.setMode,slashCommands:v2n($),submitPrompt:E,subscribeSessionEvents:E.subscribeSessionEvents})}finally{R(),await E.close?.()}}catch(f){let g=f instanceof Error?f.message:String(f);return e.stderr.write(`Error: ${g}
15417
+ Scopes: user (default), project. \`zcode plugin\` is an alias of \`zcode plugins\`.`;r(Zei,"runPluginsCommand");r(nrc,"runPluginsListCommand");r(rrc,"runPluginsInstallCommand");r(orc,"runPluginsUpdateCommand");r(irc,"reportInstallOutcome");r(Yei,"runPluginsSetCommand");r(src,"runPluginsDisableCommand");r(arc,"runPluginsUninstallCommand");r(crc,"runPluginsValidateCommand")});function urc(e=process.env){let t=e.ZCODE_STORAGE_DIR?.trim()||(0,dse.join)((0,eti.homedir)(),".zcode");return(0,dse.join)(t,"clipboard")}function tti(e={}){let t=e.platform??process.platform,n=e.maxBytes??lrc,o=e.runCommand??mrc,s=e.tempDirectory??urc(e.processEnv);return async(a={})=>t==="darwin"?await drc({maxBytes:n,runCommand:o,signal:a.abortSignal,tempDirectory:s}):t==="linux"?await prc({maxBytes:n,runCommand:o,signal:a.abortSignal}):t==="win32"?await frc({maxBytes:n,runCommand:o,signal:a.abortSignal,tempDirectory:s}):null}async function drc(e){await(0,M4.mkdir)(e.tempDirectory,{recursive:!0});let t=await(0,M4.mkdtemp)((0,dse.join)(e.tempDirectory,"zcode-clipboard-")),n=(0,dse.join)(t,"clipboard.png");try{return(await e.runCommand("osascript",["-e","set png_data to (the clipboard as \xABclass PNGf\xBB)","-e",`set fp to open for access POSIX file ${hrc(n)} with write permission`,"-e","write png_data to fp","-e","close access fp"],{maxBytes:e.maxBytes,signal:e.signal})).exitCode!==0?null:await nti(n,"image/png",e.maxBytes)}finally{await(0,M4.rm)(t,{force:!0,recursive:!0})}}async function prc(e){let t=[{args:["--type","image/png"],file:"wl-paste",mediaType:"image/png"},{args:["--type","image/jpeg"],file:"wl-paste",mediaType:"image/jpeg"},{args:["--type","image/gif"],file:"wl-paste",mediaType:"image/gif"},{args:["--type","image/webp"],file:"wl-paste",mediaType:"image/webp"},{args:["-selection","clipboard","-t","image/png","-o"],file:"xclip",mediaType:"image/png"},{args:["-selection","clipboard","-t","image/jpeg","-o"],file:"xclip",mediaType:"image/jpeg"},{args:["-selection","clipboard","-t","image/gif","-o"],file:"xclip",mediaType:"image/gif"},{args:["-selection","clipboard","-t","image/webp","-o"],file:"xclip",mediaType:"image/webp"}];for(let n of t){let o=await e.runCommand(n.file,n.args,{maxBytes:e.maxBytes,signal:e.signal}),s=rti(o.stdout,n.mediaType,e.maxBytes);if(o.exitCode===0&&s)return s}return null}async function frc(e){await(0,M4.mkdir)(e.tempDirectory,{recursive:!0});let t=await(0,M4.mkdtemp)((0,dse.join)(e.tempDirectory,"zcode-clipboard-")),n=(0,dse.join)(t,"clipboard.png"),o=["Add-Type -AssemblyName System.Windows.Forms;","$img = Get-Clipboard -Format Image;","if ($null -eq $img) { exit 2 }",`$img.Save(${grc(n)}, [System.Drawing.Imaging.ImageFormat]::Png);`].join(" ");try{return(await e.runCommand("powershell.exe",["-NoProfile","-NonInteractive","-Command",o],{maxBytes:e.maxBytes,signal:e.signal})).exitCode!==0?null:await nti(n,"image/png",e.maxBytes)}finally{await(0,M4.rm)(t,{force:!0,recursive:!0})}}async function nti(e,t,n){let o=await(0,M4.readFile)(e);return rti(o,t,n)}function rti(e,t,n){return e.byteLength===0||e.byteLength>n?null:{dataUrl:`data:${t};base64,${e.toString("base64")}`,mediaType:t,sizeBytes:e.byteLength}}async function mrc(e,t,n){return await new Promise(o=>{let s;try{s=(0,Qei.spawn)(e,t,{signal:n.signal,stdio:["ignore","pipe","ignore"],windowsHide:!0})}catch{o({exitCode:-1,stdout:Buffer.alloc(0)});return}let a=[],l=0,u=!1,f=r(g=>{u||(u=!0,o(g))},"finish");s.stdout?.on("data",g=>{if(l+=g.byteLength,l>n.maxBytes){s.kill();return}a.push(g)}),s.on("error",()=>f({exitCode:-1,stdout:Buffer.alloc(0)})),s.on("close",(g,_)=>{f({exitCode:g,signal:_,stdout:Buffer.concat(a)})})})}function hrc(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function grc(e){return`'${e.replace(/'/g,"''")}'`}var Qei,M4,eti,dse,lrc,oti=Y(()=>{"use strict";Qei=require("node:child_process"),M4=require("node:fs/promises"),eti=require("node:os"),dse=require("node:path"),lrc=20*1024*1024;r(urc,"resolveDefaultClipboardDirectory");r(tti,"createNodeClipboardImageReader");r(drc,"readMacClipboardImage");r(prc,"readLinuxClipboardImage");r(frc,"readWindowsClipboardImage");r(nti,"readImageFile");r(rti,"bufferToClipboardImage");r(mrc,"runCommandBuffer");r(hrc,"appleScriptString");r(grc,"powershellString")});function sti(e={}){let t=e.maxBytes??_rc,n=e.platform??process.platform,o=e.runCommand??Irc;return async s=>{let a=Trc(s,t);if(a.byteLength===0)return;let l=wrc(e.stdout,a),u=await krc({input:s,platform:n,runCommand:o});if(!l&&!u)throw new Error("No text clipboard target accepted the selected text.")}}function wrc(e,t){if(!e)return!1;try{return e.write(`${vrc}${yrc};${t.toString("base64")}${brc}`),!0}catch{return!1}}async function krc(e){for(let t of xrc(e.platform))if((await e.runCommand(t.file,t.args,{input:e.input})).exitCode===0)return!0;return!1}function xrc(e){return e==="darwin"?[{args:[],file:"pbcopy"}]:e==="linux"?[{args:[],file:"wl-copy"},{args:["-selection","clipboard"],file:"xclip"},{args:["--clipboard","--input"],file:"xsel"}]:e==="win32"?[{args:["-NoProfile","-NonInteractive","-Command",Src],file:"powershell.exe"}]:[]}function Trc(e,t){let n=Buffer.from(e,"utf8");if(n.byteLength>t)throw new Error(`Clipboard text exceeds ${t} bytes.`);return n}async function Irc(e,t,n){return await new Promise(o=>{let s;try{s=(0,iti.spawn)(e,t,{stdio:["pipe","ignore","ignore"],windowsHide:!0})}catch{o({exitCode:-1});return}let a=!1,l=r(u=>{a||(a=!0,o(u))},"finish");s.stdin?.on("error",()=>{}),s.stdin?.end(n.input),s.on("error",()=>l({exitCode:-1})),s.on("close",(u,f)=>l({exitCode:u,signal:f}))})}var iti,_rc,yrc,vrc,brc,Src,ati=Y(()=>{"use strict";iti=require("node:child_process"),_rc=1024*1024,yrc="c",vrc="\x1B]52;",brc="\x07",Src="Set-Clipboard -Value ([Console]::In.ReadToEnd())";r(sti,"createNodeClipboardTextWriter");r(wrc,"writeOsc52");r(krc,"writeNativeClipboardText");r(xrc,"nativeClipboardCommands");r(Trc,"assertClipboardTextSize");r(Irc,"runCommandText")});async function BTt(e){let t=e.env??process.env,n=(e.cwd??process.cwd)();return e.listCustomCommands?await e.listCustomCommands({env:t,logger:e.logger,workingDirectory:n}):await(await Qg()).listZCodeCustomCommands({env:t,logger:e.logger,workingDirectory:n})}async function cti(e,t){let n=e.env??process.env,o=(e.cwd??process.cwd)();return e.loadCustomCommand?await e.loadCustomCommand({env:n,logger:e.logger,name:t,workingDirectory:o}):await(await Qg()).loadZCodeCustomCommand({env:n,logger:e.logger,name:t,workingDirectory:o})}async function lti(e){let t=e.env??process.env,n=(e.cwd??process.cwd)();return await(e.listSkills??(await Qg()).listZCodeSkills)({env:t,logger:e.logger,workingDirectory:n})}async function uti(e){let t=e.env??process.env,n=(e.cwd??process.cwd)();return(await(e.listSessions??(await Qg()).listZCodeSessions)({directory:n,env:t,limit:50})).map(a=>({directory:a.directory,id:a.id,parentId:a.parentID,title:a.title,updatedAt:a.time.updated}))}async function dti(e){try{return await e.getSessionMetadata?.()??{}}catch(t){if(Crc(t))throw t;return{}}}function Crc(e){return e instanceof Error?e.name==="SqliteSessionMigrationError":!1}var j2n=Y(()=>{"use strict";b9();r(BTt,"listCustomCommandsForTui");r(cti,"loadCustomCommandForTui");r(lti,"listSkillsForTui");r(uti,"listSessionsForTui");r(dti,"loadInitialTuiSessionMetadata");r(Crc,"isStartupGateError")});function pti(e){let t=new Set,n,o=r(()=>{n?.(),n=void 0},"detach"),s=r(()=>{if(o(),t.size===0)return;n=e.readSubscriber(e.currentRuntime())?.({onSessionEvent:r(l=>{for(let u of t)u(l)},"onSessionEvent")})},"reattach");return{addSink:r(a=>(t.add(a),t.size===1&&s(),()=>{t.delete(a),t.size===0&&o()}),"addSink"),reattach:s,detach:o,isAttached:r(()=>n!==void 0,"isAttached")}}var fti=Y(()=>{"use strict";r(pti,"createTuiSessionEventRelay")});var mti,hti=Y(()=>{"use strict";TTt();mti=r((e,t)=>{const $zTuiBridge=e,$zTuiGetApp=t;$zTuiBridge.loadSessionTranscript=async()=>await(await $zTuiGetApp()).loadSessionTranscript?.()??[],$zTuiBridge.loadSessionContextMessages=async()=>await(await $zTuiGetApp()).loadSessionContextMessages?.()??[],$zTuiBridge.readGoal=async()=>await(await $zTuiGetApp()).readTarget?.()??null,$zTuiBridge.readTodos=async()=>await(await $zTuiGetApp()).readTodos?.()??[],$zTuiBridge.readRuntimeProjection=async()=>{let $zRuntimeProjectionBridge=await $zTuiGetApp();return await require(require("node:path").join(__dirname,"cli-config.cjs")).readTuiRuntimeProjection($zRuntimeProjectionBridge,$zTuiBridge)},$zTuiBridge.$zRestorePersistedBackgroundTasks=async $zApp=>await require(require("node:path").join(__dirname,"cli-config.cjs")).restoreTuiBackgroundTasks($zApp),$zTuiBridge.readSessionUsage=async()=>await(await $zTuiGetApp()).readSessionUsage?.()??null,$zTuiBridge.cancelBackgroundTask=async e=>await(await $zTuiGetApp()).cancelBackgroundTask?.(e)??null,$zTuiBridge.previewFileRewind=async e=>{let t=await $zTuiGetApp();return await t.runtime?.previewWorkspaceFileRewind?.({targetMessageIds:e})??null},$zTuiBridge.applyFileRewind=async e=>{let t=await $zTuiGetApp();return await t.runtime?.applyWorkspaceFileRewind?.({targetMessageIds:e})??null},$zTuiBridge.setCustomSessionTitle=async e=>{let t=await $zTuiGetApp();let r=t.runtime?.setCustomSessionTitle?.bind(t.runtime)??t.setCustomSessionTitle?.bind(t);if(!r)throw new Error("Session renaming is unavailable in this runtime.");return await r({title:e.title,traceContext:e.traceContext??t.runtime?.rootTraceContext})},$zTuiBridge.readCustomSessionTitle=async()=>{let t=await $zTuiGetApp(),o=t.sessionStore??t.runtime?.sessionStore,r=await o?.getSession?.(t.sessionId);return r?.titleSource==="custom"&&typeof r.title==="string"?r.title:void 0},$zTuiBridge.setMode=async e=>{return await(await $zTuiGetApp()).setMode(e)},$zTuiBridge.readExecutionState=async()=>await(await $zTuiGetApp()).readExecutionState(),$zTuiBridge.setPlanEnabled=async e=>await(await $zTuiGetApp()).setPlanEnabled(e),$zTuiBridge.setTransientModel=async e=>{if(e==="main"){e=await $zTuiBridge.readDefaultModel();if(!e)throw new Error("No default model is configured.")}let t=await $zTuiGetApp(),r=await t.setModel(e);return{...r,thoughtLevel:t.getThoughtLevel(),effortOptions:t.listThoughtLevels()}},$zTuiBridge.readSessionModel=async()=>{let $zSessionModelApp=await $zTuiGetApp(),s=await $zSessionModelApp.readSessionModelState();if(s?.selection&&!s.issue)await $zSessionModelApp.setModel(s.selection,{transient:!0});return s},$zTuiBridge.sendBackgroundTaskMessage=async e=>await require(require("node:path").join(__dirname,"cli-config.cjs")).sendTuiBackgroundTaskMessage(await $zTuiGetApp(),$zTuiBridge,e),$zTuiBridge.interruptTurn=async e=>{let t=await $zTuiGetApp(),r=e?.reservationId??"tui-steer-interrupt",o=(Array.isArray(e?.pendingInputIds)?e.pendingInputIds:[]).filter(Boolean),n=[],i=async()=>{for(let a of n)await t.releaseQueueItemReservation?.(a,r);n=[]};try{if(t.reserveQueueItem&&t.releaseQueueItemReservation)for(let a of o)if(await t.reserveQueueItem(a,r))n.push(a);else{await i();break}let a=t.runtime?.stopActiveForegroundExecution?.({preserveQueueAutoDrainOnCancel:o.length>0&&n.length===o.length,reason:e?.reason??"TUI steer interrupt"})??{kind:"unsupported"};if(a.kind==="stopped"&&e?.waitForIdle===!0&&t.runtime?.getActiveForegroundExecutionId){let u=Date.now()+5e3;for(;t.runtime.getActiveForegroundExecutionId()!==void 0;){if(Date.now()>=u)throw new Error("Timed out waiting for background result processing to stop.");await new Promise(l=>setTimeout(l,25))}}return a.kind!=="stopped"&&await i(),a}catch(a){await i();throw a}},$zTuiBridge.promoteQueuedInput=async(e,t,r)=>{let o=await $zTuiGetApp(),n=r?.pendingInputReservationId??r?.queryId??r?.inputId??"tui-promotion",i=(Array.isArray(t)?t:[t]).filter(Boolean);if(i.length===0||!o.reserveQueueItem||!o.markQueueItemPromoting||!o.releaseQueueItemReservation||!o.removeQueueItem)return $zTuiBridge.sendInput(e,{...r,delivery:"start_turn"});let a=[],u=!1;try{for(let l of i){if(await o.markQueueItemPromoting(l,n)){a.push(l);continue}if(!await o.reserveQueueItem(l,n))throw new Error("TUI queued input is already reserved: "+l);a.push(l);if(!await o.markQueueItemPromoting(l,n))throw new Error("TUI queued input promotion failed: "+l)}let c=await $zTuiBridge.sendInput(e,{...r,delivery:"start_turn"});if(c?.kind==="rejected")return c;u=!0;for(let l of a)if(!await o.removeQueueItem(l,{reason:"promoted",reservationId:n}))throw new Error("TUI queued input promotion commit failed: "+l);return c}finally{if(!u)for(let l of a)await o.releaseQueueItemReservation(l,n)}},$zTuiBridge.$zSendInputWithoutBackgroundRestore=$zTuiBridge.sendInput,$zTuiBridge.sendInput=async(...$zArgs)=>{let $zApp=await $zTuiGetApp();await $zTuiBridge.$zRestorePersistedBackgroundTasks?.($zApp);return await $zTuiBridge.$zSendInputWithoutBackgroundRestore.apply($zTuiBridge,$zArgs)},e.recallPreviousInput=async n=>await(await t()).recallPreviousInputHistory?.(n)??null,e.getSessionMetadata=async()=>{let n=await t();return{locale:n.getLocale?.(),model:n.getModel?.(),theme:n.getTheme?.(),thoughtLevel:n.getThoughtLevel?.()}},e.reloadModelOptions=async()=>await(await t()).reloadModels(),e.readDefaultModel=async()=>{await t();let $zSelection=await(await e.$zReadProviderRegistryRuntime()).modelSelectionConfigRepository.read();return $zSelection?$zSelection.providerId+"/"+$zSelection.modelId:void 0},e.setDefaultModel=async $zModel=>{let $zApp=await t(),$zIndex=$zModel.indexOf("/"),$zSelection={providerId:$zModel.slice(0,$zIndex),modelId:$zModel.slice($zIndex+1)};if($zIndex<=0||!$zApp.getModelOption($zSelection))throw new Error("Unknown default model: "+$zModel);await(await e.$zReadProviderRegistryRuntime()).modelSelectionConfigRepository.saveConfiguredDefault($zSelection);return await e.setTransientModel($zModel)},e.listModelOptions=async()=>(await t()).listModels?.()??[],e.listEffortOptions=async()=>{let n=await t();return await j3e(n)??[]},e.listMcpServers=async()=>(await t()).listMcpServers?.()??{},e.listWorkflowRuns=async()=>await(await t()).listDynamicWorkflowRuns?.({})??[],e.replayWorkflowRuns=async n=>await(await t()).replayDynamicWorkflowRuns?.(n)??[]},"attachTuiAppQueries")});async function _ti(e,t,n,o){let s=e.env??process.env,a=(e.cwd??process.cwd)(),l=(e.loadDotenv??rA)({cwd:a,env:s});if(l.error)throw new Error(`Failed to load environment file: ${l.path}`,{cause:l.error});let u=await OTt(n,a,s,e),f=e.createZCodeApp?void 0:await Qg(),g=e.createZCodeApp??f?.createZCodeApp;if(!g)throw new Error("ZCode app factory is unavailable.");let _=e.prepareZCodeTelemetryEnv??f?.prepareZCodeTelemetryEnv;_&&(o.shutdownTelemetry=e.shutdownZCodeTelemetry??f?.shutdownZCodeTelemetry);let b=_?await _(s,{cliVersion:t,productVersion:s.ZCODE_APP_VERSION}):s,w=e.startProcessProviderRegistryRuntime??f?.startProcessProviderRegistryRuntime;if(!w)throw new Error("Provider Registry runtime is unavailable.");o.providerRegistryRuntimePromise??=w(b,e.skipUserConfig?{}:{standalone:{...gPe(),...e.userConfigPath?{legacyCliUserConfigFilePath:e.userConfigPath}:{}}});let T=await o.providerRegistryRuntimePromise,I=T?.modelSelectionConfigRepository?await T.modelSelectionConfigRepository.read():T?.configuredDefaultModelSelection,E=e.createProviderEndpointRoutingPort??f?.createDefaultProviderEndpointRoutingPort;return o.providerEndpointRoutingPort??=E?.({appVersion:t,env:s,projectConfigPath:e.projectConfigPath,skipUserConfig:e.skipUserConfig,userConfigPath:e.userConfigPath,workingDirectory:a}),{appEnv:b,configuredDefaultModelSelection:I,createAppFactory:g,providerRegistryRuntime:T,sessionId:u,workingDirectory:a}}var gti,yti=Y(()=>{"use strict";b9();jQ();NXe();A2n();gti=r(()=>({providerEndpointRoutingPort:void 0,providerRegistryRuntimePromise:void 0,shutdownTelemetry:void 0}),"createTuiProcessRuntimeState");r(_ti,"prepareTuiAppRuntime")});async function vti(e,t){let n=e.env??process.env,o=(e.cwd??process.cwd)(),s=(e.loadDotenv??rA)({cwd:o,env:n});if(s.error)throw new Error(`Failed to load environment file: ${s.path}`,{cause:s.error});return await(e.loginZCodeCli??(await Qg()).loginZCodeCli)({abortSignal:t?.abortSignal,env:n,onAuthorizeUrl:t?.onAuthorizeUrl})}async function bti(e,t){let n=e.env??process.env,o=(e.cwd??process.cwd)(),s=(e.loadDotenv??rA)({cwd:o,env:n});if(s.error)throw new Error(`Failed to load environment file: ${s.path}`,{cause:s.error});return await(e.loginBigmodelCodingPlan??(await Qg()).loginBigmodelCodingPlan)({abortSignal:t?.abortSignal,env:n,onAuthorizeUrl:t?.onAuthorizeUrl})}async function Sti(e,t){return await(e.configureCodingPlanApiKey??(await Qg()).configureCodingPlanApiKey)({apiKey:t.apiKey,env:e.env??process.env,providerId:t.providerId})}async function wti(e){let t=e.env??process.env,n=(e.cwd??process.cwd)(),o=(e.loadDotenv??rA)({cwd:n,env:t});if(o.error)throw new Error(`Failed to load environment file: ${o.path}`,{cause:o.error});return await(e.logoutZCodeCli??(await Qg()).logoutZCodeCli)({env:t})}var kti=Y(()=>{"use strict";b9();jQ();r(vti,"loginForTui");r(bti,"loginBigmodelForTui");r(Sti,"configureApiKeyForTui");r(wti,"logoutForTui")});var xti,Tti,XK,B2n=Y(()=>{"use strict";xti={},Tti=r(e=>({current:e,override:e}),"createCliModeState"),XK=r(e=>e.current??e.override??"build","currentCliMode")});function U2n(e,t,n){return{kind:"started_turn",result:{...e,locale:e.locale??t.getLocale?.(),mode:n,model:e.model??t.getModel?.(),theme:e.theme??t.getTheme?.(),thoughtLevel:e.thoughtLevel??t.getThoughtLevel?.()}}}var Iti=Y(()=>{"use strict";r(U2n,"withTuiMetadata")});function Cti(e,t,n,o={continueSession:!1},s,a,l=Myt,u,f=!1,g,_){let b,w=s,T=gti(),I,E=new WeakMap,R=new WeakMap,L,U=Math.max(1,Math.trunc(e.shutdownCleanupTimeoutMs??nGe)),B={requestPermission:r(async(Pe,Tt)=>{let Ye=L;return Ye?await Ye(Pe,Tt):{decision:"deny",reason:`No interactive approval handler configured for ${Pe.toolName}`,resolvedAt:new Date}},"requestPermission")},z=r(async(Pe=b)=>{if(!Pe)return;let Tt=Pe,Ye=E.get(Tt);Ye||(Ye=(async()=>{await FL(async()=>Pe.close?.(),U),await FL(async()=>R.get(Tt)?.close(),U)})(),E.set(Tt,Ye)),await Ye},"closeApp"),$=pti({currentRuntime:r(()=>b?.runtime,"currentRuntime"),readSubscriber:RTt}),J=r(async Pe=>{let Tt=b,Ye=await Pe();return b=Ye,Tt&&Tt!==Ye&&await z(Tt),$.reattach(),t.current=b.getMode?.()??XK(t),b},"replaceApp"),q=r(async Pe=>{if(I)throw new Error("TUI prompt handler is closed");let{appEnv:Tt,configuredDefaultModelSelection:Ye,createAppFactory:Fe,providerRegistryRuntime:St,sessionId:kt,workingDirectory:st}=await _ti(e,n,Pe,T),$e=T.providerEndpointRoutingPort,jt=ATt({browserExecutable:_,browserUse:g},e),Je;try{Je=await Fe({browserControlPort:jt?.browserControlPort,env:Tt,projectConfigPath:e.projectConfigPath,...$e?{providerEndpointRoutingPort:$e}:{},providerRegistry:St.runtime.registryService,configuredDefaultModelSelection:Ye,...St.providerRuntimeHeadersPort?{providerRuntimeHeadersPort:St.providerRuntimeHeadersPort}:{},resume:kt!==void 0,runtimeConfig:{...t.override?{mode:t.override}:{},...u?{toolDisallowlist:u}:{},...f?{midConversationSystem:{mode:"force"}}:{},modelStreaming:"on",titleGeneration:xti,workingDirectory:st},permissionBroker:B,sessionId:kt,skipUserConfig:e.skipUserConfig,uiDetectedLocale:a,uiLocale:w,userConfigPath:e.userConfigPath,version:n})}catch(Xe){throw await FL(async()=>jt?.close(),U),Xe}if(jt&&R.set(Je,jt),I)throw await z(Je),new Error("TUI prompt handler is closed");return t.current=Je.getMode?.()??t.override??t.current??"build",Je},"createApp"),ie=r(async()=>(b??=await q(o),t.current=b.getMode?.()??XK(t),b),"getApp"),ae=r(async Pe=>await J(async()=>await q(Pe?{continueSession:!1,resumeSessionId:Pe}:{continueSession:!0})),"resumeApp"),Ce=r(async()=>await J(async()=>await q({continueSession:!1})),"newApp"),pe=r(async Pe=>{if(t.override=Pe,b){let Tt=b;if(Tt.setMode){let Ye=await Tt.setMode(Pe);return t.current=Ye.mode,Ye.mode}Tt.runtime.updateConfig({mode:Pe})}return t.current=Pe,Pe},"setCliMode"),ze=$3e({forkApp:r(async Pe=>{let Ye=await(await ie()).forkFromCheckpoint?.({targetCheckpointId:Pe});if(!Ye)throw new Error("Forking is not available in this client.");return await J(async()=>await q({continueSession:!1,resumeSessionId:Ye.forkedSessionId})),{copiedMessageCount:Ye.copiedMessageCount,forkedSessionId:Ye.forkedSessionId,response:`${Ye.response}
15418
+ Switched to forked session ${Ye.forkedSessionId}.`,restoredFileCount:Ye.restoredFileCount??Ye.restoredFiles?.length??0}},"forkApp"),getApp:ie,getMode:r(()=>XK(t),"getMode"),getLocale:r(()=>b?.getLocale?.()??YRn(w,a)??l,"getLocale"),hasConfiguredCodingPlanAccess:k2n(e),listCustomCommands:r(()=>BTt(e),"listCustomCommands"),listSessions:r(()=>uti(e),"listSessions"),listSkills:r(()=>lti(e),"listSkills"),configureApiKey:r(Pe=>Sti(e,Pe),"configureApiKey"),login:r(Pe=>vti(e,Pe),"login"),loginBigmodel:r(Pe=>bti(e,Pe),"loginBigmodel"),loadCustomCommand:r(Pe=>cti(e,Pe),"loadCustomCommand"),newApp:Ce,recordInputHistory:r(async(Pe,Tt)=>{await b?.recordInputHistory?.(Pe,Tt)},"recordInputHistory"),resumeApp:ae,logout:r(()=>wti(e),"logout"),setLocale:r(async Pe=>{if(b?.setLocale){let Ye=await b.setLocale(Pe);return w=Pe,Ye}return w=Pe,{configPath:(await yOe(e.userConfigPath??U7(),Pe)).path,locale:YRn(Pe,a)??"en-US",requestedLocale:Pe}},"setLocale"),setMode:pe}),rt=r(async(Pe,Tt)=>{let Ye=L;L=Tt.requestPermission;try{return await ze(Pe,Tt)}finally{L=Ye}},"submitPrompt");return rt.setMode=async Pe=>({mode:await pe(Pe)}),rt.sendInput=async(Pe,Tt)=>{let Ye=L;L=Tt?.requestPermission;try{let Fe=await ie();if(Fe.sendInput){let St=await Fe.sendInput(Pe,Tt);return St.kind!=="started_turn"?St:U2n(await(St.result??St.completion),Fe,XK(t))}return U2n(await Fe.submitPrompt(Pe,Tt),Fe,XK(t))}finally{L=Ye}},rt.listSkills=async()=>await lti(e),rt.$zReadProviderRegistryRuntime=()=>T.providerRegistryRuntimePromise,mti(rt,ie),rt.subscribeSessionEvents=Pe=>{let Tt=$.addSink(Pe);return ie().then(()=>$.reattach(),()=>{}),Tt},rt.getMainSessionId=()=>{let Tt=b?.runtime?.getSessionId?.();return typeof Tt=="string"&&Tt.length>0?Tt:void 0},rt.close=async()=>{I??=(async()=>{await z(),await FL(async()=>T.shutdownTelemetry?.(),U),(await T.providerRegistryRuntimePromise)?.dispose()})(),await I},rt}var Eti=Y(()=>{"use strict";vw();eN();ETt();XRn();I2n();DTt();fti();hti();yti();Tde();kti();j2n();B2n();CTt();Iti();r(Cti,"createTuiSubmitPrompt")});var Ati,Pti,Y1,QK,cP,Rti,Dti,Erc,Arc,Oti,Mti,Prc,Rrc,Drc,Orc,Mrc,Nrc,Nti=Y(()=>{"use strict";Ati=require("node:crypto"),Pti=require("node:fs"),Y1=require("node:fs/promises"),QK=require("node:os"),cP=require("node:path"),Rti=require("node:url"),Dti="zcode-tui-runtime/",Erc=`${Dti}manifest.json`,Arc="node_modules/@zcode/tui/dist/index.js",Oti="manifest.json",Mti=r(async()=>{let e=await import("node:sea");if(!e.isSea())return await import("@zcode/tui");let t=await Prc(e);return await import((0,Rti.pathToFileURL)((0,cP.join)(t,Arc)).href)},"loadTuiRuntime"),Prc=r(async e=>{let t=Rrc(e),n=(0,cP.join)(Orc(),"0.16.9",t.target,t.hash),o=(0,cP.join)(n,Oti);if(await Drc(o,t))return n;let s=`${n}.tmp-${process.pid}-${Date.now()}`;await(0,Y1.rm)(s,{force:!0,recursive:!0}),await(0,Y1.mkdir)(s,{recursive:!0});for(let a of t.files){let l=e.getRawAsset(`${Dti}${a.path}`),u=Buffer.from(l);if((0,Ati.createHash)("sha256").update(u).digest("hex")!==a.sha256)throw new Error(`SEA TUI asset hash mismatch for ${a.path}`);let g=(0,cP.join)(s,a.path);await(0,Y1.mkdir)((0,cP.dirname)(g),{recursive:!0}),await(0,Y1.writeFile)(g,u),await(0,Y1.chmod)(g,a.mode??Nrc(a.path))}return await(0,Y1.writeFile)(Mrc(s),JSON.stringify(t,null,2)),await(0,Y1.rm)(n,{force:!0,recursive:!0}),await(0,Y1.mkdir)((0,cP.dirname)(n),{recursive:!0}),await(0,Y1.rename)(s,n),n},"ensureSeaTuiRuntime"),Rrc=r(e=>{let t=e.getAsset(Erc,"utf8"),n=JSON.parse(t);if(n.version!==1||!n.hash||!Array.isArray(n.files))throw new Error("Invalid SEA TUI runtime manifest.");return n},"readManifest"),Drc=r(async(e,t)=>{if(!(0,Pti.existsSync)(e))return!1;try{let n=JSON.parse(await(0,Y1.readFile)(e,"utf8"));return n.hash===t.hash&&n.target===t.target}catch{return!1}},"isCacheCurrent"),Orc=r(()=>{let e=(0,QK.homedir)();return(0,QK.platform)()==="darwin"&&e?(0,cP.join)(e,"Library","Caches","zcode","sea-assets"):(0,QK.platform)()==="win32"?(0,cP.join)(process.env.LOCALAPPDATA??(0,cP.join)(e||(0,QK.tmpdir)(),"AppData","Local"),"zcode","Cache","sea-assets"):(0,cP.join)(process.env.XDG_CACHE_HOME??(0,cP.join)(e||(0,QK.tmpdir)(),".cache"),"zcode","sea-assets")},"cacheBaseDirectory"),Mrc=r(e=>(0,cP.join)(e,Oti),"markerPathForDirectory"),Nrc=r(e=>/\.(?:dll|dylib|node|so)$/i.test(e)?493:420,"modeForPath")});function Lti({deps:e,options:t,workingDirectory:n}){let o=K0({cliOverrides:Lrc(t.locale),env:e.env??process.env,projectConfigPath:e.projectConfigPath,skipUserConfig:e.skipUserConfig,userConfigPath:e.userConfigPath,workingDirectory:n});return e8(o.config.ui.locale,t.detectedLocale)}var Lrc,Fti=Y(()=>{"use strict";vw();eN();Lrc=r(e=>e?{ui:{locale:e}}:void 0,"localeCliOverrides");r(Lti,"resolveTuiStartupLocale")});function Bti(e){let t=e.fileSystemPort??hH(),n=(0,pN.resolve)(e.workspaceDirectory);return async o=>{let s=zrc(o.token);if(!s)return{items:[],truncated:!1};let a=(0,pN.resolve)(n,s.directoryToken);if(!Vrc(n,a))return{items:[],truncated:!1};try{let u=(await t.listDirectory({path:a},{signal:o.abortSignal})).entries.flatMap(g=>{if(g.kind!=="directory"&&g.kind!=="file")return[];if(g.kind==="directory"&&Urc.has(g.name))return[];if(!s.query.startsWith(".")&&g.name.startsWith("."))return[];if(!$rc(g.name,s.query))return[];let _=Wrc(n,g.path);return _?[{kind:g.kind,path:g.kind==="directory"?`${_}/`:_}]:[]}).sort((g,_)=>qrc(g,_,s.query)),f=Math.max(1,Math.floor(o.limit??Frc));return{items:u.slice(0,f),truncated:u.length>f}}catch{return{items:[],truncated:!1}}}}function zrc(e){let t=e.replace(/^@/u,"");if(t.startsWith("/")||t.startsWith("\\")||(0,pN.isAbsolute)(t)||Brc.test(t))return;let n=t.replace(jrc,"/");if(n.split("/").some(s=>s===".."))return;let o=n.lastIndexOf("/");return o<0?{directoryToken:"",query:n}:{directoryToken:n.slice(0,o+1),query:n.slice(o+1)}}function $rc(e,t){return t.length===0?!0:e.toLowerCase().includes(t.toLowerCase())}function qrc(e,t,n){if(e.kind!==t.kind)return e.kind==="directory"?-1:1;let o=jti(e.path),s=jti(t.path),a=n.toLowerCase(),l=o.toLowerCase().startsWith(a),u=s.toLowerCase().startsWith(a);return l!==u?l?-1:1:e.path.localeCompare(t.path)}function jti(e){let t=e.endsWith("/")?e.slice(0,-1):e,n=t.lastIndexOf("/");return n<0?t:t.slice(n+1)}function Wrc(e,t){let n=(0,pN.relative)(e,t);if(!(!n||n.startsWith("..")||(0,pN.isAbsolute)(n)))return n.split(pN.sep).join("/")}function Vrc(e,t){let n=(0,pN.relative)(e,t);return n===""||!n.startsWith("..")&&!(0,pN.isAbsolute)(n)}var pN,Frc,jrc,Brc,Urc,Uti=Y(()=>{"use strict";yme();pN=require("node:path"),Frc=50,jrc=/[\\/]+/gu,Brc=/^[a-zA-Z]:[\\/]/u,Urc=new Set([".bzr",".git",".hg",".jj",".sl",".svn","node_modules"]);r(Bti,"createWorkspacePathSuggestionProvider");r(zrc,"parseWorkspacePathToken");r($rc,"matchesPathQuery");r(qrc,"compareWorkspacePathSuggestion");r(jti,"basenameFromSuggestion");r(Wrc,"toWorkspaceRelativePath");r(Vrc,"isPathInside")});async function $ti(e){let t=e.maxOutputBytes??Krc,n=e.timeoutMs??Jrc,s=await(e.runCommand??Yrc)(Hrc,["-C",e.workspaceDirectory,...Grc],{maxOutputBytes:t,timeoutMs:n}).catch(()=>({exitCode:-1,stdout:""}));if(s.exitCode!==0)return;let a=s.stdout.trim().split(/\r?\n/,1)[0]?.trim();if(!(!a||a===Zrc))return a}async function Yrc(e,t,n){return await new Promise(o=>{let s;try{s=(0,zti.spawn)(e,t,{stdio:["ignore","pipe","ignore"],windowsHide:!0})}catch{o({exitCode:-1,stdout:""});return}let a="",l=!1,u=setTimeout(()=>{s.kill(),f({exitCode:-1,stdout:a})},n.timeoutMs),f=r(g=>{l||(l=!0,clearTimeout(u),o(g))},"finish");s.stdout?.on("data",g=>{a+=g.toString("utf8"),Buffer.byteLength(a,"utf8")>n.maxOutputBytes&&(s.kill(),f({exitCode:-1,stdout:a}))}),s.on("error",()=>f({exitCode:-1,stdout:a})),s.on("close",g=>f({exitCode:g,stdout:a}))})}var zti,Hrc,Grc,Jrc,Krc,Zrc,qti=Y(()=>{"use strict";zti=require("node:child_process"),Hrc="git",Grc=["symbolic-ref","--quiet","--short","HEAD"],Jrc=750,Krc=512,Zrc="HEAD";r($ti,"resolveWorkspaceGitBranch");r(Yrc,"runGitCommand")});var Wti,Vti=Y(()=>{"use strict";ms();oti();ati();ETt();Tde();j2n();CTt();Eti();Nti();Fti();Uti();qti();B2n();Wti=r(async(e,t,n,o,s,a,l,u=!1)=>{try{let f=Tti(s),g=n.runTui??(await Mti()).runTui,_=(n.cwd??process.cwd)(),b=n.env??process.env,w=OCe(b)==="development",T=await(n.resolveWorkspaceGitBranch??$ti)({workspaceDirectory:_}).catch(()=>{}),I=Lti({deps:n,options:t,workingDirectory:_}),E=Cti(n,f,o,a,t.locale,t.detectedLocale,I,l,u,t.browserUse,t.browserExecutable),R=rGe({cleanup:r(async()=>{await E.close?.()},"cleanup"),cleanupTimeoutMs:n.shutdownCleanupTimeoutMs,exitProcess:n.exitProcess,process:n.shutdownProcess});try{let L=await fei(n),U=L?{locale:I}:await dti(E),B=L||!U.model?[]:await E.listModelOptions?.().catch(()=>[]),z=L||!U.model?[]:await E.listEffortOptions?.().catch(()=>[]),$=await BTt(n).catch(()=>{});return await g({initialMode:XK(f),initialModel:U.model,initialThoughtLevel:U.thoughtLevel,loginRequired:L,locale:U.locale??I,theme:U.theme??"auto",developerMode:w,version:o,workspaceDirectory:_,workspaceGitBranch:T,noColor:t.noColor,readClipboardImage:n.readClipboardImage??tti(),effortOptions:z,modelOptions:B,listWorkspacePathSuggestions:Bti({workspaceDirectory:_}),listMcpServers:E.listMcpServers,listWorkflowRuns:E.listWorkflowRuns,replayWorkflowRuns:E.replayWorkflowRuns,reduceWorkflowRuns:($zState,$zEvent)=>{zhr();return oQe($zState,$zEvent)},getMainSessionId:E.getMainSessionId,writeClipboardText:n.writeClipboardText??sti({stdout:e.stdout}),stderr:e.stderr,stdin:e.stdin,stdout:e.stdout,loadSessionTranscript:E.loadSessionTranscript,loadSessionContextMessages:E.loadSessionContextMessages,readGoal:E.readGoal,readTodos:E.readTodos,readRuntimeProjection:E.readRuntimeProjection,readSessionUsage:E.readSessionUsage,cancelBackgroundTask:E.cancelBackgroundTask,previewFileRewind:E.previewFileRewind,applyFileRewind:E.applyFileRewind,setCustomSessionTitle:E.setCustomSessionTitle,readCustomSessionTitle:E.readCustomSessionTitle,interruptTurn:E.interruptTurn,promoteQueuedInput:E.promoteQueuedInput,listSkills:E.listSkills,readDefaultModel:E.readDefaultModel,setDefaultModel:E.setDefaultModel,reloadModelOptions:E.reloadModelOptions,listModelOptions:E.listModelOptions,readExecutionState:E.readExecutionState,setPlanEnabled:E.setPlanEnabled,setTransientModel:E.setTransientModel,readSessionModel:E.readSessionModel,sendBackgroundTaskMessage:E.sendBackgroundTaskMessage,recallPreviousInput:E.recallPreviousInput,sendInput:E.sendInput,setMode:E.setMode,slashCommands:v2n($),submitPrompt:E,subscribeSessionEvents:E.subscribeSessionEvents})}finally{R(),await E.close?.()}}catch(f){let g=f instanceof Error?f.message:String(f);return e.stderr.write(`Error: ${g}
15419
15419
  `),t.verbose&&f instanceof Error&&f.stack&&e.stderr.write(`${f.stack}
15420
15420
  `),1}},"runTuiCommand")});var Jti={};Ng(Jti,{run:()=>Toc});var S9,Xrc,Qrc,eoc,toc,noc,roc,ooc,ioc,soc,aoc,coc,zTt,Hti,loc,uoc,Gti,doc,poc,foc,moc,hoc,goc,_oc,yoc,voc,boc,Soc,woc,UTt,koc,xoc,Toc,Kti=Y(()=>{"use strict";Dqt();adt();Y0();Y0();eN();jQ();L2o();WXo();XRn();b9();ZXo();oQo();cQo();n2n();F8t();X8t();mQo();jei();Xei();P2n();Vti();S9="0.16.9",Xrc="--target requires non-empty text.",Qrc="yolo",eoc="--force-mcs can only be used with --prompt, --target, or tui.",toc="--target-replace requires --target.",noc='--target cannot be used with --prompt. Use either --target <objective> or --prompt "/goal <objective>".',roc=new Set(["--disallowedTools","--disallowed-tools"]),ooc="--browser-executable requires --browser-use=headless.",ioc="--browser-use=headless can only be used with --prompt, --target, or tui.",soc="--surface can only be used with --prompt, --target, app-server, or agent-server.",aoc="--memory-bench can only be used with -p/--prompt.",coc=r(e=>({...e.all===!0?{all:!0}:{},...e.available===!0?{available:!0}:{},...e["keep-data"]===!0?{keepData:!0}:{},...typeof e.scope=="string"?{scope:e.scope}:{},...Array.isArray(e.sparse)?{sparse:e.sparse}:{}}),"pluginsCommandFlags"),zTt=r(e=>e[0]??"tui","commandName"),Hti=r(e=>typeof e.prompt=="string"||e.targetRequest!==void 0||zTt(e.positionals)==="tui","isForceMcsSupportedInvocation"),loc=r(e=>{let t=zTt(e.positionals);return typeof e.prompt=="string"||e.targetRequest!==void 0||t==="app-server"||t==="agent-server"},"isPresentationSurfaceSupportedInvocation"),uoc=r((e,t,n,o,s,a)=>({browserExecutable:s,browserUse:o,detectedLocale:n,force:e.force===!0,json:e.json===!0,locale:t,...e["memory-bench"]===!0?{memoryBench:!0}:{},noColor:e["no-color"]===!0,...a?{outputFormat:a}:{},verbose:e.verbose===!0}),"globalOptions"),Gti=["text","json","stream-json"],doc=r(e=>{if(e!==void 0){if(Gti.includes(e))return e;throw new Error(`--output-format must be one of ${Gti.join(", ")} (received: ${e}).`)}},"normalizeOutputFormat"),poc=r(e=>{if(e!==void 0){if(L6e(e))return e;throw new Error(S4().cli.errors.localeUnsupported(e))}},"normalizeLocaleOption"),foc=r(e=>{if(e===void 0)return;let t=e.toLowerCase();if(t==="build"||t==="edit"||t==="yolo")return t;throw new Error(`Unsupported --mode value: ${e}. Supported modes: build, edit, yolo. Use /plan in the TUI to toggle planning.`)},"normalizePromptMode"),moc=r(e=>{if(e!==void 0){if(e.toLowerCase()==="headless")return"headless";throw new Error(`Unsupported --browser-use value: ${e}. Supported value: headless.`)}},"normalizeBrowserUse"),hoc=r(e=>{if(e===void 0||e.toLowerCase()==="terminal")return"terminal";if(e.toLowerCase()==="desktop")return"zcode_desktop";throw new Error(`Unsupported --surface value: ${e}. Supported surfaces: terminal, desktop.`)},"normalizePresentationSurface"),goc=r(e=>{let t=[],n=[];for(let o=0;o<e.length;o+=1){let s=e[o],a=s.match(/^(--disallowedTools|--disallowed-tools)=(.*)$/);if(a){n.push(a[2]??"");continue}if(!roc.has(s)){t.push(s);continue}let l=!1;for(;o+1<e.length&&!_oc(e[o+1]);)n.push(e[o+1]),o+=1,l=!0;if(!l)throw new Error(`${s} requires at least one tool.`)}return{args:t,toolDisallowlist:yoc(n)}},"extractDisallowedToolsArgs"),_oc=r(e=>e==="--"||/^-[^-]?|^--/.test(e),"isCliOptionToken"),yoc=r(e=>{let t=[],n=new Set;for(let o of e)for(let s of voc(o)){let a=boc(s);!a||n.has(a)||(n.add(a),t.push(a))}return t.length>0?t:void 0},"normalizeCliToolRuleList"),voc=r(e=>{let t=[],n="",o=!1,s=r(()=>{let a=n.trim();a&&t.push(a),n=""},"flush");for(let a of e)switch(a){case"(":o=!0,n+=a;break;case")":o=!1,n+=a;break;case",":o?n+=a:s();break;case" ":o?n+=a:s();break;default:n+=a;break}return s(),t},"splitCliToolRules"),boc=r(e=>e?e==="web_search"?"WebSearch":e.startsWith("web_search(")?`WebSearch${e.slice(10)}`:e:"","normalizeCliToolRule"),Soc=r(e=>{let t=e.target,n=e["target-replace"]===!0;if(t===void 0){if(n)throw new Error(toc);return}let o=t.trim();if(o.length===0)throw new Error(Xrc);return{objective:o,replaceExisting:n}},"normalizeTargetRequest"),woc=r(e=>e.replaceExisting?`/goal replace ${e.objective}`:`/goal ${e.objective}`,"buildHeadlessTargetCommand"),UTt=r((e,t,n)=>{e.write(N2o(S9,t,n))},"writeHelp"),koc=r((e,t,n)=>{let o=wTn(),s={cli:{name:aZn,processName:L8t,version:S9},runtime:{arch:o.arch,cwd:n,execPath:o.execPath,node:o.node,platform:o.platform,processTitle:process.title,sea:o.sea},packaging:{default:"node-bundle",sea:"optional"}};if(t.json)return e.stdout.write(e0(s)),0;let a=bTn(e.stdout,t.noColor);return e.stdout.write(`${STn.bold("zcode doctor",a)}
15421
15421
  `),e.stdout.write(`version: ${s.cli.version}