@songtonyli/dsh-cli 0.1.21 → 0.1.22

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.
@@ -1,5 +1,5 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { CURSOR_MARKER, Container, Editor, Input, Loader, Markdown, ProcessTerminal, SelectList, Text, TuiMainScreen, decodeKittyPrintable, fuzzyFilter, matchesKey, sliceByColumn, stripTerminalSequences, truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
2
+ import { CURSOR_MARKER, Container, Editor, Input, Loader, Markdown, ProcessTerminal, SelectList, Text, TuiMainScreen, decodeKittyPrintable, fuzzyFilter, isKeyRelease, matchesKey, sliceByColumn, stripTerminalSequences, truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
3
3
  import z from "@deepseek-ai/schemastery";
4
4
  import { brandString } from "@deepseek-ai/dsh-brand";
5
5
  import { installModelSelection } from "@deepseek-ai/dsh-agent";
@@ -318,6 +318,17 @@ function describeFailure(error) {
318
318
  return error instanceof Error ? error.message : String(error);
319
319
  }
320
320
  /**
321
+ * The extension of a path, lowercased, as a language hint for its content.
322
+ * @param path - a file path in either separator style.
323
+ * @returns the extension without its dot, or undefined for a dotfile or an
324
+ * extensionless name.
325
+ */
326
+ function extensionOf(path) {
327
+ const base = path.slice(Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")) + 1);
328
+ const dot = base.lastIndexOf(".");
329
+ return dot <= 0 ? void 0 : base.slice(dot + 1).toLowerCase();
330
+ }
331
+ /**
321
332
  * Parse the model's raw argument JSON for presentation.
322
333
  * @param argumentsJson - the `tool/call` event's verbatim argument string.
323
334
  * @returns the parsed value, or undefined when it is not JSON.
@@ -330,15 +341,52 @@ function parseArguments(argumentsJson) {
330
341
  }
331
342
  }
332
343
  /**
333
- * Render a diff for a card body.
344
+ * Render a diff for a card body, with the code span behind each changed or
345
+ * context row so the card can colour the file's own language.
334
346
  * @param diff - one file's old and new text.
335
- * @returns rows prefixed with `+`, `-`, or two spaces, plus `…` gap markers.
347
+ * @returns the rows and their spans; the `…` gap markers carry no span.
336
348
  */
337
- function diffRows(diff) {
338
- return hunks(diffLines(diff.oldText, diff.newText), DIFF_CONTEXT_LINES).map((row) => {
339
- if (row === void 0) return " …";
340
- return (row.kind === "added" ? "+ " : row.kind === "removed" ? "- " : " ") + row.text;
341
- });
349
+ function diffBody(diff) {
350
+ const lang = extensionOf(diff.path);
351
+ const rows = hunks(diffLines(diff.oldText, diff.newText), DIFF_CONTEXT_LINES);
352
+ const lines = [];
353
+ const code = [];
354
+ for (const row of rows) {
355
+ if (row === void 0) {
356
+ lines.push(" …");
357
+ code.push(void 0);
358
+ continue;
359
+ }
360
+ const prefix = row.kind === "added" ? "+ " : row.kind === "removed" ? "- " : " ";
361
+ lines.push(prefix + row.text);
362
+ code.push(lang === void 0 ? void 0 : {
363
+ lang,
364
+ prefix,
365
+ source: row.text
366
+ });
367
+ }
368
+ return {
369
+ lines,
370
+ code
371
+ };
372
+ }
373
+ /**
374
+ * Concatenate bodies: a heading row per diff, then that diff's rows.
375
+ * @param diffs - the files in display order.
376
+ * @returns one body for the whole card half.
377
+ */
378
+ function diffsBody(diffs) {
379
+ const lines = [];
380
+ const code = [];
381
+ for (const diff of diffs) {
382
+ const body = diffBody(diff);
383
+ lines.push(diff.path, ...body.lines);
384
+ code.push(void 0, ...body.code);
385
+ }
386
+ return {
387
+ lines,
388
+ code
389
+ };
342
390
  }
343
391
  /**
344
392
  * Text for a tool call from its presentation view, falling back to the raw
@@ -376,46 +424,91 @@ function toolCallText(argumentsJson, view) {
376
424
  }
377
425
  case "diff": return {
378
426
  title: view.title,
379
- lines: view.diffs.flatMap((diff) => [diff.path, ...diffRows(diff)])
427
+ ...diffsBody(view.diffs)
380
428
  };
381
429
  default: return assertNever(view, "tui tool call view");
382
430
  }
383
431
  }
384
432
  /**
385
- * Text rows for a completed tool call from its presentation view, falling
386
- * back to the model-facing result content.
433
+ * {@link toolResultLines} with the code span behind each row of a `read` or
434
+ * `diff` card, so the card draws the file's own language in colour.
387
435
  * @param view - the tool's `presentResult` view, when it has one.
388
436
  * @param content - the model-facing result content.
389
- * @returns the rows, before any preview truncation.
437
+ * @returns the rows and, for the two code cards, their spans.
390
438
  */
391
- function toolResultLines(view, content) {
392
- if (view === void 0) return contentText(content).split("\n").filter((line) => line !== "");
439
+ function toolResultBody(view, content) {
440
+ if (view === void 0) return { lines: contentText(content).split("\n").filter((line) => line !== "") };
393
441
  switch (view.card) {
394
- case "generic": return contentText(view.content ?? content).split("\n").filter((line) => line !== "");
442
+ case "generic": return { lines: contentText(view.content ?? content).split("\n").filter((line) => line !== "") };
395
443
  case "terminal": {
396
444
  const lines = (view.output ?? "").split("\n");
397
445
  while (lines.length > 0 && lines.at(-1) === "") lines.pop();
398
446
  if (view.exitCode !== void 0 && view.exitCode !== 0) lines.push(`exit ${String(view.exitCode)}`);
399
447
  if (view.signal !== void 0) lines.push(`signal ${view.signal}`);
400
- return lines;
448
+ return { lines };
401
449
  }
402
- case "diff": return view.diffs.flatMap((diff) => [diff.path, ...diffRows(diff)]);
450
+ case "diff": return diffsBody(view.diffs);
403
451
  case "search": {
404
452
  const lines = view.shape === "matches" ? view.files.flatMap((file) => file.matches.map((match) => `${file.path}:${String(match.lineNumber)}: ${match.line}`)) : [...view.paths];
405
453
  if (view.truncated) lines.push(`… ${String(view.total)} total`);
406
- return lines;
454
+ return { lines };
455
+ }
456
+ case "read": {
457
+ const lang = view.lang;
458
+ const rows = view.lines.map((line) => ({
459
+ prefix: `${String(line.number).padStart(4)}│ `,
460
+ source: line.text
461
+ }));
462
+ return {
463
+ lines: rows.map((row) => `${row.prefix}${row.source}`),
464
+ ...lang === void 0 ? {} : { code: rows.map((row) => ({
465
+ lang,
466
+ ...row
467
+ })) }
468
+ };
407
469
  }
408
- case "read": return view.lines.map((line) => `${String(line.number).padStart(4)}│ ${line.text}`);
409
470
  case "web": {
410
- if (view.kind === "fetch") return [`${view.url} (${String(view.statusCode)})`];
471
+ if (view.kind === "fetch") return { lines: [`${view.url} (${String(view.statusCode)})`] };
411
472
  const lines = view.sources.map((source) => source.title === void 0 ? source.url : `${source.title} — ${source.url}`);
412
473
  if (view.answer !== void 0) lines.unshift(view.answer);
413
- return lines;
474
+ return { lines };
414
475
  }
415
476
  default: return assertNever(view, "tui tool result view");
416
477
  }
417
478
  }
418
479
  /**
480
+ * Draw card rows in syntax colour where a highlighter and a span allow it.
481
+ * Consecutive spans of one language are coloured as one block, so a comment
482
+ * or string that spans rows keeps its colour; a group the highlighter cannot
483
+ * colour yet, or colours to a different row count, draws plain and is drawn
484
+ * again once its grammar lands.
485
+ * @param lines - the plain rows.
486
+ * @param code - the span behind each row, aligned by index; absent rows draw plain.
487
+ * @param highlight - the highlighter; absent draws every row plain.
488
+ * @returns the rows to draw, same length as `lines`.
489
+ */
490
+ function paintCodeRows(lines, code, highlight) {
491
+ if (code === void 0 || highlight === void 0) return [...lines];
492
+ const out = [...lines];
493
+ let index = 0;
494
+ while (index < lines.length) {
495
+ const span = code[index];
496
+ if (span === void 0) {
497
+ index += 1;
498
+ continue;
499
+ }
500
+ let end = index + 1;
501
+ while (end < lines.length && code[end]?.lang === span.lang) end += 1;
502
+ const group = code.slice(index, end);
503
+ const coloured = highlight.lines(group.map((row) => row.source).join("\n"), span.lang);
504
+ if (coloured !== void 0 && coloured.length === group.length) coloured.forEach((text, offset) => {
505
+ out[index + offset] = `${group[offset].prefix}${text}`;
506
+ });
507
+ index = end;
508
+ }
509
+ return out;
510
+ }
511
+ /**
419
512
  * Cut rows to a maximum, naming what was left out on one trailing row. Every
420
513
  * surface that shows part of something longer folds it this way - the collapsed
421
514
  * tool card, an approval's call detail, the focused-section inspector - and each
@@ -2564,6 +2657,8 @@ var ToolBlock = class {
2564
2657
  foldable = true;
2565
2658
  status = "running";
2566
2659
  resultLines = [];
2660
+ /** The code span behind each result row, for a `read` or `diff` result; absent otherwise. */
2661
+ resultCode;
2567
2662
  expanded = false;
2568
2663
  fade;
2569
2664
  resultFade;
@@ -2639,9 +2734,11 @@ var ToolBlock = class {
2639
2734
  * Attach the result rows and settle the status.
2640
2735
  * @param lines - the result rows before preview truncation.
2641
2736
  * @param isError - whether the tool reported failure.
2737
+ * @param code - the span behind each row, for a result the card colours as code.
2642
2738
  */
2643
- setResult(lines, isError) {
2739
+ setResult(lines, isError, code) {
2644
2740
  this.resultLines = lines;
2741
+ this.resultCode = code;
2645
2742
  this.status = isError ? "error" : "done";
2646
2743
  }
2647
2744
  /**
@@ -2664,7 +2761,8 @@ var ToolBlock = class {
2664
2761
  const { marked, content: outer } = focusFrame(width, this.highlight);
2665
2762
  const header = `${this.status === "running" ? palette.warning("●") : this.status === "done" ? palette.success("●") : palette.error("●")} ${palette.bold(this.name)}${this.call.title === "" ? "" : ` ${palette.dim(this.call.title)}`}`;
2666
2763
  const body = [...this.call.lines, ...this.resultLines];
2667
- const shown = this.expanded ? body : foldRows(body, this.theme.toolPreviewLines, (hidden) => foldMarker(hidden, marked ? "marked" : "transcript"));
2764
+ const code = this.call.code === void 0 && this.resultCode === void 0 ? void 0 : [...this.call.code ?? new Array(this.call.lines.length).fill(void 0), ...this.resultCode ?? new Array(this.resultLines.length).fill(void 0)];
2765
+ const shown = paintCodeRows(this.expanded ? body : foldRows(body, this.theme.toolPreviewLines, (hidden) => foldMarker(hidden, marked ? "marked" : "transcript")), code, this.theme.codeHighlight);
2668
2766
  const callCount = Math.min(this.call.lines.length, shown.length);
2669
2767
  const inner = Math.max(1, outer - 4);
2670
2768
  const rows = (lines) => lines.flatMap((line) => wrapTextWithAnsi(line, inner).map((part) => ` ${palette.dim("│")} ${part}`));
@@ -2993,10 +3091,10 @@ function rowsOfText(text) {
2993
3091
  //#endregion
2994
3092
  //#region lib/types/editor.js
2995
3093
  /**
2996
- * The prompt editor's caret. pi-tui draws the caret cell itself in reverse
2997
- * video; this module takes that block off the rendered lines and names the
2998
- * DECSCUSR sequences the application writes so the terminal draws the caret
2999
- * instead, as a blinking bar.
3094
+ * The prompt editor's caret and word navigation. pi-tui draws the caret cell
3095
+ * itself in reverse video; this module takes that block off the rendered lines,
3096
+ * names the DECSCUSR sequences for a blinking bar, and maps Shift+Left/Right to
3097
+ * pi-tui's word movement.
3000
3098
  * @module @deepseek-ai/dsh-tui-app/editor
3001
3099
  */
3002
3100
  /**
@@ -3010,6 +3108,10 @@ const SET_BLINKING_BAR_CURSOR = "\x1B[5 q";
3010
3108
  * before it releases the terminal.
3011
3109
  */
3012
3110
  const SET_TERMINAL_DEFAULT_CURSOR = "\x1B[0 q";
3111
+ /** Canonical Ctrl+Left sequence bound to pi-tui's word-backward action. */
3112
+ const WORD_LEFT = "\x1B[1;5D";
3113
+ /** Canonical Ctrl+Right sequence bound to pi-tui's word-forward action. */
3114
+ const WORD_RIGHT = "\x1B[1;5C";
3013
3115
  /** SGR reverse video on, which pi-tui opens its drawn block cursor with. */
3014
3116
  const REVERSE_VIDEO_ON = "\x1B[7m";
3015
3117
  /** SGR reset, which pi-tui closes its drawn block cursor with. */
@@ -3045,9 +3147,11 @@ function stripBlockCursor(line) {
3045
3147
  * placed from the `CURSOR_MARKER` the editor emits at the same position. This
3046
3148
  * subclass removes that block from the lines `render` returns so the
3047
3149
  * terminal's own cursor - which the application shapes with
3048
- * `SET_BLINKING_BAR_CURSOR` - is the only caret on screen. Everything else is
3049
- * pi-tui's: text, autocomplete, padding, borders, scrolling, submission, and
3050
- * history are untouched, and the component writes to no terminal itself.
3150
+ * `SET_BLINKING_BAR_CURSOR` - is the only caret on screen. It also gives
3151
+ * Shift+Left and Shift+Right the editor's existing word-backward and
3152
+ * word-forward actions. Text, autocomplete, padding, borders, scrolling,
3153
+ * submission, and history otherwise remain pi-tui's, and the component writes
3154
+ * to no terminal itself.
3051
3155
  *
3052
3156
  * pi-tui emits the marker only while the editor is focused, yet it draws the
3053
3157
  * block either way, so an unfocused editor would keep a caret while another
@@ -3057,6 +3161,21 @@ function stripBlockCursor(line) {
3057
3161
  * terminal cursor stays with the region that owns the keyboard.
3058
3162
  */
3059
3163
  var BarCursorEditor = class extends Editor {
3164
+ /**
3165
+ * Handle Shift+Left and Shift+Right as pi-tui's word movements.
3166
+ * @param data - the bytes the terminal sent.
3167
+ */
3168
+ handleInput(data) {
3169
+ if (matchesKey(data, "shift+left")) {
3170
+ super.handleInput(WORD_LEFT);
3171
+ return;
3172
+ }
3173
+ if (matchesKey(data, "shift+right")) {
3174
+ super.handleInput(WORD_RIGHT);
3175
+ return;
3176
+ }
3177
+ super.handleInput(data);
3178
+ }
3060
3179
  /**
3061
3180
  * Render the editor without pi-tui's drawn block cursor.
3062
3181
  * @param width - the total width to lay the editor out in.
@@ -3112,10 +3231,10 @@ function effortItems(reasoning) {
3112
3231
  * The dim row under the picker heading.
3113
3232
  * @param reasoning - what the model declares.
3114
3233
  * @param effort - the effort in force, or undefined for the provider default.
3115
- * @returns one row naming the effort in force and the keys that change it.
3234
+ * @returns one row naming the effort in force and how to dismiss the picker.
3116
3235
  */
3117
3236
  function effortHint(reasoning, effort) {
3118
- return `current: ${effortName(reasoning, effort)} · Esc keeps it · Shift+Tab cycles`;
3237
+ return `current: ${effortName(reasoning, effort)} · Esc keeps it`;
3119
3238
  }
3120
3239
  /**
3121
3240
  * The effort a typed `/effort` argument names. A declared id wins over the
@@ -3382,7 +3501,8 @@ function widestHint(region) {
3382
3501
  */
3383
3502
  const KEY_LINES = {
3384
3503
  editor: [
3385
- "Enter sends · Shift+Enter newline · ↑↓ history · Ctrl+S steers · Shift+Tab effort",
3504
+ "Enter sends · Shift+Enter newline · ↑↓ history · Ctrl+S steers",
3505
+ "Shift+Tab effort list · Shift+←→ words",
3386
3506
  "@ completes paths and sessions · / completes commands · Tab takes one",
3387
3507
  `${ENTRY_KEYS} · Ctrl+G reader`,
3388
3508
  "Ctrl+O folds every tool card and context row",
@@ -4801,7 +4921,7 @@ function effortSegment(effort) {
4801
4921
  return {
4802
4922
  id: "effort",
4803
4923
  label: unset ? "effort default" : `effort ${effort}`,
4804
- detail: printed([unset ? "reasoning effort: the model's own default" : `reasoning effort: ${effort}`, `Shift+Tab cycles it${SEPARATOR$1}/effort picks one`])
4924
+ detail: printed([unset ? "reasoning effort: the model's own default" : `reasoning effort: ${effort}`, "Shift+Tab or /effort opens the effort list"])
4805
4925
  };
4806
4926
  }
4807
4927
  /**
@@ -5249,6 +5369,13 @@ var ListPrompt = class {
5249
5369
  highlight(index) {
5250
5370
  this.list.setSelectedIndex(index);
5251
5371
  }
5372
+ /**
5373
+ * The row the highlight sits on.
5374
+ * @returns that row, or null while the list shows no row.
5375
+ */
5376
+ selected() {
5377
+ return this.list.getSelectedItem();
5378
+ }
5252
5379
  handleInput(data) {
5253
5380
  this.list.handleInput(data);
5254
5381
  }
@@ -5317,8 +5444,10 @@ function rowText(row) {
5317
5444
  * once the query is empty. The visible rows are the query's fuzzy matches
5318
5445
  * against each row's label and description, best match first; the row in
5319
5446
  * force keeps its mark and stays highlighted only while the query is empty.
5447
+ * `Ctrl+S` hands the highlighted row to `onSave` without closing the picker.
5320
5448
  */
5321
5449
  var PickPrompt = class extends ListPrompt {
5450
+ items;
5322
5451
  /** Every row in declared order, without the mark, as matched against. */
5323
5452
  rows;
5324
5453
  /** The same rows with the in-force one marked, shown while the query is empty. */
@@ -5329,6 +5458,8 @@ var PickPrompt = class extends ListPrompt {
5329
5458
  query = "";
5330
5459
  /** The rows the list shows: all of them, or the query's matches. */
5331
5460
  visible;
5461
+ /** What `Ctrl+S` does with the highlighted row, when the caller gave it a meaning. */
5462
+ onSave;
5332
5463
  constructor(palette, title, items, options = {}) {
5333
5464
  const rows = items.map((item) => ({ ...item }));
5334
5465
  const inForce = items.findIndex((item) => item.value === options.current);
@@ -5337,10 +5468,12 @@ var PickPrompt = class extends ListPrompt {
5337
5468
  label: `${row.label}${CURRENT_MARK}`
5338
5469
  } : row);
5339
5470
  super(palette, `${palette.accent("?")} ${palette.bold(title)}`, options.body ?? [], [...markedRows], (row) => items.find((item) => item.value === row.value), () => void 0, options.layout);
5471
+ this.items = items;
5340
5472
  this.rows = rows;
5341
5473
  this.markedRows = markedRows;
5342
5474
  this.inForce = inForce;
5343
5475
  this.visible = markedRows;
5476
+ this.onSave = options.onSave;
5344
5477
  if (inForce > 0) this.highlight(inForce);
5345
5478
  }
5346
5479
  /**
@@ -5370,6 +5503,12 @@ var PickPrompt = class extends ListPrompt {
5370
5503
  this.setQuery("");
5371
5504
  return;
5372
5505
  }
5506
+ if (matchesKey(data, "ctrl+s")) {
5507
+ const row = this.selected();
5508
+ const item = row === null ? void 0 : this.items.find((candidate) => candidate.value === row.value);
5509
+ if (item !== void 0) this.onSave?.(item);
5510
+ return;
5511
+ }
5373
5512
  const typed = typedText(data);
5374
5513
  if (typed === void 0) {
5375
5514
  super.handleInput(data);
@@ -7096,7 +7235,8 @@ var GuardedMainScreen = class extends TuiMainScreen {
7096
7235
  //#region lib/types/sessions.js
7097
7236
  /**
7098
7237
  * Session facts the terminal shows and switches between: the persisted
7099
- * session list with titles, and the label rows of the `/sessions` picker.
7238
+ * session list with titles, and the label rows of the `/sessions` and
7239
+ * `/resume` picker.
7100
7240
  * @module @deepseek-ai/dsh-tui-app/sessions
7101
7241
  */
7102
7242
  /**
@@ -7450,6 +7590,22 @@ var ToastPane = class {
7450
7590
  */
7451
7591
  /** A second Ctrl+C inside this window quits. */
7452
7592
  const QUIT_DOUBLE_PRESS_MS = 600;
7593
+ /** What input reports while the host is opening another session. */
7594
+ const SESSION_SWITCH_WAIT = "wait for the session switch to finish";
7595
+ /** The one extra key the model picker answers, stated above its rows. */
7596
+ const MODEL_PICKER_HINT = "Ctrl+S saves the highlighted model as the default for the next launch";
7597
+ /**
7598
+ * Read a picker row value back into a selection.
7599
+ * @param value - `provider/model`, as {@link TuiApp.modelItems} writes it.
7600
+ * @returns the provider and model.
7601
+ */
7602
+ function splitModelValue(value) {
7603
+ const slash = value.indexOf("/");
7604
+ return {
7605
+ provider: value.slice(0, slash),
7606
+ model: value.slice(slash + 1)
7607
+ };
7608
+ }
7453
7609
  /** What the transcript is told when a session switch took the conversation the reader was showing. */
7454
7610
  const READER_GONE = "the transcript changed · reader closed";
7455
7611
  /**
@@ -7580,6 +7736,10 @@ const LOCAL_COMMANDS = [
7580
7736
  name: "sessions",
7581
7737
  description: "Switch to another session"
7582
7738
  },
7739
+ {
7740
+ name: "resume",
7741
+ description: "Resume a previous session"
7742
+ },
7583
7743
  {
7584
7744
  name: "new",
7585
7745
  description: "Start a new session"
@@ -7685,6 +7845,10 @@ var TuiApp = class {
7685
7845
  /** Draws the focused transcript section, and nothing at all while the keyboard is elsewhere. */
7686
7846
  inspector;
7687
7847
  editor;
7848
+ /** Holds {@link queue} exactly while the bound Agent's inbox has a prompt waiting. */
7849
+ queueSlot = new Container();
7850
+ /** The prompts queued for the next turn or step, drawn above the editor until the loop claims them. */
7851
+ queue;
7688
7852
  /** Holds {@link panel} exactly while the bound session has subagent rows. */
7689
7853
  panelSlot = new Container();
7690
7854
  /** Blank rows that give the mounted reader the whole viewport; see {@link ViewportPad}. */
@@ -7792,8 +7956,10 @@ var TuiApp = class {
7792
7956
  toolsExpanded = false;
7793
7957
  /** Set while a session switch awaits the host, so input cannot target the session being left. */
7794
7958
  switching = false;
7795
- /** Serializes Shift+Tab effort cycles so rapid presses apply in order. */
7796
- effortCycle = Promise.resolve();
7959
+ /** The current-model effort command, including its lookup and optional picker. */
7960
+ effortOperation;
7961
+ /** The persisted-session picker shared by `/resume` and `/sessions`, including its listing. */
7962
+ sessionPicker;
7797
7963
  /** Serializes `/attach` reads so pending attachments keep the typed order. */
7798
7964
  attaching = Promise.resolve();
7799
7965
  usage = EMPTY_USAGE;
@@ -7838,6 +8004,7 @@ var TuiApp = class {
7838
8004
  this.editor.onSubmit = (text) => {
7839
8005
  this.onSubmit(text);
7840
8006
  };
8007
+ this.queue = new Text("", 0, 0);
7841
8008
  this.panel = new Text("", 0, 0);
7842
8009
  this.footer = new FooterBar(() => ({
7843
8010
  segments: this.segments,
@@ -7860,6 +8027,7 @@ var TuiApp = class {
7860
8027
  this.statusSlot,
7861
8028
  this.modalSlot,
7862
8029
  this.inspector,
8030
+ this.queueSlot,
7863
8031
  this.editor,
7864
8032
  this.panelSlot,
7865
8033
  this.footer,
@@ -7892,6 +8060,12 @@ var TuiApp = class {
7892
8060
  this.markSubagentsStale();
7893
8061
  }), ctx.on("subagent/end", () => {
7894
8062
  this.markSubagentsStale();
8063
+ }), ctx.on("agent/inbox/inserted", ({ agent: subject }) => {
8064
+ if (subject === this.agent) this.refreshQueue();
8065
+ }), ctx.on("agent/inbox/claimed", ({ agent: subject }) => {
8066
+ if (subject === this.agent) this.refreshQueue();
8067
+ }), ctx.on("agent/inbox/discarded", ({ agent: subject }) => {
8068
+ if (subject === this.agent) this.refreshQueue();
7895
8069
  }), ctx.on("approval/request", (request, next) => {
7896
8070
  if (request.agent !== this.agent) return next();
7897
8071
  return this.askApproval(request.toolName, request.reason, request.callId, request.signal);
@@ -7955,6 +8129,7 @@ var TuiApp = class {
7955
8129
  this.stopped = true;
7956
8130
  this.updateTicker();
7957
8131
  this.updateFadeTicker();
8132
+ this.cancelPickers();
7958
8133
  for (const dispose of this.disposers.splice(0)) dispose();
7959
8134
  this.modals.withdrawActive();
7960
8135
  this.dropReader();
@@ -7995,6 +8170,7 @@ var TuiApp = class {
7995
8170
  this.replaying = false;
7996
8171
  if (reading) this.notice(READER_GONE);
7997
8172
  this.refreshHeader();
8173
+ this.refreshQueue();
7998
8174
  this.refreshFooter();
7999
8175
  this.refreshSubagentPanel();
8000
8176
  this.reconcileSubagents();
@@ -8009,6 +8185,7 @@ var TuiApp = class {
8009
8185
  this.notice("stop the running turn (Esc twice) before switching sessions", "error");
8010
8186
  return;
8011
8187
  }
8188
+ this.cancelPickers();
8012
8189
  this.switching = true;
8013
8190
  let next;
8014
8191
  try {
@@ -8125,6 +8302,25 @@ var TuiApp = class {
8125
8302
  this.tui.requestRender();
8126
8303
  }
8127
8304
  /**
8305
+ * Redraw the queued prompts above the editor from the bound Agent's inbox.
8306
+ * The slot is mounted exactly while a prompt waits, so the editor sits
8307
+ * directly under the conversation the rest of the time.
8308
+ */
8309
+ refreshQueue() {
8310
+ const palette = this.deps.palette;
8311
+ const inbox = this.agent.inbox;
8312
+ const row = (label, message) => `${palette.dim(`⏳ ${label}`)} ${contentText(message.content).split("\n", 1).join("")}`;
8313
+ const rows = [...inbox.nextStep.map((message) => row("next step", message)), ...inbox.nextTurn.map((message) => row("next turn", message))];
8314
+ const mounted = this.queueSlot.children.length > 0;
8315
+ if (rows.length === 0) {
8316
+ if (mounted) this.queueSlot.removeChild(this.queue);
8317
+ } else {
8318
+ this.queue.setText(rows.join("\n"));
8319
+ if (!mounted) this.queueSlot.addChild(this.queue);
8320
+ }
8321
+ this.tui.requestRender();
8322
+ }
8323
+ /**
8128
8324
  * Redraw the panel from the last listing and a fresh sample of the live
8129
8325
  * facts. The panel is mounted exactly while it has a row, so the last
8130
8326
  * resident child leaving takes the panel with it — and the keyboard back to
@@ -8296,6 +8492,23 @@ var TuiApp = class {
8296
8492
  this.chat.addChild(new Text(rows.join("\n"), 0, 1));
8297
8493
  this.tui.requestRender();
8298
8494
  }
8495
+ /** Retire and withdraw current-model effort work. */
8496
+ cancelEffortOperation() {
8497
+ const operation = this.effortOperation;
8498
+ this.effortOperation = void 0;
8499
+ operation?.controller.abort();
8500
+ }
8501
+ /** Retire and withdraw persisted-session picker work. */
8502
+ cancelSessionPicker() {
8503
+ const operation = this.sessionPicker;
8504
+ this.sessionPicker = void 0;
8505
+ operation?.controller.abort();
8506
+ }
8507
+ /** Withdraw picker work before quit or a session switch. */
8508
+ cancelPickers() {
8509
+ this.cancelEffortOperation();
8510
+ this.cancelSessionPicker();
8511
+ }
8299
8512
  /**
8300
8513
  * Show one prompt through the modal queue. Whichever docked region holds
8301
8514
  * the keyboard gives it up first: the queue hands focus to the editor once
@@ -8516,8 +8729,8 @@ var TuiApp = class {
8516
8729
  showStatus() {
8517
8730
  this.showBlock(statusReport(this.statusFacts()));
8518
8731
  }
8519
- currentSelection() {
8520
- const { selection, agent } = this.bound;
8732
+ currentSelection(bound = this.bound) {
8733
+ const { selection, agent } = bound;
8521
8734
  const selected = selection.current ?? agent.session.requestHeader()?.config;
8522
8735
  if (selected !== void 0) return selected;
8523
8736
  return {
@@ -8526,8 +8739,9 @@ var TuiApp = class {
8526
8739
  };
8527
8740
  }
8528
8741
  /**
8529
- * Answer one key press.
8742
+ * Answer one terminal key report.
8530
8743
  *
8744
+ * Kitty release reports are consumed before they can repeat the press.
8531
8745
  * A visible prompt owns the whole key stream; `Ctrl+C` and `Ctrl+D` keep
8532
8746
  * their global meaning wherever the keyboard is; everything else is what
8533
8747
  * {@link resolveKey} makes of the key in the region that holds it.
@@ -8541,6 +8755,7 @@ var TuiApp = class {
8541
8755
  * editor answers.
8542
8756
  */
8543
8757
  onKey(data) {
8758
+ if (isKeyRelease(data)) return { consume: true };
8544
8759
  this.finishReaderClose();
8545
8760
  if (this.modals.isActive()) {
8546
8761
  if (!matchesKey(data, "ctrl+c")) return void 0;
@@ -8616,11 +8831,11 @@ var TuiApp = class {
8616
8831
  this.onSubmit(this.editor.getText(), "steer");
8617
8832
  return { consume: true };
8618
8833
  case "effort":
8619
- this.effortCycle = this.effortCycle.then(
8620
- () => this.cycleEffort(),
8621
- /* v8 ignore next -- cycleEffort handles its own failures; this recovers a rejected chain */
8622
- () => this.cycleEffort()
8623
- );
8834
+ if (this.switching) {
8835
+ this.notice(SESSION_SWITCH_WAIT, "error");
8836
+ return { consume: true };
8837
+ }
8838
+ this.dispatchCommand("/effort");
8624
8839
  return { consume: true };
8625
8840
  case "type":
8626
8841
  this.focusEditor();
@@ -9151,20 +9366,28 @@ var TuiApp = class {
9151
9366
  const text = raw.trim();
9152
9367
  if (text === "") return;
9153
9368
  if (this.switching) {
9154
- this.notice("wait for the session switch to finish", "error");
9369
+ this.notice(SESSION_SWITCH_WAIT, "error");
9155
9370
  return;
9156
9371
  }
9157
9372
  this.editor.setText("");
9158
9373
  this.editor.addToHistory(text);
9159
9374
  if (text.startsWith("/")) {
9160
- const name = text.slice(0, text.indexOf(" ") === -1 ? void 0 : text.indexOf(" "));
9161
- this.runCommand(text).catch((error) => {
9162
- this.notice(`${name} failed: ${describeFailure(error)}`, "error");
9163
- });
9375
+ this.dispatchCommand(text);
9164
9376
  return;
9165
9377
  }
9166
9378
  this.submit(text, mode);
9167
9379
  }
9380
+ /**
9381
+ * Run one slash command and turn a rejection into a terminal notice.
9382
+ * @param line - the complete slash-command line.
9383
+ * @returns when the command or its failure notice settles.
9384
+ */
9385
+ dispatchCommand(line) {
9386
+ const name = line.slice(0, line.indexOf(" ") === -1 ? void 0 : line.indexOf(" "));
9387
+ return this.runCommand(line).catch((error) => {
9388
+ this.notice(`${name} failed: ${describeFailure(error)}`, "error");
9389
+ });
9390
+ }
9168
9391
  submit(text, mode = "queue") {
9169
9392
  const agent = this.agent;
9170
9393
  const attachments = this.pending.splice(0);
@@ -9175,17 +9398,19 @@ var TuiApp = class {
9175
9398
  }],
9176
9399
  source: { kind: "user" }
9177
9400
  });
9178
- this.submittedIds.add(message.id);
9179
- const shown = attachments.length === 0 ? text : `${text}\n${attachments.map((attachment) => `[${attachment.block.type}: ${attachment.name}]`).join(" ")}`;
9180
- this.chat.addChild(new UserBlock(this.theme, shown, this.turn));
9181
- if (agent.status !== "running") agent.followup(message);
9182
- else if (mode === "steer") {
9401
+ if (agent.status !== "running") {
9402
+ this.submittedIds.add(message.id);
9403
+ const shown = attachments.length === 0 ? text : `${text}\n${attachments.map((attachment) => `[${attachment.block.type}: ${attachment.name}]`).join(" ")}`;
9404
+ this.chat.addChild(new UserBlock(this.theme, shown, this.turn));
9405
+ agent.followup(message);
9406
+ } else if (mode === "steer") {
9183
9407
  agent.steer(message);
9184
9408
  this.notice("steering the running turn: it reaches the next step");
9185
9409
  } else {
9186
9410
  agent.followup(message);
9187
9411
  this.notice("queued for the next turn (Ctrl+S steers the running turn instead)");
9188
9412
  }
9413
+ this.refreshQueue();
9189
9414
  this.refreshFooter();
9190
9415
  }
9191
9416
  async runCommand(line) {
@@ -9207,13 +9432,15 @@ var TuiApp = class {
9207
9432
  this.openReader();
9208
9433
  return;
9209
9434
  case "model":
9435
+ this.cancelEffortOperation();
9210
9436
  await this.chooseModel(argument);
9211
9437
  return;
9212
9438
  case "effort":
9213
- await this.chooseCurrentEffort(argument);
9439
+ await this.runCurrentEffort(argument);
9214
9440
  return;
9215
9441
  case "sessions":
9216
- await this.chooseSession();
9442
+ case "resume":
9443
+ await this.openSessionPicker();
9217
9444
  return;
9218
9445
  case "new":
9219
9446
  await this.switchSession(() => this.deps.host.create(), "new session");
@@ -9326,15 +9553,7 @@ var TuiApp = class {
9326
9553
  async chooseModel(argument) {
9327
9554
  const { selection } = this.bound;
9328
9555
  if (argument === "save") {
9329
- const defaults = this.deps.ctx.get("agentDefaultModel");
9330
- /* v8 ignore next 4 -- the runner injects the default-model service; only teardown can remove it */
9331
- if (defaults === void 0) {
9332
- this.notice("no default model service is composed", "error");
9333
- return;
9334
- }
9335
- const current = this.currentSelection();
9336
- await defaults.saveSelection(current);
9337
- this.notice(`default model saved: ${current.provider}/${current.model}`, "success");
9556
+ await this.saveDefaultModel(this.currentSelection());
9338
9557
  return;
9339
9558
  }
9340
9559
  let next;
@@ -9355,16 +9574,19 @@ var TuiApp = class {
9355
9574
  return;
9356
9575
  }
9357
9576
  const current = this.currentSelection();
9358
- const picked = await this.showModal(new PickPrompt(this.deps.palette, "Model for the next request", items, { current: `${current.provider}/${current.model}` }));
9577
+ const picked = await this.showModal(new PickPrompt(this.deps.palette, "Model for the next request", items, {
9578
+ body: [MODEL_PICKER_HINT],
9579
+ current: `${current.provider}/${current.model}`,
9580
+ onSave: (item) => {
9581
+ this.saveDefaultModel(splitModelValue(item.value));
9582
+ }
9583
+ }));
9359
9584
  if (picked === void 0) return;
9360
- const slash = picked.value.indexOf("/");
9361
- next = {
9362
- provider: picked.value.slice(0, slash),
9363
- model: picked.value.slice(slash + 1)
9364
- };
9585
+ next = splitModelValue(picked.value);
9365
9586
  }
9366
9587
  const effort = await this.chooseEffort(next);
9367
9588
  if (effort === null) return;
9589
+ this.cancelEffortOperation();
9368
9590
  selection.current = effort === void 0 ? next : {
9369
9591
  ...next,
9370
9592
  reasoningEffort: effort
@@ -9373,6 +9595,26 @@ var TuiApp = class {
9373
9595
  this.refreshFooter();
9374
9596
  }
9375
9597
  /**
9598
+ * Record `model` as the default every later launch starts from. The
9599
+ * reasoning effort rides along when the selection carries one.
9600
+ * @param model - the provider and model to save.
9601
+ */
9602
+ async saveDefaultModel(model) {
9603
+ const defaults = this.deps.ctx.get("agentDefaultModel");
9604
+ /* v8 ignore next 4 -- the runner injects the default-model service; only teardown can remove it */
9605
+ if (defaults === void 0) {
9606
+ this.notice("no default model service is composed", "error");
9607
+ return;
9608
+ }
9609
+ try {
9610
+ await defaults.saveSelection(model);
9611
+ } catch (error) {
9612
+ this.notice(`default model not saved: ${describeFailure(error)}`, "error");
9613
+ return;
9614
+ }
9615
+ this.notice(`default model saved: ${model.provider}/${model.model}`, "success");
9616
+ }
9617
+ /**
9376
9618
  * Offer the model's reasoning efforts when it declares more than one. The
9377
9619
  * picker opens on the effort already in force for that exact model.
9378
9620
  * @param model - the model the user picked.
@@ -9396,15 +9638,59 @@ var TuiApp = class {
9396
9638
  return picked.value === "" ? void 0 : ReasoningEffortId(picked.value);
9397
9639
  }
9398
9640
  /**
9641
+ * Whether asynchronous command or picker work may no longer affect its
9642
+ * originating session.
9643
+ * @param bound - the session binding that started the work.
9644
+ * @param signal - cancellation owned by the picker operation.
9645
+ * @returns true after cancellation, quit, or a session switch.
9646
+ */
9647
+ operationAbandoned(bound, signal) {
9648
+ return this.stopped || this.switching || this.bound !== bound || signal?.aborted === true;
9649
+ }
9650
+ /**
9651
+ * Whether current-model effort work lost either its session or selection.
9652
+ * @param bound - the session binding that started the work.
9653
+ * @param selected - that binding's explicit selection when the work began.
9654
+ * @param signal - cancellation owned by the effort operation.
9655
+ * @returns true when applying the result would overwrite newer state.
9656
+ */
9657
+ effortAbandoned(bound, selected, signal) {
9658
+ return bound.selection.current !== selected || this.operationAbandoned(bound, signal);
9659
+ }
9660
+ /**
9661
+ * Run one current-model effort command; equal active arguments share it and
9662
+ * a different argument supersedes it.
9663
+ * @param argument - a declared effort id, `default`, or empty for the picker.
9664
+ * @returns when this effort operation settles.
9665
+ */
9666
+ runCurrentEffort(argument) {
9667
+ if (this.effortOperation?.argument === argument) return this.effortOperation.done;
9668
+ this.cancelEffortOperation();
9669
+ const controller = new AbortController();
9670
+ const operation = {
9671
+ argument,
9672
+ controller,
9673
+ done: Promise.resolve()
9674
+ };
9675
+ this.effortOperation = operation;
9676
+ operation.done = this.chooseCurrentEffort(argument, this.bound, controller.signal).finally(() => {
9677
+ if (this.effortOperation === operation) this.effortOperation = void 0;
9678
+ });
9679
+ return operation.done;
9680
+ }
9681
+ /**
9399
9682
  * Choose the bound model's reasoning effort for the next request: an empty
9400
9683
  * argument opens the picker on the effort in force, `default` restores the
9401
9684
  * provider default, and anything else names a declared effort.
9402
9685
  * @param argument - a declared effort id, `default`, or empty.
9686
+ * @param bound - the session binding whose selection the lookup describes.
9687
+ * @param signal - withdraws an empty-argument picker when the session changes.
9403
9688
  */
9404
- async chooseCurrentEffort(argument) {
9405
- const current = this.currentSelection();
9689
+ async chooseCurrentEffort(argument, bound, signal) {
9690
+ const selected = bound.selection.current;
9691
+ const current = this.currentSelection(bound);
9406
9692
  const lookup = await this.lookupEfforts(current);
9407
- if (this.stopped) return;
9693
+ if (this.effortAbandoned(bound, selected, signal)) return;
9408
9694
  if (lookup.kind !== "ready") {
9409
9695
  this.reportEffortLookup(lookup, current);
9410
9696
  return;
@@ -9423,28 +9709,11 @@ var TuiApp = class {
9423
9709
  const picked = await this.showModal(new PickPrompt(this.deps.palette, `Reasoning effort · ${current.provider}/${current.model}`, effortItems(reasoning), {
9424
9710
  body: [effortHint(reasoning, current.reasoningEffort)],
9425
9711
  current: current.reasoningEffort ?? ""
9426
- }));
9427
- if (picked === void 0) return;
9712
+ }), signal);
9713
+ if (picked === void 0 || this.effortAbandoned(bound, selected, signal)) return;
9428
9714
  this.applyEffort(current, picked.value === "" ? void 0 : ReasoningEffortId(picked.value));
9429
9715
  }
9430
9716
  /**
9431
- * Advance the bound selection to the next reasoning effort, wrapping through
9432
- * the provider default. A model with fewer than two efforts has nothing to cycle.
9433
- */
9434
- async cycleEffort() {
9435
- if (this.stopped || this.modals.isActive()) return;
9436
- const current = this.currentSelection();
9437
- const lookup = await this.lookupEfforts(current);
9438
- if (this.stopped) return;
9439
- if (lookup.kind !== "ready") {
9440
- this.reportEffortLookup(lookup, current);
9441
- return;
9442
- }
9443
- const steps = [void 0, ...lookup.reasoning.efforts.map((effort) => effort.id)];
9444
- const index = steps.findIndex((step) => step === current.reasoningEffort);
9445
- this.applyEffort(current, steps[index === -1 ? 1 : (index + 1) % steps.length]);
9446
- }
9447
- /**
9448
9717
  * Read what one model declares about reasoning effort.
9449
9718
  * @param model - the model to resolve.
9450
9719
  * @returns the declared efforts, or why the terminal has none to offer.
@@ -9524,9 +9793,38 @@ var TuiApp = class {
9524
9793
  }
9525
9794
  return items;
9526
9795
  }
9527
- async chooseSession() {
9796
+ /**
9797
+ * Open the one persisted-session picker shared by `/sessions` and `/resume`.
9798
+ * @returns when the active picker operation settles.
9799
+ */
9800
+ openSessionPicker() {
9801
+ if (this.sessionPicker !== void 0) return this.sessionPicker.done;
9802
+ const controller = new AbortController();
9803
+ const operation = {
9804
+ controller,
9805
+ done: Promise.resolve()
9806
+ };
9807
+ this.sessionPicker = operation;
9808
+ operation.done = this.chooseSession(this.bound, controller.signal).finally(() => {
9809
+ if (this.sessionPicker === operation) this.sessionPicker = void 0;
9810
+ });
9811
+ return operation.done;
9812
+ }
9813
+ /**
9814
+ * List and open sessions for one still-current binding.
9815
+ * @param bound - the session that was current when listing began.
9816
+ * @param signal - cancels listing and withdraws its queued or visible picker.
9817
+ */
9818
+ async chooseSession(bound, signal) {
9528
9819
  this.notice("listing sessions…");
9529
- const choices = await listSessionChoices(this.deps.ctx, this.agent.session.id, new AbortController().signal);
9820
+ let choices;
9821
+ try {
9822
+ choices = await listSessionChoices(this.deps.ctx, bound.agent.session.id, signal);
9823
+ } catch (error) {
9824
+ if (signal.aborted) return;
9825
+ throw error;
9826
+ }
9827
+ if (this.operationAbandoned(bound, signal)) return;
9530
9828
  if (choices.length === 0) {
9531
9829
  this.notice("no persisted sessions are listed by the composed query engine", "error");
9532
9830
  return;
@@ -9535,8 +9833,9 @@ var TuiApp = class {
9535
9833
  value: choice.id,
9536
9834
  ...describeSession(choice)
9537
9835
  }));
9538
- const picked = await this.showModal(new PickPrompt(this.deps.palette, "Switch to a session", items));
9539
- const target = choices.find((choice) => choice.id === picked?.value);
9836
+ const picked = await this.showModal(new PickPrompt(this.deps.palette, "Switch to a session", items), signal);
9837
+ if (picked === void 0 || this.operationAbandoned(bound, signal)) return;
9838
+ const target = choices.find((choice) => choice.id === picked.value);
9540
9839
  if (target === void 0 || target.current) return;
9541
9840
  await this.switchSession(() => this.deps.host.resume(target.id), "resumed");
9542
9841
  }
@@ -9600,6 +9899,7 @@ var TuiApp = class {
9600
9899
  const inbox = this.agent.inbox;
9601
9900
  if (argument === "clear") {
9602
9901
  inbox.clear();
9902
+ this.refreshQueue();
9603
9903
  this.notice("queue cleared", "success");
9604
9904
  return;
9605
9905
  }
@@ -10112,8 +10412,8 @@ var TuiApp = class {
10112
10412
  const block = this.toolBlocks.get(result.toolCallId);
10113
10413
  if (block === void 0) break;
10114
10414
  const isError = result.isError === true;
10115
- const view = this.presentResult(block.name, this.toolArguments.get(result.toolCallId), result.content, isError, event.data.meta);
10116
- block.setResult(toolResultLines(view, result.content), isError);
10415
+ const body = toolResultBody(this.presentResult(block.name, this.toolArguments.get(result.toolCallId), result.content, isError, event.data.meta), result.content);
10416
+ block.setResult(body.lines, isError, body.code);
10117
10417
  this.fadeBlock((fade) => {
10118
10418
  block.setResultFade(fade);
10119
10419
  });