zcode-app-cli 3.14.5-34 → 3.15.3-36

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.
Files changed (75) hide show
  1. package/README.md +13 -2
  2. package/bin/zcode.js +9 -0
  3. package/docs/CONFIGURATION.md +36 -5
  4. package/docs/CONFIGURATION.zh-CN.md +29 -3
  5. package/docs/PROVIDER_CONFIG.md +25 -0
  6. package/docs/PROVIDER_CONFIG.zh-CN.md +20 -0
  7. package/package.json +5 -3
  8. package/vendor/cli-config.cjs +88 -0
  9. package/vendor/extraction.json +24 -6
  10. package/vendor/node_modules/@zcode/tui/dist/index.js +533 -98
  11. package/vendor/packages/browser-use-plugin/README.md +1 -1
  12. package/vendor/packages/browser-use-plugin/docs/api.json +1 -1
  13. package/vendor/packages/browser-use-plugin/docs/overview.md +6 -6
  14. package/vendor/packages/browser-use-plugin/docs/playwright.md +3 -3
  15. package/vendor/packages/browser-use-plugin/docs/workflow.md +2 -2
  16. package/vendor/packages/browser-use-plugin/scripts/browser-client.mjs +5 -7
  17. package/vendor/packages/browser-use-plugin/scripts/build.mjs +0 -1
  18. package/vendor/packages/browser-use-plugin/skills/control-browser/SKILL.md +9 -9
  19. package/vendor/packages/bundled-skills/skills/dynamic-workflows/SKILL.md +760 -687
  20. package/vendor/packages/bundled-skills/skills/dynamic-workflows/examples.md +310 -1
  21. package/vendor/packages/bundled-skills/skills/dynamic-workflows/patterns.md +336 -4
  22. package/vendor/packages/documents-plugin/.zcode-plugin/plugin.json +2 -2
  23. package/vendor/packages/documents-plugin/package.json +2 -2
  24. package/vendor/packages/documents-plugin/skills/docx/LICENSE.txt +10 -10
  25. package/vendor/packages/node-repl-host/.zcode-plugin/plugin.json +1 -1
  26. package/vendor/packages/node-repl-host/dist/mcp/server.js +116 -48
  27. package/vendor/packages/node-repl-host/package.json +1 -1
  28. package/vendor/packages/node-repl-host/scripts/build.mjs +4 -4
  29. package/vendor/packages/pdf-plugin/.zcode-plugin/plugin.json +2 -2
  30. package/vendor/packages/pdf-plugin/package.json +2 -2
  31. package/vendor/packages/pdf-plugin/skills/pdf/LICENSE.txt +10 -10
  32. package/vendor/packages/pdf-plugin/skills/pdf/references/resume-altacv.tex +1 -1
  33. package/vendor/packages/plugin-creator-plugin/skills/plugin-creator/SKILL.md +1 -1
  34. package/vendor/packages/plugin-creator-plugin/skills/plugin-creator/references/plugin-json-spec.md +1 -1
  35. package/vendor/packages/presentations-plugin/.zcode-plugin/plugin.json +2 -2
  36. package/vendor/packages/presentations-plugin/package.json +2 -2
  37. package/vendor/packages/presentations-plugin/skills/pptx/LICENSE.txt +10 -10
  38. package/vendor/packages/restore-legacy-sessions-plugin/skills/restore-legacy-sessions/SKILL.md +1 -1
  39. package/vendor/packages/spreadsheets-plugin/.zcode-plugin/plugin.json +2 -2
  40. package/vendor/packages/spreadsheets-plugin/package.json +2 -2
  41. package/vendor/packages/spreadsheets-plugin/skills/xlsx/LICENSE.txt +10 -10
  42. package/vendor/packages/visualize-plugin/.zcode-plugin/plugin.json +10 -0
  43. package/vendor/packages/visualize-plugin/package.json +8 -0
  44. package/vendor/packages/visualize-plugin/skills/visualize/LICENSE.md +5 -0
  45. package/vendor/packages/visualize-plugin/skills/visualize/SKILL.md +277 -0
  46. package/vendor/packages/visualize-plugin/skills/visualize/assets/calendar.js +273 -0
  47. package/vendor/packages/visualize-plugin/skills/visualize/assets/runtime-manifest.json +16 -0
  48. package/vendor/packages/visualize-plugin/skills/visualize/assets/standalone-host-bridge.js +256 -0
  49. package/vendor/packages/visualize-plugin/skills/visualize/assets/standalone-shell.js +183 -0
  50. package/vendor/packages/visualize-plugin/skills/visualize/assets/vendor/d3-7.9.0.min.js +2 -0
  51. package/vendor/packages/visualize-plugin/skills/visualize/assets/vendor/d3-7.9.0.min.js.LICENSE +13 -0
  52. package/vendor/packages/visualize-plugin/skills/visualize/assets/vendor/floating-ui-core-1.7.3.min.js +1 -0
  53. package/vendor/packages/visualize-plugin/skills/visualize/assets/vendor/floating-ui-core-1.7.3.min.js.LICENSE +20 -0
  54. package/vendor/packages/visualize-plugin/skills/visualize/assets/vendor/floating-ui-dom-1.7.4.min.js +1 -0
  55. package/vendor/packages/visualize-plugin/skills/visualize/assets/vendor/floating-ui-dom-1.7.4.min.js.LICENSE +20 -0
  56. package/vendor/packages/visualize-plugin/skills/visualize/assets/vendor/lucide-1.17.0.js +19521 -0
  57. package/vendor/packages/visualize-plugin/skills/visualize/assets/vendor/lucide-1.17.0.js.LICENSE +43 -0
  58. package/vendor/packages/visualize-plugin/skills/visualize/assets/vendor/manifest.json +57 -0
  59. package/vendor/packages/visualize-plugin/skills/visualize/assets/visualize.css +1222 -0
  60. package/vendor/packages/visualize-plugin/skills/visualize/assets/visualize.html +517 -0
  61. package/vendor/packages/visualize-plugin/skills/visualize/examples/calendar.html +10 -0
  62. package/vendor/packages/visualize-plugin/skills/visualize/references/api.md +128 -0
  63. package/vendor/packages/visualize-plugin/skills/visualize/references/styles.md +3 -0
  64. package/vendor/packages/visualize-plugin/skills/visualize/scripts/render.py +248 -0
  65. package/vendor/packages/visualize-plugin/skills/visualize/scripts/vendor.py +56 -0
  66. package/vendor/packages/visualize-plugin/skills/visualize/tweak.md +62 -0
  67. package/vendor/packages/visualize-plugin/skills/visualize/widgets/calendar.md +90 -0
  68. package/vendor/packages/zcode-cua-plugin/.zcode-plugin/plugin.json +1 -1
  69. package/vendor/packages/zcode-cua-plugin/docs/computer-use.md +1 -1
  70. package/vendor/packages/zcode-cua-plugin/package.json +1 -1
  71. package/vendor/packages/zcode-cua-plugin/scripts/computer-use-client.mjs +35 -41
  72. package/vendor/packages/zcode-guide-plugin/skills/zcode-configuration-guide/SKILL.md +2 -2
  73. package/vendor/provider/zcode-builtin.json +96 -1
  74. package/vendor/zcode.cjs +1622 -1425
  75. package/zcode-runtime.lock.json +3 -3
@@ -6,6 +6,7 @@ import { access, link, mkdir, open, readFile, rename, rm, stat, writeFile } from
6
6
  import { basename, dirname, extname, isAbsolute, join, posix, resolve, sep, win32 } from "node:path";
7
7
  import { randomUUID } from "node:crypto";
8
8
  import { Box, CombinedAutocompleteProvider, Container, Editor, Image, Input, Markdown, ProcessTerminal, ScrollView, SelectList, Spacer, Text, TuiAltScreen, TuiMainScreen, VStack, decodeKittyPrintable, getKeybindings, isKeyRelease, isViewportTUI, matchesKey, truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
9
+ import { AltScreenSearchComponent } from "@earendil-works/pi-tui/dist/alt-screen-search.js";
9
10
  import { StringDecoder } from "node:string_decoder";
10
11
  import { isDeepStrictEqual } from "node:util";
11
12
  var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
@@ -393,6 +394,80 @@ async function missingCodingPlanKey(options = {}) {
393
394
  return message(providerId);
394
395
  }
395
396
  //#endregion
397
+ //#region packages/zcode-tui/src/stream-error-guard.ts
398
+ function watchStreamErrors(sources, onError) {
399
+ const uniqueSources = [...new Set(sources)];
400
+ for (const source of uniqueSources) source.on("error", onError);
401
+ let active = true;
402
+ return () => {
403
+ if (!active) return;
404
+ active = false;
405
+ for (const source of uniqueSources) source.off("error", onError);
406
+ };
407
+ }
408
+ //#endregion
409
+ //#region packages/zcode-tui/src/startup.ts
410
+ async function loadTuiStartupOptions(options) {
411
+ const loadStartupOptions = options.loadStartupOptions;
412
+ if (!loadStartupOptions) return options;
413
+ if (!process.stdin.isTTY || !process.stdout.isTTY) throw new Error("ZCode TUI requires an interactive terminal.");
414
+ const ui = new TuiMainScreen(new ProcessTerminal(), true);
415
+ const chinese = options.locale?.startsWith("zh");
416
+ ui.addChild(new Text(chinese ? "正在启动 ZCode…" : "Starting ZCode…", 1, 0));
417
+ ui.addChild(new Text(chinese ? "按 Ctrl+C 取消" : "Press Ctrl+C to cancel", 1, 0));
418
+ let cancelled = false;
419
+ let resolveCancelled;
420
+ const cancellation = new Promise((resolve) => {
421
+ resolveCancelled = () => resolve(void 0);
422
+ });
423
+ const cancel = (exitCode) => {
424
+ if (cancelled) return;
425
+ cancelled = true;
426
+ process.exitCode = exitCode;
427
+ resolveCancelled();
428
+ };
429
+ const onSigint = () => cancel(128 + constants$1.signals.SIGINT);
430
+ const onSigterm = () => cancel(128 + constants$1.signals.SIGTERM);
431
+ const onSighup = () => cancel(128 + constants$1.signals.SIGHUP);
432
+ ui.addInputListener((data) => {
433
+ if (!isKeyRelease(data) && matchesKey(data, "ctrl+c")) onSigint();
434
+ return { consume: true };
435
+ });
436
+ const removeStreamErrorGuards = watchStreamErrors([process.stdout, process.stderr], () => cancel(1));
437
+ process.once("SIGINT", onSigint);
438
+ process.once("SIGTERM", onSigterm);
439
+ if (process.platform !== "win32") process.once("SIGHUP", onSighup);
440
+ try {
441
+ ui.start();
442
+ ui.renderNow();
443
+ await new Promise((resolve) => setImmediate(resolve));
444
+ if (cancelled) return void 0;
445
+ return await Promise.race([Promise.resolve().then(async () => {
446
+ if (cancelled) return void 0;
447
+ const startup = await loadStartupOptions();
448
+ return cancelled ? void 0 : {
449
+ ...options,
450
+ ...startup
451
+ };
452
+ }), cancellation]);
453
+ } finally {
454
+ process.off("SIGINT", onSigint);
455
+ process.off("SIGTERM", onSigterm);
456
+ if (process.platform !== "win32") process.off("SIGHUP", onSighup);
457
+ try {
458
+ ui.clear();
459
+ ui.renderNow();
460
+ } finally {
461
+ try {
462
+ ui.stop();
463
+ } finally {
464
+ await new Promise((resolve) => setImmediate(resolve));
465
+ removeStreamErrorGuards();
466
+ }
467
+ }
468
+ }
469
+ }
470
+ //#endregion
396
471
  //#region packages/zcode-tui/src/prompt-preflight.ts
397
472
  /** Preserve rejected input without replacing a draft typed during validation. */
398
473
  async function preflightSubmission(options) {
@@ -153805,6 +153880,15 @@ function removeLastGrapheme(value) {
153805
153880
  segments.pop();
153806
153881
  return segments.join("");
153807
153882
  }
153883
+ /**
153884
+ * Drop the reverse-video SGR pair the editor and input components draw
153885
+ * around the caret grapheme (Editor resets with 0, Input with 27). Cell
153886
+ * contents and visible widths are unchanged; only the highlight goes away.
153887
+ * Input placeholders may add SGR (e.g. dim) inside the caret; retain it.
153888
+ */
153889
+ function stripCaretHighlight(text) {
153890
+ return text.replace(/\x1b\[7m((?:\x1b\[(?!(?:0|27)m)[0-9;:]*m|[^\x1b])*)\x1b\[(?:0|27)m/gu, "$1");
153891
+ }
153808
153892
  const maxHighlightCharacters = 1e5;
153809
153893
  const plainLanguages = /* @__PURE__ */ new Set([
153810
153894
  "",
@@ -157848,6 +157932,8 @@ var PromptInput = class extends Input {
157848
157932
  mask;
157849
157933
  placeholderText;
157850
157934
  theme;
157935
+ /** Read at render time so terminal focus changes need no state plumbing. */
157936
+ isTerminalFocused = () => true;
157851
157937
  constructor(mask, placeholderText, theme) {
157852
157938
  super();
157853
157939
  this.mask = mask;
@@ -157855,6 +157941,10 @@ var PromptInput = class extends Input {
157855
157941
  this.theme = theme;
157856
157942
  }
157857
157943
  render(width) {
157944
+ const lines = this.renderInput(width);
157945
+ return this.isTerminalFocused() ? lines : lines.map(stripCaretHighlight);
157946
+ }
157947
+ renderInput(width) {
157858
157948
  const value = this.getValue();
157859
157949
  if (this.mask && value) {
157860
157950
  this.setValue("*".repeat(value.length));
@@ -157876,6 +157966,8 @@ var PromptEditor = class extends Editor {
157876
157966
  placeholder;
157877
157967
  promptTheme;
157878
157968
  onEscape;
157969
+ /** Read at render time so terminal focus changes need no state plumbing. */
157970
+ isTerminalFocused = () => true;
157879
157971
  constructor(ui, placeholder, promptTheme) {
157880
157972
  super(ui, promptTheme.editor, { paddingX: 1 });
157881
157973
  this.placeholder = placeholder;
@@ -157889,6 +157981,10 @@ var PromptEditor = class extends Editor {
157889
157981
  super.handleInput(data);
157890
157982
  }
157891
157983
  render(width) {
157984
+ const lines = this.renderEditor(width);
157985
+ return this.isTerminalFocused() ? lines : lines.map(stripCaretHighlight);
157986
+ }
157987
+ renderEditor(width) {
157892
157988
  const lines = super.render(width);
157893
157989
  if (this.getText() || !this.placeholder) return lines;
157894
157990
  const cursor = "\x1B[7m \x1B[0m";
@@ -157900,7 +157996,9 @@ var PromptEditor = class extends Editor {
157900
157996
  function promptText(ui, host, theme, options) {
157901
157997
  return new Promise((resolve) => {
157902
157998
  const placeholder = options.placeholder ? sanitizeTerminalText(options.placeholder, { preserveSgr: false }) : void 0;
157999
+ const isTerminalFocused = options.isTerminalFocused ?? (() => true);
157903
158000
  const input = options.mask === true ? new PromptInput(true, placeholder, theme) : new PromptEditor(ui, placeholder, theme);
158001
+ input.isTerminalFocused = isTerminalFocused;
157904
158002
  if (options.initialValue) if (input instanceof PromptEditor) input.setText(options.initialValue);
157905
158003
  else input.setValue(options.initialValue);
157906
158004
  const dialog = new TextPromptDialog(sanitizeTerminalText(options.title, { preserveSgr: false }), sanitizeTerminalText(options.prompt, { preserveSgr: false }), input, theme, sanitizeTerminalText(options.help ?? "Enter confirm · Esc cancel", { preserveSgr: false }));
@@ -158418,8 +158516,11 @@ var PlanEditor = class extends Editor {
158418
158516
  planColor = (text) => text;
158419
158517
  planHint = "Research and plan before making changes";
158420
158518
  hintColor = (text) => text;
158519
+ /** Read at render time so terminal focus changes need no state plumbing. */
158520
+ isTerminalFocused = () => true;
158421
158521
  render(width) {
158422
- const lines = super.render(width);
158522
+ let lines = super.render(width);
158523
+ if (!this.isTerminalFocused()) lines = lines.map(stripCaretHighlight);
158423
158524
  if (!this.planEnabled || width < 4 || !lines[0]) return lines;
158424
158525
  const label = width >= 10 ? " Plan ──" : "Plan";
158425
158526
  const prefixWidth = width - visibleWidth(label);
@@ -160673,9 +160774,9 @@ function permissionRuleContent(input) {
160673
160774
  if (value) return value;
160674
160775
  }
160675
160776
  }
160676
- function defaultPermissionChoices(toolName, input) {
160777
+ function defaultPermissionChoices(toolName, input, approvalMode) {
160677
160778
  const ruleContent = permissionRuleContent(input);
160678
- return [
160779
+ const choices = [
160679
160780
  {
160680
160781
  value: "allow_once",
160681
160782
  label: "Allow once",
@@ -160717,6 +160818,7 @@ function defaultPermissionChoices(toolName, input) {
160717
160818
  }
160718
160819
  }
160719
160820
  ];
160821
+ return approvalMode === "user-once" ? choices.filter((choice) => choice.value === "allow_once" || choice.value === "deny") : choices;
160720
160822
  }
160721
160823
  function planText$1(input) {
160722
160824
  if (typeof input === "string") return input.trim() || void 0;
@@ -161760,6 +161862,7 @@ async function requestAppServer(request) {
161760
161862
  if (envelope?.error) throw new AppServerRequestError(envelope.error.message?.trim() || "App-server request failed.", envelope.error.code, envelope.error.data);
161761
161863
  if (code !== 0) throw processError(stderr.trim() || `App-server exited with status ${code}.`, code);
161762
161864
  if (!envelope || !("result" in envelope)) throw new Error(stderr.trim() || "App-server did not return a response envelope.");
161865
+ if (stderr) request.onStderr?.(stderr);
161763
161866
  return envelope.result;
161764
161867
  } finally {
161765
161868
  if (forceTerminationTimer) clearTimeout(forceTerminationTimer);
@@ -162227,7 +162330,6 @@ var TurnNotifier = class {
162227
162330
  settings;
162228
162331
  active = false;
162229
162332
  focusReporting = false;
162230
- focusReportingRequired;
162231
162333
  terminalFocus = "unknown";
162232
162334
  terminalUnavailable = false;
162233
162335
  constructor(options) {
@@ -162236,7 +162338,6 @@ var TurnNotifier = class {
162236
162338
  this.platform = options.platform ?? process.platform;
162237
162339
  this.nativeNotify = options.nativeNotify ?? ((platform, title, body) => sendNativeNotification(platform, title, body, this.env));
162238
162340
  this.settings = options.settings ?? notificationSettings(this.env);
162239
- this.focusReportingRequired = options.focusReportingRequired === true;
162240
162341
  }
162241
162342
  start() {
162242
162343
  this.active = true;
@@ -162259,26 +162360,25 @@ var TurnNotifier = class {
162259
162360
  };
162260
162361
  }
162261
162362
  setSettings(settings) {
162262
- if (this.settings.condition !== settings.condition) this.terminalFocus = "unknown";
162263
162363
  this.settings = { ...settings };
162264
162364
  this.syncFocusReporting();
162265
162365
  }
162266
- setFocusReportingRequired(required) {
162267
- if (this.focusReportingRequired === required) return;
162268
- this.focusReportingRequired = required;
162269
- this.syncFocusReporting();
162270
- }
162271
162366
  handleInput(data) {
162272
162367
  if (data === focusIn) {
162273
- this.terminalFocus = "focused";
162368
+ this.setFocusState("focused");
162274
162369
  return true;
162275
162370
  }
162276
162371
  if (data === focusOut) {
162277
- this.terminalFocus = "unfocused";
162372
+ this.setFocusState("unfocused");
162278
162373
  return true;
162279
162374
  }
162280
162375
  return false;
162281
162376
  }
162377
+ setFocusState(state) {
162378
+ if (this.terminalFocus === state) return;
162379
+ this.terminalFocus = state;
162380
+ this.options.onFocusChange?.(state);
162381
+ }
162282
162382
  async notify(kind, detail = "") {
162283
162383
  if (this.settings.method === "off" || this.settings.condition === "unfocused" && this.terminalFocus === "focused") return false;
162284
162384
  const fallback = kind === "completed" ? "Agent turn complete" : "Agent turn failed";
@@ -162321,7 +162421,7 @@ var TurnNotifier = class {
162321
162421
  }
162322
162422
  }
162323
162423
  syncFocusReporting() {
162324
- if (!this.active || !this.focusReportingRequired && (this.settings.method === "off" || this.settings.condition !== "unfocused")) {
162424
+ if (!this.active) {
162325
162425
  this.disableFocusReporting();
162326
162426
  return;
162327
162427
  }
@@ -162335,18 +162435,6 @@ var TurnNotifier = class {
162335
162435
  }
162336
162436
  };
162337
162437
  //#endregion
162338
- //#region packages/zcode-tui/src/stream-error-guard.ts
162339
- function watchStreamErrors(sources, onError) {
162340
- const uniqueSources = [...new Set(sources)];
162341
- for (const source of uniqueSources) source.on("error", onError);
162342
- let active = true;
162343
- return () => {
162344
- if (!active) return;
162345
- active = false;
162346
- for (const source of uniqueSources) source.off("error", onError);
162347
- };
162348
- }
162349
- //#endregion
162350
162438
  //#region packages/zcode-tui/src/tui-mode.ts
162351
162439
  function record$1(value) {
162352
162440
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
@@ -162428,6 +162516,49 @@ function emitSessionTerminalTitle(stream, title) {
162428
162516
  stream.write(safeTitle ? `\x1b]0;${SESSION_TITLE_PREFIX}${safeTitle}\x07` : "\x1B]0;\x07");
162429
162517
  }
162430
162518
  //#endregion
162519
+ //#region packages/zcode-tui/src/shortcuts.ts
162520
+ const modes = [
162521
+ "build",
162522
+ "edit",
162523
+ "guarded",
162524
+ "yolo"
162525
+ ];
162526
+ function normalizedMode(mode, fallback = "build") {
162527
+ const candidate = mode;
162528
+ return modes.includes(candidate) ? candidate : fallback;
162529
+ }
162530
+ function nextMode(currentMode) {
162531
+ const currentIndex = modes.indexOf(currentMode);
162532
+ return modes[(currentIndex + 1) % modes.length] ?? modes[0];
162533
+ }
162534
+ function settingTargetForCommand(input) {
162535
+ const command = /^\/([^\s]+)/u.exec(input.trim())?.[1]?.toLowerCase();
162536
+ if (command === "mode") return "mode";
162537
+ if (command === "model") return "model";
162538
+ if (command === "effort" || command === "variant") return "effort";
162539
+ }
162540
+ function appliesToSetting(target, field) {
162541
+ return target === void 0 || target === field;
162542
+ }
162543
+ function nextPickerCommand(picker, currentValue) {
162544
+ if (picker.items.length < 2) return void 0;
162545
+ const currentIndex = picker.items.findIndex((item) => item.value === currentValue);
162546
+ const nextIndex = currentIndex < 0 ? 0 : (currentIndex + 1) % picker.items.length;
162547
+ return picker.items[nextIndex]?.command;
162548
+ }
162549
+ /** Like nextPickerCommand but returns the item value (model id) directly. */
162550
+ function nextPickerValue(picker, currentValue) {
162551
+ if (picker.items.length < 2) return void 0;
162552
+ const currentIndex = picker.items.findIndex((item) => item.value === currentValue);
162553
+ const nextIndex = currentIndex < 0 ? 0 : (currentIndex + 1) % picker.items.length;
162554
+ return picker.items[nextIndex]?.value;
162555
+ }
162556
+ function transcriptPageDirection(data) {
162557
+ if (isKeyRelease(data)) return void 0;
162558
+ if (matchesKey(data, "pageUp") || matchesKey(data, "left")) return -1;
162559
+ if (matchesKey(data, "pageDown") || matchesKey(data, "right")) return 1;
162560
+ }
162561
+ //#endregion
162431
162562
  //#region packages/zcode-tui/src/selectors.ts
162432
162563
  function pickerRequest(input, commands) {
162433
162564
  const match = /^\/([^\s]+)(?:\s+(.*))?$/u.exec(input.trim());
@@ -162442,18 +162573,10 @@ function isModePickerRequest(input) {
162442
162573
  return pickerRequest(input, /* @__PURE__ */ new Set(["mode"]));
162443
162574
  }
162444
162575
  function modePicker(currentMode, availableModes) {
162445
- const items = (availableModes?.length ? availableModes : [
162446
- "build",
162447
- "edit",
162448
- "yolo"
162449
- ]).filter((mode) => [
162450
- "build",
162451
- "edit",
162452
- "yolo"
162453
- ].includes(mode)).map((mode) => ({
162576
+ const items = (availableModes?.length ? availableModes : modes).filter((mode) => modes.includes(mode)).map((mode) => ({
162454
162577
  value: mode,
162455
162578
  label: mode.charAt(0).toUpperCase() + mode.slice(1),
162456
- description: [mode === "build" ? "Ask before changes" : mode === "edit" ? "Edit automatically" : "Full access", mode === currentMode ? "current" : void 0].filter(Boolean).join(" · "),
162579
+ description: [mode === "build" ? "Ask before changes" : mode === "edit" ? "Edit automatically" : mode === "guarded" ? "Autonomous · ask before risky commands" : "Full access", mode === currentMode ? "current" : void 0].filter(Boolean).join(" · "),
162457
162580
  command: `/mode ${mode}`
162458
162581
  }));
162459
162582
  const currentIndex = items.findIndex((item) => item.value === currentMode);
@@ -163473,7 +163596,7 @@ var DynamicWorkflows = class {
163473
163596
  return operation;
163474
163597
  }
163475
163598
  };
163476
- function safe(value) {
163599
+ function safe$1(value) {
163477
163600
  return sanitizeTerminalText(typeof value === "string" ? value : "", { preserveSgr: false }).slice(0, 2e3);
163478
163601
  }
163479
163602
  function workflowRunDetail(run) {
@@ -163481,18 +163604,290 @@ function workflowRunDetail(run) {
163481
163604
  const actors = Array.isArray(run.actors) ? run.actors.filter(isRecord) : [];
163482
163605
  const artifacts = Array.isArray(run.artifacts) ? run.artifacts.filter(isRecord) : [];
163483
163606
  const usage = isRecord(run.usage) ? run.usage : void 0;
163484
- const lines = [safe(run.label) || safe(run.runId), `Status: ${safe(run.status) || "unknown"}${run.stopReason ? ` · ${safe(run.stopReason)}` : ""}`];
163607
+ const lines = [safe$1(run.label) || safe$1(run.runId), `Status: ${safe$1(run.status) || "unknown"}${run.stopReason ? ` · ${safe$1(run.stopReason)}` : ""}`];
163485
163608
  if (run.progressIncomplete === true) lines.push("Progress is incomplete. Use /dwf list for runtime status.");
163486
163609
  if (nodes) lines.push(`Steps: ${nodes.filter((node) => node.phase === "settled").length}/${nodes.length} observed steps settled`);
163487
163610
  if (typeof usage?.spentTokens === "number") lines.push(`Tokens: ${usage.spentTokens.toLocaleString()}`);
163488
163611
  if (run.resumable === true) lines.push("This run can be resumed.");
163489
- if (actors.length) lines.push("", "Agents", ...actors.slice(0, 12).map((actor) => `${safe(actor.name) || safe(actor.sessionId) || "Agent"} · ${safe(actor.status)}`));
163490
- if (artifacts.length) lines.push("", "Artifacts", ...artifacts.slice(0, 12).map((artifact) => safe(artifact.title) || safe(artifact.artifactId) || safe(artifact.id)));
163491
- if (asString(run.error)) lines.push("", `Error: ${safe(run.error)}`);
163492
- if (asString(run.resultPreview)) lines.push("", safe(run.resultPreview));
163612
+ const concurrency = isRecord(run.concurrency) ? run.concurrency : void 0;
163613
+ if (concurrency) lines.push(`Concurrency: ${concurrency.cap} shared · ${concurrency.limit ?? concurrency.ceiling} run limit`);
163614
+ else if (typeof run.concurrencyCeiling === "number") lines.push(`Concurrency: default ${run.concurrencyCeiling}`);
163615
+ if (typeof run.subagentModel === "string") lines.push(`Subagent default model: ${safe$1(run.subagentModel)}`);
163616
+ if (actors.length) lines.push("", "Agents", ...actors.slice(0, 12).map((actor) => [
163617
+ safe$1(actor.name) || safe$1(actor.sessionId) || "Agent",
163618
+ safe$1(actor.status),
163619
+ safe$1(actor.model) || safe$1(run.subagentModel) || "session model"
163620
+ ].filter(Boolean).join(" · ")));
163621
+ if (artifacts.length) lines.push("", "Artifacts", ...artifacts.slice(0, 12).map((artifact) => safe$1(artifact.title) || safe$1(artifact.artifactId) || safe$1(artifact.id)));
163622
+ if (asString(run.error)) lines.push("", `Error: ${safe$1(run.error)}`);
163623
+ if (asString(run.resultPreview)) lines.push("", safe$1(run.resultPreview));
163493
163624
  return lines.join("\n");
163494
163625
  }
163495
163626
  //#endregion
163627
+ //#region packages/zcode-tui/src/workflow-management.ts
163628
+ function safe(value) {
163629
+ return sanitizeTerminalText(asString(value) ?? "", { preserveSgr: false }).slice(0, 2e3);
163630
+ }
163631
+ function workflowAdjustableSettings(toolName, input) {
163632
+ if (toolName !== "CreateWorkflow" && toolName !== "AmendWorkflow") return void 0;
163633
+ if (!isRecord(input) || !isRecord(input.adjustable_settings)) return void 0;
163634
+ return typeof input.adjustable_settings.subagent_model === "boolean" ? input.adjustable_settings : void 0;
163635
+ }
163636
+ function workflowSettingsSummary(input, adjustment = {}) {
163637
+ const settings = isRecord(input.adjustable_settings) ? input.adjustable_settings : {};
163638
+ const concurrency = adjustment.max_concurrency !== void 0 ? adjustment.max_concurrency : input.max_concurrency;
163639
+ const model = adjustment.subagent_model !== void 0 ? adjustment.subagent_model : input.subagent_model;
163640
+ const defaultConcurrency = typeof settings.concurrency_ceiling === "number" ? ` (${settings.concurrency_ceiling})` : "";
163641
+ return [
163642
+ `Concurrency: ${typeof concurrency === "number" ? concurrency : `default${defaultConcurrency}`}`,
163643
+ `Subagent default model: ${safe(model) || "session model"}`,
163644
+ ...isRecord(input.model_bindings) && Object.keys(input.model_bindings).length ? ["Models explicitly named in the script remain unchanged.", ...Object.entries(input.model_bindings).slice(0, 12).map(([name, reference]) => `${safe(name)} → ${safe(reference)}`)] : []
163645
+ ].join("\n");
163646
+ }
163647
+ async function promptWorkflowConcurrency(dialogs, signal) {
163648
+ while (!signal?.aborted && dialogs.isCurrent()) {
163649
+ const value = await dialogs.prompt({
163650
+ title: "Workflow concurrency",
163651
+ prompt: "Enter a positive integer, or default to restore the runtime default.",
163652
+ signal
163653
+ });
163654
+ if (value === null || signal?.aborted || !dialogs.isCurrent()) return void 0;
163655
+ const trimmed = value.trim();
163656
+ if (trimmed.toLowerCase() === "default") return null;
163657
+ const concurrency = Number(trimmed);
163658
+ if (/^[0-9]+$/u.test(trimmed) && Number.isSafeInteger(concurrency) && concurrency > 0) return concurrency;
163659
+ dialogs.notice("Enter a positive whole number, or default.", "warning");
163660
+ }
163661
+ }
163662
+ async function requestWorkflowApproval(request, dialogs, preview, signal) {
163663
+ const input = isRecord(request.input) ? request.input : {};
163664
+ const settings = workflowAdjustableSettings(String(request.toolName), input);
163665
+ const adjustment = {};
163666
+ while (!signal?.aborted && dialogs.isCurrent()) {
163667
+ const content = new Container();
163668
+ content.addChild(new Text(workflowSettingsSummary(input, adjustment), 0, 0));
163669
+ if (preview) content.addChild(preview);
163670
+ const choice = await dialogs.choose({
163671
+ title: `Approve ${safe(request.toolName)}`,
163672
+ prompt: "Review settings before allowing this workflow.",
163673
+ content,
163674
+ signal,
163675
+ numberShortcuts: true,
163676
+ filterMode: "substring",
163677
+ items: [
163678
+ {
163679
+ value: "allow",
163680
+ label: "Allow once",
163681
+ description: "Apply these settings to this workflow only"
163682
+ },
163683
+ {
163684
+ value: "deny",
163685
+ label: "Deny"
163686
+ },
163687
+ {
163688
+ value: "concurrency",
163689
+ label: "Change concurrency"
163690
+ },
163691
+ ...settings?.subagent_model === true ? [{
163692
+ value: "model",
163693
+ label: "Change default model"
163694
+ }] : []
163695
+ ]
163696
+ });
163697
+ if (!choice || choice.value === "deny" || signal?.aborted || !dialogs.isCurrent()) break;
163698
+ if (choice.value === "allow") return {
163699
+ decision: "allow",
163700
+ ...Object.keys(adjustment).length ? { inputAdjustments: adjustment } : {}
163701
+ };
163702
+ if (choice.value === "concurrency") {
163703
+ const value = await promptWorkflowConcurrency(dialogs, signal);
163704
+ if (value !== void 0) adjustment.max_concurrency = value;
163705
+ } else if (choice.value === "model") {
163706
+ const models = (await dialogs.models()).filter((model) => !isRecord(model) || !model.disabledReason);
163707
+ if (signal?.aborted || !dialogs.isCurrent()) break;
163708
+ const selected = await dialogs.choose({
163709
+ title: "Workflow default model",
163710
+ prompt: "Explicit per-agent models in the script are not overridden.",
163711
+ signal,
163712
+ filterMode: "substring",
163713
+ items: [{
163714
+ value: "default",
163715
+ label: "Session model",
163716
+ payload: null
163717
+ }, ...modelPicker(models).items.map((item) => ({
163718
+ ...item,
163719
+ payload: item.value
163720
+ }))]
163721
+ });
163722
+ if (selected && !signal?.aborted && dialogs.isCurrent()) adjustment.subagent_model = typeof selected.payload === "string" ? selected.payload : null;
163723
+ }
163724
+ }
163725
+ return {
163726
+ decision: "deny",
163727
+ reason: "Workflow approval cancelled"
163728
+ };
163729
+ }
163730
+ function workflowActionMessage(result, success) {
163731
+ if (!isRecord(result)) return "Workflow operation returned an invalid result.";
163732
+ if (result.ok === true) return `${success}${result.runId ? ` · ${safe(result.runId)}` : ""}${result.path ? ` · ${safe(result.path)}` : ""}${result.shadowing ? ` · ${safe(result.shadowing)}` : ""}`;
163733
+ return `Workflow operation rejected: ${safe(result.reason) || "unknown"}${result.message || result.detail ? ` · ${safe(result.message ?? result.detail)}` : ""}`;
163734
+ }
163735
+ async function retuneWorkflow(runId, adapter, dialogs) {
163736
+ const value = await promptWorkflowConcurrency(dialogs);
163737
+ if (value === void 0 || !dialogs.isCurrent() || !adapter.retuneWorkflowConcurrency) return;
163738
+ if ((await dialogs.choose({
163739
+ title: "Apply concurrency",
163740
+ prompt: "Changes only the live run. It will not stop, restart, or replace the workflow.",
163741
+ items: [{
163742
+ value: "apply",
163743
+ label: `Apply ${value === null ? "default concurrency" : `concurrency ${value}`}`
163744
+ }, {
163745
+ value: "cancel",
163746
+ label: "Cancel"
163747
+ }]
163748
+ }))?.value !== "apply" || !dialogs.isCurrent()) return;
163749
+ const result = await adapter.retuneWorkflowConcurrency({
163750
+ runId,
163751
+ maxConcurrency: value
163752
+ });
163753
+ if (dialogs.isCurrent()) dialogs.notice(workflowActionMessage(result, "Workflow concurrency updated"), isRecord(result) && result.ok === true ? "muted" : "warning");
163754
+ }
163755
+ async function saveWorkflow(run, adapter, dialogs) {
163756
+ if (!adapter.saveWorkflowRun) return;
163757
+ const name = await dialogs.prompt({
163758
+ title: "Save workflow",
163759
+ prompt: "Name: up to 64 letters, digits, dots, underscores or hyphens; no .."
163760
+ });
163761
+ if (name === null || !dialogs.isCurrent()) return;
163762
+ const trimmed = name.trim();
163763
+ if (!/^[A-Za-z0-9_.-]{1,64}$/u.test(trimmed) || trimmed.includes("..")) {
163764
+ dialogs.notice("Invalid workflow name. Nothing was saved.", "warning");
163765
+ return;
163766
+ }
163767
+ const scope = await dialogs.choose({
163768
+ title: "Save workflow scope",
163769
+ prompt: "Choose where this reusable definition is stored.",
163770
+ items: [{
163771
+ value: "project",
163772
+ label: "This project",
163773
+ description: ".zcode/workflows"
163774
+ }, {
163775
+ value: "global",
163776
+ label: "All projects",
163777
+ description: "~/.zcode/workflows"
163778
+ }]
163779
+ });
163780
+ if (!scope || !dialogs.isCurrent()) return;
163781
+ const description = await dialogs.prompt({
163782
+ title: "Workflow description",
163783
+ prompt: "Describe what this workflow does.",
163784
+ initialValue: safe(run.label)
163785
+ });
163786
+ if (!description?.trim() || !dialogs.isCurrent()) return;
163787
+ const input = {
163788
+ runId: String(run.runId),
163789
+ name: trimmed,
163790
+ scope: scope.value,
163791
+ description: description.trim()
163792
+ };
163793
+ let result = await adapter.saveWorkflowRun(input);
163794
+ if (!dialogs.isCurrent()) return;
163795
+ if (isRecord(result) && result.reason === "target_exists") {
163796
+ if ((await dialogs.choose({
163797
+ title: "Replace saved workflow?",
163798
+ prompt: safe(result.path),
163799
+ items: [{
163800
+ value: "cancel",
163801
+ label: "Keep existing definition"
163802
+ }, {
163803
+ value: "overwrite",
163804
+ label: "Replace definition",
163805
+ description: "Overwrite the existing saved script"
163806
+ }]
163807
+ }))?.value !== "overwrite" || !dialogs.isCurrent()) return;
163808
+ result = await adapter.saveWorkflowRun({
163809
+ ...input,
163810
+ overwrite: true
163811
+ });
163812
+ }
163813
+ if (dialogs.isCurrent()) dialogs.notice(workflowActionMessage(result, "Workflow saved"), isRecord(result) && result.ok === true ? "muted" : "warning");
163814
+ }
163815
+ async function showSavedWorkflows(adapter, dialogs) {
163816
+ if (!adapter.listSavedWorkflows || !adapter.readSavedWorkflow || !adapter.startSavedWorkflow) {
163817
+ dialogs.notice("Saved workflows are unavailable in this runtime.", "warning");
163818
+ return;
163819
+ }
163820
+ const listed = await adapter.listSavedWorkflows();
163821
+ if (!dialogs.isCurrent()) return;
163822
+ if (!isRecord(listed) || !Array.isArray(listed.workflows)) throw new Error("Saved workflow list is invalid.");
163823
+ const workflows = listed.workflows.filter(isRecord).filter((item) => typeof item.name === "string" && (item.scope === "project" || item.scope === "global"));
163824
+ if (Array.isArray(listed.invalid) && listed.invalid.length) dialogs.notice(`${listed.invalid.length} saved definitions could not be loaded. Fix their source files and retry.`, "warning");
163825
+ if (!workflows.length) {
163826
+ dialogs.notice("No saved workflows. Use /workflows to save a run first.", "muted");
163827
+ return;
163828
+ }
163829
+ const choice = await dialogs.choose({
163830
+ title: "Saved workflows",
163831
+ prompt: "Choose a definition to run again. This starts a new run, not a progress replay.",
163832
+ items: workflows.map((item, index) => ({
163833
+ value: String(index),
163834
+ label: `${safe(item.name)} · ${item.scope}`,
163835
+ description: safe(item.description),
163836
+ payload: item
163837
+ }))
163838
+ });
163839
+ if (!choice || !isRecord(choice.payload) || !dialogs.isCurrent()) return;
163840
+ const input = {
163841
+ name: String(choice.payload.name),
163842
+ scope: choice.payload.scope
163843
+ };
163844
+ const definition = await adapter.readSavedWorkflow(input);
163845
+ if (!dialogs.isCurrent()) return;
163846
+ if (!isRecord(definition) || definition.ok !== true) {
163847
+ dialogs.notice(workflowActionMessage(definition, ""), "warning");
163848
+ return;
163849
+ }
163850
+ const meta = isRecord(definition.meta) ? definition.meta : {};
163851
+ const declarations = isRecord(meta.args) ? meta.args : {};
163852
+ const parameterHelp = Object.entries(declarations).slice(0, 32).map(([name, declaration]) => {
163853
+ const details = isRecord(declaration) ? declaration : {};
163854
+ return `${safe(name)}: ${safe(details.type)}${details.required === true ? " (required)" : ""}${details.description ? ` · ${safe(details.description)}` : ""}`;
163855
+ }).join("\n");
163856
+ let args;
163857
+ if (Object.keys(declarations).length) while (dialogs.isCurrent()) {
163858
+ const text = await dialogs.prompt({
163859
+ title: "Workflow arguments",
163860
+ prompt: `${parameterHelp}\nEnter a JSON object. {} uses declared defaults.`,
163861
+ initialValue: "{}"
163862
+ });
163863
+ if (text === null || !dialogs.isCurrent()) return;
163864
+ try {
163865
+ const value = JSON.parse(text);
163866
+ if (!isRecord(value)) throw new Error("Arguments must be a JSON object.");
163867
+ args = value;
163868
+ break;
163869
+ } catch {
163870
+ dialogs.notice("Enter a valid JSON object, such as {}.", "warning");
163871
+ }
163872
+ }
163873
+ if ((await dialogs.choose({
163874
+ title: "Run saved workflow",
163875
+ prompt: `${safe(input.name)} · ${input.scope}\nStarts a new run and may consume model credits. Runtime validates parameters and models before execution.`,
163876
+ items: [{
163877
+ value: "cancel",
163878
+ label: "Cancel"
163879
+ }, {
163880
+ value: "run",
163881
+ label: "Run workflow"
163882
+ }]
163883
+ }))?.value !== "run" || !dialogs.isCurrent()) return;
163884
+ const result = await adapter.startSavedWorkflow({
163885
+ ...input,
163886
+ ...args ? { args } : {}
163887
+ });
163888
+ if (dialogs.isCurrent()) dialogs.notice(workflowActionMessage(result, "Saved workflow started"), isRecord(result) && result.ok === true ? "muted" : "warning");
163889
+ }
163890
+ //#endregion
163496
163891
  //#region packages/zcode-tui/src/runtime-context-cache.ts
163497
163892
  /** A session-scoped, invalidatable summary of persisted request usage. */
163498
163893
  var RuntimeContextCache = class {
@@ -163768,48 +164163,6 @@ function skillDescription(candidate) {
163768
164163
  return description ? truncateGraphemes(description, skillDescriptionLimit) : void 0;
163769
164164
  }
163770
164165
  //#endregion
163771
- //#region packages/zcode-tui/src/shortcuts.ts
163772
- const modes = [
163773
- "build",
163774
- "edit",
163775
- "yolo"
163776
- ];
163777
- function normalizedMode(mode, fallback = "build") {
163778
- const candidate = mode;
163779
- return modes.includes(candidate) ? candidate : fallback;
163780
- }
163781
- function nextMode(currentMode) {
163782
- const currentIndex = modes.indexOf(currentMode);
163783
- return modes[(currentIndex + 1) % modes.length] ?? modes[0];
163784
- }
163785
- function settingTargetForCommand(input) {
163786
- const command = /^\/([^\s]+)/u.exec(input.trim())?.[1]?.toLowerCase();
163787
- if (command === "mode") return "mode";
163788
- if (command === "model") return "model";
163789
- if (command === "effort" || command === "variant") return "effort";
163790
- }
163791
- function appliesToSetting(target, field) {
163792
- return target === void 0 || target === field;
163793
- }
163794
- function nextPickerCommand(picker, currentValue) {
163795
- if (picker.items.length < 2) return void 0;
163796
- const currentIndex = picker.items.findIndex((item) => item.value === currentValue);
163797
- const nextIndex = currentIndex < 0 ? 0 : (currentIndex + 1) % picker.items.length;
163798
- return picker.items[nextIndex]?.command;
163799
- }
163800
- /** Like nextPickerCommand but returns the item value (model id) directly. */
163801
- function nextPickerValue(picker, currentValue) {
163802
- if (picker.items.length < 2) return void 0;
163803
- const currentIndex = picker.items.findIndex((item) => item.value === currentValue);
163804
- const nextIndex = currentIndex < 0 ? 0 : (currentIndex + 1) % picker.items.length;
163805
- return picker.items[nextIndex]?.value;
163806
- }
163807
- function transcriptPageDirection(data) {
163808
- if (isKeyRelease(data)) return void 0;
163809
- if (matchesKey(data, "pageUp") || matchesKey(data, "left")) return -1;
163810
- if (matchesKey(data, "pageDown") || matchesKey(data, "right")) return 1;
163811
- }
163812
- //#endregion
163813
164166
  //#region packages/zcode-tui/src/status-line.ts
163814
164167
  var StatusLine = class {
163815
164168
  fields = [];
@@ -166220,6 +166573,16 @@ var ZCodeAltScreen = class extends TuiAltScreen {
166220
166573
  setCurrentInput(data) {
166221
166574
  this.currentInput = data;
166222
166575
  }
166576
+ showOverlay(component, options) {
166577
+ if (component instanceof AltScreenSearchComponent) {
166578
+ const render = component.render.bind(component);
166579
+ component.render = (width) => {
166580
+ const lines = render(width);
166581
+ return this.getShowHardwareCursor() ? lines : lines.map(stripCaretHighlight);
166582
+ };
166583
+ }
166584
+ return super.showOverlay(component, options);
166585
+ }
166223
166586
  /**
166224
166587
  * The terminal can lose visible rows while this process is unfocused even
166225
166588
  * though pi-tui's logical frame remains unchanged. Invalidate its
@@ -166334,6 +166697,7 @@ var ZCodeTui = class {
166334
166697
  executionStateRevision = 0;
166335
166698
  model;
166336
166699
  tuiMode;
166700
+ terminalFocus = "unknown";
166337
166701
  copyOnSelect = true;
166338
166702
  thoughtLevel;
166339
166703
  modelOptions;
@@ -166429,7 +166793,10 @@ var ZCodeTui = class {
166429
166793
  this.ui = this.createTui(this.tuiMode);
166430
166794
  this.notifications = new TurnNotifier({
166431
166795
  writeTerminal: (data) => this.ui.terminal.write(data),
166432
- focusReportingRequired: this.tuiMode === "fullscreen"
166796
+ onFocusChange: (state) => {
166797
+ this.terminalFocus = state;
166798
+ this.applyTerminalFocus();
166799
+ }
166433
166800
  });
166434
166801
  this.status = new StatusLine();
166435
166802
  this.turnStatus = new FooterBar();
@@ -166484,7 +166851,6 @@ var ZCodeTui = class {
166484
166851
  if (effective !== this.tuiMode) {
166485
166852
  this.ui = this.createTui(effective);
166486
166853
  this.tuiMode = effective;
166487
- this.notifications.setFocusReportingRequired(effective === "fullscreen");
166488
166854
  this.editor = this.createEditor(this.ui);
166489
166855
  }
166490
166856
  } catch {}
@@ -166593,6 +166959,17 @@ var ZCodeTui = class {
166593
166959
  this.copyOnSelect = enabled;
166594
166960
  this.fullscreenAltScreen?.setCopyOnSelect(enabled);
166595
166961
  }
166962
+ /**
166963
+ * Mirror terminal focus onto the hardware cursor so multiplexer panes
166964
+ * (tmux/windows-style splits) only show a live cursor in the focused pane;
166965
+ * the state flip also schedules the render that re-evaluates the drawn
166966
+ * carets (editor and prompt inputs read isTerminalFocused at render time).
166967
+ * "unknown" keeps the cursor visible; terminals without focus reports
166968
+ * (mode 1004) never report focus loss in the first place.
166969
+ */
166970
+ applyTerminalFocus() {
166971
+ this.ui.setShowHardwareCursor(this.terminalFocus !== "unfocused");
166972
+ }
166596
166973
  createTui(mode) {
166597
166974
  let fullscreenTui;
166598
166975
  const terminal = new NotifyingProcessTerminal((data) => {
@@ -166755,6 +167132,7 @@ var ZCodeTui = class {
166755
167132
  editor.planEnabled = this.planEnabled;
166756
167133
  editor.planColor = this.theme.accent;
166757
167134
  editor.hintColor = this.theme.muted;
167135
+ editor.isTerminalFocused = () => this.terminalFocus !== "unfocused";
166758
167136
  if (this.options.locale?.startsWith("zh")) editor.planHint = "先调研与规划,再开始修改";
166759
167137
  for (const input of [...this.editorHistory].reverse()) editor.addToHistory(input);
166760
167138
  const commands = this.autocompleteCommands();
@@ -166791,7 +167169,6 @@ var ZCodeTui = class {
166791
167169
  this.ui.stop({ preserveScreen: true });
166792
167170
  this.ui = this.createTui(next);
166793
167171
  this.tuiMode = next;
166794
- this.notifications.setFocusReportingRequired(next === "fullscreen");
166795
167172
  this.sessionHasContent = hadSessionContent;
166796
167173
  this.fullscreenWelcomeVisible = !hadSessionContent;
166797
167174
  this.fullscreenHeader.setPhase(hadSessionContent ? "rail" : "welcome");
@@ -166805,6 +167182,7 @@ var ZCodeTui = class {
166805
167182
  if (savedDraft) this.editor.setText(savedDraft);
166806
167183
  this.ui.requestRender(true);
166807
167184
  this.notifications.start();
167185
+ this.applyTerminalFocus();
166808
167186
  try {
166809
167187
  await writeTuiMode(next);
166810
167188
  } catch (error) {
@@ -166817,7 +167195,6 @@ var ZCodeTui = class {
166817
167195
  } catch {}
166818
167196
  this.ui = previousUi;
166819
167197
  this.tuiMode = previousMode;
166820
- this.notifications.setFocusReportingRequired(previousMode === "fullscreen");
166821
167198
  this.sessionHasContent = hadSessionContent;
166822
167199
  this.fullscreenWelcomeVisible = previousMode === "fullscreen" ? !hadSessionContent : true;
166823
167200
  this.fullscreenHeader.setPhase(hadSessionContent ? "rail" : "welcome");
@@ -166831,6 +167208,7 @@ var ZCodeTui = class {
166831
167208
  this.bindInput();
166832
167209
  this.focusEditor();
166833
167210
  this.notifications.start();
167211
+ this.applyTerminalFocus();
166834
167212
  this.ui.requestRender(true);
166835
167213
  } catch {}
166836
167214
  }
@@ -166915,6 +167293,7 @@ var ZCodeTui = class {
166915
167293
  if (!this.stopped) {
166916
167294
  this.ui.start();
166917
167295
  this.notifications.start();
167296
+ this.applyTerminalFocus();
166918
167297
  this.focusEditor();
166919
167298
  this.ui.requestRender(true);
166920
167299
  }
@@ -166988,7 +167367,8 @@ var ZCodeTui = class {
166988
167367
  },
166989
167368
  {
166990
167369
  name: "workflows",
166991
- description: "Inspect workflow progress, results and recovery"
167370
+ description: "Inspect, tune and save workflow runs",
167371
+ argumentHint: "[list|saved]"
166992
167372
  },
166993
167373
  {
166994
167374
  name: "tasks",
@@ -167257,6 +167637,16 @@ var ZCodeTui = class {
167257
167637
  await this.showDynamicWorkflows();
167258
167638
  return;
167259
167639
  }
167640
+ if (input === "/workflows saved") {
167641
+ try {
167642
+ await showSavedWorkflows(this.options, this.workflowDialogs());
167643
+ await this.dynamicWorkflows.hydrate();
167644
+ this.renderDynamicWorkflow();
167645
+ } catch (error) {
167646
+ this.addNotice(error instanceof Error ? error.message : String(error), "error");
167647
+ }
167648
+ return;
167649
+ }
167260
167650
  if (input === "/tasks" || input === "/tasks list") {
167261
167651
  await this.showBackgroundTasks();
167262
167652
  return;
@@ -167307,7 +167697,7 @@ var ZCodeTui = class {
167307
167697
  if (isModePickerRequest(input) && await this.showModePicker()) return;
167308
167698
  if (/^\/mode(?:\s|$)/iu.test(input)) {
167309
167699
  const mode = input.slice(5).trim().toLowerCase();
167310
- if (!modes.includes(mode)) this.addNotice("Choose /mode build, edit or yolo. Use /plan on or /plan off for planning.", "warning");
167700
+ if (!modes.includes(mode)) this.addNotice("Choose /mode build, edit, guarded or yolo. Use /plan on or /plan off for planning.", "warning");
167311
167701
  else await this.applyModeShortcut(mode, true);
167312
167702
  return;
167313
167703
  }
@@ -167887,11 +168277,13 @@ var ZCodeTui = class {
167887
168277
  this.addNotice("Workflow inspection is unavailable in this runtime.", "warning");
167888
168278
  return;
167889
168279
  }
168280
+ const dialogs = this.workflowDialogs();
167890
168281
  await this.dynamicWorkflows.hydrate();
167891
168282
  if (this.dynamicWorkflows.error) this.addNotice(this.dynamicWorkflows.error, "warning");
167892
168283
  const runs = this.dynamicWorkflows.runs();
167893
168284
  if (runs.length === 0) {
167894
168285
  this.addNotice("No workflow runs in this session.", "muted");
168286
+ if (this.options.listSavedWorkflows) await showSavedWorkflows(this.options, dialogs);
167895
168287
  return;
167896
168288
  }
167897
168289
  const choice = await this.showChoice({
@@ -167901,9 +168293,18 @@ var ZCodeTui = class {
167901
168293
  value: String(run.runId),
167902
168294
  label: asString(run.label) || String(run.runId),
167903
168295
  description: [run.status, run.resumable === true ? "resumable" : void 0].filter(Boolean).join(" · ")
167904
- }))
168296
+ })).concat(this.options.listSavedWorkflows ? [{
168297
+ value: "$saved",
168298
+ label: "Saved workflows",
168299
+ description: "Run a reusable definition"
168300
+ }] : [])
167905
168301
  });
167906
- if (!choice) return;
168302
+ if (!choice || !dialogs.isCurrent()) return;
168303
+ if (choice.value === "$saved") {
168304
+ await showSavedWorkflows(this.options, dialogs);
168305
+ await this.dynamicWorkflows.hydrate();
168306
+ return;
168307
+ }
167907
168308
  this.selectedDynamicWorkflow = choice.value;
167908
168309
  const run = this.dynamicWorkflows.runs().find((run) => run.runId === choice.value);
167909
168310
  if (!run) {
@@ -167916,6 +168317,7 @@ var ZCodeTui = class {
167916
168317
  const action = await this.showChoice({
167917
168318
  title: "Workflow actions",
167918
168319
  prompt: "Progress remains visible in the transcript.",
168320
+ filterMode: "substring",
167919
168321
  items: [
167920
168322
  {
167921
168323
  value: "close",
@@ -167928,15 +168330,30 @@ var ZCodeTui = class {
167928
168330
  ...run.resumable === true ? [{
167929
168331
  value: "resume",
167930
168332
  label: "Resume workflow"
168333
+ }] : [],
168334
+ ...this.options.retuneWorkflowConcurrency && ["pending", "running"].includes(String(run.status)) ? [{
168335
+ value: "concurrency",
168336
+ label: "Adjust concurrency"
168337
+ }] : [],
168338
+ ...this.options.saveWorkflowRun ? [{
168339
+ value: "save",
168340
+ label: "Save workflow"
167931
168341
  }] : []
167932
168342
  ]
167933
168343
  });
167934
- if (!action || action.value === "close") return;
168344
+ if (!action || action.value === "close" || !dialogs.isCurrent()) return;
167935
168345
  if (!/^[A-Za-z0-9_.:-]+$/u.test(choice.value)) {
167936
168346
  this.addNotice("This workflow ID cannot be passed to the runtime command.", "error");
167937
168347
  return;
167938
168348
  }
167939
168349
  try {
168350
+ if (action.value === "concurrency" || action.value === "save") {
168351
+ if (action.value === "concurrency") await retuneWorkflow(choice.value, this.options, dialogs);
168352
+ else await saveWorkflow(run, this.options, dialogs);
168353
+ await this.dynamicWorkflows.hydrate();
168354
+ this.renderDynamicWorkflow();
168355
+ return;
168356
+ }
167940
168357
  const result = await this.options.submitPrompt(`/dwf ${action.value} ${choice.value}`, {});
167941
168358
  await this.handleResult(result);
167942
168359
  await this.dynamicWorkflows.hydrate();
@@ -168916,6 +169333,7 @@ var ZCodeTui = class {
168916
169333
  let response;
168917
169334
  if (asksUserQuestion) response = await this.requestUserQuestions(request.input, signal);
168918
169335
  else if (isExitPlanModeTool(toolName)) response = await this.requestPlanApproval(request.input, signal);
169336
+ else if (workflowAdjustableSettings(toolName, request.input)) response = await requestWorkflowApproval(request, this.workflowDialogs(), this.permissionPreview(toolName, request.input), signal);
168919
169337
  else response = await this.requestToolPermission(request, toolName, signal);
168920
169338
  const settledElsewhere = signal?.aborted === true && this.turnAbortController?.signal.aborted !== true;
168921
169339
  if (tool && !settledElsewhere) {
@@ -168930,8 +169348,18 @@ var ZCodeTui = class {
168930
169348
  }
168931
169349
  return response;
168932
169350
  }
169351
+ workflowDialogs() {
169352
+ const sessionId = this.options.getMainSessionId?.();
169353
+ return {
169354
+ choose: (options) => this.showChoice(options),
169355
+ prompt: (options) => this.showTextPrompt(options),
169356
+ notice: (message, tone) => this.addNotice(message, tone),
169357
+ models: async () => this.options.listModelOptions ? await this.options.listModelOptions() : this.modelOptions,
169358
+ isCurrent: () => sessionId === this.options.getMainSessionId?.()
169359
+ };
169360
+ }
168933
169361
  async requestToolPermission(request, toolName, signal) {
168934
- const items = (Array.isArray(request.options) ? request.options : []).flatMap((option, index) => {
169362
+ const items = (request.approvalMode !== "user-once" && Array.isArray(request.options) ? request.options : []).flatMap((option, index) => {
168935
169363
  if (!isRecord(option)) return [];
168936
169364
  const response = isRecord(option.response) ? option.response : void 0;
168937
169365
  const value = asString(option.optionId) ?? asString(option.kind) ?? String(index);
@@ -168942,7 +169370,7 @@ var ZCodeTui = class {
168942
169370
  payload: response
168943
169371
  }];
168944
169372
  });
168945
- if (items.length === 0) items.push(...defaultPermissionChoices(toolName, request.input).map((choice) => ({
169373
+ if (items.length === 0) items.push(...defaultPermissionChoices(toolName, request.input, request.approvalMode).map((choice) => ({
168946
169374
  value: choice.value,
168947
169375
  label: choice.label,
168948
169376
  description: choice.description,
@@ -170535,7 +170963,10 @@ var ZCodeTui = class {
170535
170963
  async showTextPrompt(options) {
170536
170964
  this.choiceDepth += 1;
170537
170965
  try {
170538
- return await promptText(this.ui, this.choiceHost, this.theme, options);
170966
+ return await promptText(this.ui, this.choiceHost, this.theme, {
170967
+ ...options,
170968
+ isTerminalFocused: () => this.terminalFocus !== "unfocused"
170969
+ });
170539
170970
  } finally {
170540
170971
  this.choiceDepth = Math.max(0, this.choiceDepth - 1);
170541
170972
  if (this.choiceDepth === 0) this.focusEditor();
@@ -170603,7 +171034,10 @@ var ZCodeTui = class {
170603
171034
  this.sessionModelIssue = void 0;
170604
171035
  try {
170605
171036
  const saved = await this.options.readSessionModel?.();
170606
- if (!isRecord(saved)) return;
171037
+ if (!isRecord(saved)) {
171038
+ if (this.model === "default") this.model = await this.options.readDefaultModel?.() ?? this.model;
171039
+ return;
171040
+ }
170607
171041
  if (typeof saved.model === "string") this.model = saved.model;
170608
171042
  this.thoughtLevel = asString(saved.thoughtLevel);
170609
171043
  if (Array.isArray(saved.effortOptions)) this.effortOptions = saved.effortOptions;
@@ -171021,7 +171455,8 @@ var ZCodeTui = class {
171021
171455
  };
171022
171456
  async function runTui(options) {
171023
171457
  suppressTuiAiSdkWarnings();
171024
- await new ZCodeTui(options).run();
171458
+ const readyOptions = await loadTuiStartupOptions(options);
171459
+ if (readyOptions) await new ZCodeTui(readyOptions).run();
171025
171460
  }
171026
171461
  //#endregion
171027
171462
  export { loginFailureDiagnostic, runTui, shouldSuspendForLoginCommand, shouldUseNoBrowserForLogin, suppressTuiAiSdkWarnings, suspendedZaiLoginCommand };