@songtonyli/dsh-cli 0.1.80 → 0.1.82

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 (70) hide show
  1. package/README.md +1 -1
  2. package/bin/dsh.mjs +1 -1
  3. package/node_modules/@aws-sdk/core/dist-cjs/submodules/protocols/index.js +94 -1589
  4. package/node_modules/@aws-sdk/core/dist-es/submodules/protocols/index.js +1 -7
  5. package/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/AwsJsonRpcProtocol.js +1 -3
  6. package/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/AwsRestJsonProtocol.js +1 -3
  7. package/node_modules/@aws-sdk/core/package.json +2 -2
  8. package/node_modules/@aws-sdk/credential-provider-env/package.json +3 -3
  9. package/node_modules/@aws-sdk/credential-provider-http/package.json +3 -3
  10. package/node_modules/@aws-sdk/credential-provider-ini/package.json +10 -10
  11. package/node_modules/@aws-sdk/credential-provider-login/package.json +4 -4
  12. package/node_modules/@aws-sdk/credential-provider-node/package.json +8 -8
  13. package/node_modules/@aws-sdk/credential-provider-process/package.json +3 -3
  14. package/node_modules/@aws-sdk/credential-provider-sso/package.json +5 -5
  15. package/node_modules/@aws-sdk/credential-provider-web-identity/package.json +4 -4
  16. package/node_modules/@aws-sdk/eventstream-handler-node/package.json +2 -2
  17. package/node_modules/@aws-sdk/middleware-eventstream/package.json +2 -2
  18. package/node_modules/@aws-sdk/middleware-websocket/package.json +3 -3
  19. package/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/cognito-identity/index.js +1 -1
  20. package/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/signin/index.js +1 -1
  21. package/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso/index.js +1 -1
  22. package/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso-oidc/index.js +1 -1
  23. package/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/index.js +1 -1
  24. package/node_modules/@aws-sdk/nested-clients/package.json +3 -3
  25. package/node_modules/@aws-sdk/token-providers/dist-cjs/index.js +37 -19
  26. package/node_modules/@aws-sdk/token-providers/dist-es/fromSso.js +37 -19
  27. package/node_modules/@aws-sdk/token-providers/package.json +4 -4
  28. package/node_modules/@deepseek-ai/dsh-client-modules/lib/index.js +1 -1
  29. package/node_modules/@deepseek-ai/dsh-client-ui-sidebar/lib/client.js +1 -1
  30. package/node_modules/@deepseek-ai/dsh-subprocess-local/README.i18n.yaml +14 -14
  31. package/node_modules/@deepseek-ai/dsh-subprocess-local/README.md +7 -5
  32. package/node_modules/@deepseek-ai/dsh-subprocess-local/README.zh.md +7 -5
  33. package/node_modules/@deepseek-ai/dsh-subprocess-local/lib/index.js +15 -3
  34. package/node_modules/@deepseek-ai/dsh-subprocess-local/lib/runner-launch-f9xQyTek.js +1669 -0
  35. package/node_modules/@deepseek-ai/dsh-subprocess-local/lib/runner.js +1 -1
  36. package/node_modules/@deepseek-ai/dsh-tui-app/README.i18n.yaml +19 -16
  37. package/node_modules/@deepseek-ai/dsh-tui-app/README.md +30 -13
  38. package/node_modules/@deepseek-ai/dsh-tui-app/README.zh.md +30 -13
  39. package/node_modules/@deepseek-ai/dsh-tui-app/lib/index.js +615 -245
  40. package/node_modules/execa/lib/convert/duplex.js +8 -4
  41. package/node_modules/execa/lib/convert/readable.js +3 -8
  42. package/node_modules/execa/lib/convert/writable.js +6 -5
  43. package/node_modules/execa/lib/io/input-sync.js +2 -1
  44. package/node_modules/execa/lib/io/max-buffer.js +2 -1
  45. package/node_modules/execa/lib/io/output-sync.js +2 -1
  46. package/node_modules/execa/lib/methods/create.js +7 -0
  47. package/node_modules/execa/lib/methods/node.js +1 -1
  48. package/node_modules/execa/lib/methods/script.js +3 -3
  49. package/node_modules/execa/lib/resolve/all-async.js +2 -1
  50. package/node_modules/execa/lib/resolve/wait-subprocess.js +6 -0
  51. package/node_modules/execa/lib/stdio/handle-async.js +3 -2
  52. package/node_modules/execa/lib/stdio/handle.js +8 -3
  53. package/node_modules/execa/lib/transform/generator.js +7 -0
  54. package/node_modules/execa/lib/transform/run-sync.js +17 -5
  55. package/node_modules/execa/package.json +1 -1
  56. package/package.json +16 -16
  57. package/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/JsonSettings.js +0 -1
  58. package/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/codec-v1/JsonCodec.js +0 -20
  59. package/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/codec-v1/JsonSettings.js +0 -1
  60. package/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/codec-v1/JsonShapeDeserializer.js +0 -160
  61. package/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/codec-v1/JsonShapeSerializer.js +0 -193
  62. package/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/codec-v2/JsonBytesStringAdapter.js +0 -103
  63. package/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/codec-v2/JsonCodec2.js +0 -20
  64. package/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/codec-v2/JsonShapeDeserializer2.js +0 -200
  65. package/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/codec-v2/JsonShapeSerializer2.js +0 -519
  66. package/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/detectBufferParsing.js +0 -18
  67. package/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/jsonReplacer.js +0 -46
  68. package/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/jsonReviver.js +0 -121
  69. package/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/needsReviver.js +0 -41
  70. package/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/parseJsonBody.js +0 -89
@@ -2324,6 +2324,280 @@ function sliceColumns(line, cuts) {
2324
2324
  }
2325
2325
  return pieces;
2326
2326
  }
2327
+ //#endregion
2328
+ //#region lib/types/style.js
2329
+ /**
2330
+ * The terminal palette: one table of SGR open/close pairs behind named roles,
2331
+ * so components never emit raw escape codes. Colored roles draw from the
2332
+ * Tokyo Night (Night) hues, as 24-bit color on a terminal that declares
2333
+ * truecolor and as the nearest xterm-256 index otherwise. A disabled palette
2334
+ * returns text unchanged for dumb terminals and captured output. The palette
2335
+ * also says whether the keys a surface names are clickable, because it is what
2336
+ * every surface draws a key chip with.
2337
+ * @module @deepseek-ai/dsh-tui-app/style
2338
+ */
2339
+ const ESC = "\x1B[";
2340
+ /** SGR that resets the foreground, closing every hue. */
2341
+ const FOREGROUND_CLOSE = "39";
2342
+ /** Each hue's Tokyo Night (Night) color and its nearest xterm-256 index. */
2343
+ const HUES = {
2344
+ blue: ["#7aa2f7", 111],
2345
+ cyan: ["#7dcfff", 117],
2346
+ teal: ["#73daca", 80],
2347
+ green: ["#9ece6a", 149],
2348
+ yellow: ["#e0af68", 179],
2349
+ orange: ["#ff9e64", 215],
2350
+ red: ["#f7768e", 210],
2351
+ magenta: ["#bb9af7", 141],
2352
+ purple: ["#9d7cd8", 140]
2353
+ };
2354
+ /** The hue each colored role draws in. */
2355
+ const ROLE_HUES = {
2356
+ accent: "blue",
2357
+ heading: "orange",
2358
+ link: "magenta",
2359
+ success: "green",
2360
+ warning: "yellow",
2361
+ error: "red",
2362
+ tool: "cyan",
2363
+ subject: "teal",
2364
+ model: "purple",
2365
+ addedSign: "green",
2366
+ removedSign: "red"
2367
+ };
2368
+ /** SGR open/close code pairs of the roles that are not a hue. */
2369
+ const SGR = {
2370
+ dim: ["2", "22"],
2371
+ bold: ["1", "22"],
2372
+ italic: ["3", "23"],
2373
+ underline: ["4", "24"],
2374
+ strikethrough: ["9", "29"],
2375
+ inverse: ["7", "27"],
2376
+ band: ["48;5;236", "49"],
2377
+ injectedBand: ["48;5;234", "49"],
2378
+ addedBand: ["48;5;22", "49"],
2379
+ removedBand: ["48;5;52", "49"]
2380
+ };
2381
+ /**
2382
+ * The SGR parameters that set one hue as the foreground.
2383
+ * @param hue - the hue.
2384
+ * @param depth - how the terminal encodes it.
2385
+ * @returns e.g. `38;2;122;162;247` or `38;5;111`.
2386
+ */
2387
+ function hueOpen(hue, depth) {
2388
+ const [rgb, ansi256] = HUES[hue];
2389
+ if (depth === "ansi256") return `38;5;${String(ansi256)}`;
2390
+ const value = Number.parseInt(rgb.slice(1), 16);
2391
+ return `38;2;${String(value >> 16)};${String(value >> 8 & 255)};${String(value & 255)}`;
2392
+ }
2393
+ /**
2394
+ * Whether the environment declares 24-bit color: `COLORTERM` of `truecolor` or `24bit`.
2395
+ * @param env - the process environment.
2396
+ * @returns true when `ESC[38;2;R;G;Bm` is understood.
2397
+ */
2398
+ function declaresTruecolor(env) {
2399
+ const colorterm = (env.COLORTERM ?? "").toLowerCase();
2400
+ return colorterm === "truecolor" || colorterm === "24bit";
2401
+ }
2402
+ /**
2403
+ * Decide how the palette encodes its hues.
2404
+ * @param env - the process environment.
2405
+ * @returns `truecolor` when the environment declares it, otherwise `ansi256`.
2406
+ */
2407
+ function paletteDepth(env) {
2408
+ return declaresTruecolor(env) ? "truecolor" : "ansi256";
2409
+ }
2410
+ /**
2411
+ * Build the palette.
2412
+ * @param enabled - whether escape sequences are emitted; false makes every role the identity.
2413
+ * @param clickableKeys - whether key chips carry click marks; false by default.
2414
+ * @param depth - how hues are encoded; `ansi256` by default.
2415
+ * @returns the palette.
2416
+ */
2417
+ function createPalette(enabled, clickableKeys = false, depth = "ansi256") {
2418
+ const wrap = (open, close) => enabled ? (text) => `${ESC}${open}m${text}${ESC}${close}m` : (text) => text;
2419
+ const role = (name) => wrap(...SGR[name]);
2420
+ const paint = (name) => wrap(hueOpen(name, depth), FOREGROUND_CLOSE);
2421
+ const hue = {
2422
+ blue: paint("blue"),
2423
+ cyan: paint("cyan"),
2424
+ teal: paint("teal"),
2425
+ green: paint("green"),
2426
+ yellow: paint("yellow"),
2427
+ orange: paint("orange"),
2428
+ red: paint("red"),
2429
+ magenta: paint("magenta"),
2430
+ purple: paint("purple")
2431
+ };
2432
+ const colored = (name) => hue[ROLE_HUES[name]];
2433
+ return {
2434
+ dim: role("dim"),
2435
+ bold: role("bold"),
2436
+ italic: role("italic"),
2437
+ underline: role("underline"),
2438
+ strikethrough: role("strikethrough"),
2439
+ accent: colored("accent"),
2440
+ heading: colored("heading"),
2441
+ link: colored("link"),
2442
+ success: colored("success"),
2443
+ warning: colored("warning"),
2444
+ error: colored("error"),
2445
+ tool: colored("tool"),
2446
+ subject: colored("subject"),
2447
+ model: colored("model"),
2448
+ inverse: role("inverse"),
2449
+ band: role("band"),
2450
+ injectedBand: role("injectedBand"),
2451
+ addedBand: role("addedBand"),
2452
+ removedBand: role("removedBand"),
2453
+ addedSign: colored("addedSign"),
2454
+ removedSign: colored("removedSign"),
2455
+ hue,
2456
+ enabled,
2457
+ clickableKeys
2458
+ };
2459
+ }
2460
+ /**
2461
+ * Paint added and removed diff rows while leaving context and metadata rows
2462
+ * unchanged. `source` stays plain so syntax-colored rows can be classified.
2463
+ * @param rows - rows after optional syntax highlighting.
2464
+ * @param source - corresponding plain rows carrying the diff prefixes.
2465
+ * @param palette - active terminal palette.
2466
+ * @returns the rows with additions green and removals red.
2467
+ */
2468
+ function paintDiffRows(rows, source, palette) {
2469
+ return rows.map((row, index) => {
2470
+ const plain = source[index];
2471
+ if (plain?.startsWith("+ ") === true) return palette.success(row);
2472
+ if (plain?.startsWith("- ") === true) return palette.error(row);
2473
+ return row;
2474
+ });
2475
+ }
2476
+ /**
2477
+ * Lay one row on a background tint across the full width.
2478
+ * @param palette - the active palette.
2479
+ * @param row - the styled row, at most `width` columns.
2480
+ * @param width - the columns the band spans.
2481
+ * @param band - the tint; {@link Palette.band} by default.
2482
+ * @returns the row padded to `width` under the tint; the row unchanged, with
2483
+ * no padding, when the palette is disabled.
2484
+ */
2485
+ function bandRow(palette, row, width, band = palette.band) {
2486
+ return palette.enabled ? band(`${row}${" ".repeat(Math.max(0, width - visibleWidth(row)))}`) : row;
2487
+ }
2488
+ /**
2489
+ * The `+` or `-` of a changed row, painted apart from the tint the row is
2490
+ * filled with. The sign sits in the plain row's own prefix - the file line
2491
+ * number, when the diff carries one, then the sign and a space - and syntax
2492
+ * colour starts after it, so the styled row opens with the same characters.
2493
+ * @param row - the styled row.
2494
+ * @param plain - the same row before any syntax colour.
2495
+ * @param mark - whether the row is an addition or a removal.
2496
+ * @param palette - the active palette.
2497
+ * @returns the row with its sign painted, or unchanged when the styled row
2498
+ * does not open with the plain prefix.
2499
+ */
2500
+ function paintDiffSign(row, plain, mark, palette) {
2501
+ const sign = mark === "added" ? "+" : "-";
2502
+ const at = plain.indexOf(`${sign} `);
2503
+ if (at === -1 || !row.startsWith(plain.slice(0, at + 1))) return row;
2504
+ const paint = mark === "added" ? palette.addedSign : palette.removedSign;
2505
+ return `${row.slice(0, at)}${paint(sign)}${row.slice(at + 1)}`;
2506
+ }
2507
+ /**
2508
+ * Wrap rows to `width` and fill each changed row edge to edge with its own
2509
+ * background tint - green for an addition, red for a removal - so a run of
2510
+ * changes reads as one region without spending a column on a border. The `+`
2511
+ * and `-` are painted in their own lighter colour, apart from the fill, and a
2512
+ * wrapped continuation carries the tint with no sign of its own. Every
2513
+ * returned line is at most `width` columns, and every filled line is exactly
2514
+ * `width`; a disabled palette pads nothing and returns the rows as they are.
2515
+ * @param rows - the styled rows.
2516
+ * @param plain - the same rows before any syntax colour, which carry the signs.
2517
+ * @param marks - per row, whether it is an addition or a removal; undefined
2518
+ * for a row no tint fills.
2519
+ * @param width - the columns the rows fit.
2520
+ * @param palette - the active palette.
2521
+ * @returns the wrapped rows, the changed ones filled.
2522
+ */
2523
+ function bandDiffRows(rows, plain, marks, width, palette) {
2524
+ const columns = Math.max(1, width);
2525
+ const out = [];
2526
+ for (const [index, row] of rows.entries()) {
2527
+ const mark = marks[index];
2528
+ if (mark === void 0) {
2529
+ out.push(...wrapTextWithAnsi(row, columns));
2530
+ continue;
2531
+ }
2532
+ const fill = mark === "added" ? palette.addedBand : palette.removedBand;
2533
+ const signed = paintDiffSign(row, plain[index] ?? "", mark, palette);
2534
+ for (const part of wrapTextWithAnsi(signed, columns)) out.push(palette.enabled ? fill(`${part}${" ".repeat(Math.max(0, columns - visibleWidth(part)))}`) : part);
2535
+ }
2536
+ return out;
2537
+ }
2538
+ /**
2539
+ * Decide whether the terminal gets color: `NO_COLOR` (any non-empty value)
2540
+ * wins, then a non-empty non-zero `FORCE_COLOR`, then whether stdout is a TTY.
2541
+ * @param env - the process environment.
2542
+ * @param isTty - whether stdout is a terminal.
2543
+ * @returns true when SGR styling should be emitted.
2544
+ */
2545
+ function colorEnabled(env, isTty) {
2546
+ if (env.NO_COLOR !== void 0 && env.NO_COLOR !== "") return false;
2547
+ if (env.FORCE_COLOR !== void 0 && env.FORCE_COLOR !== "" && env.FORCE_COLOR !== "0") return true;
2548
+ return isTty;
2549
+ }
2550
+ /**
2551
+ * The Markdown theme derived from the palette.
2552
+ * @param palette - the active palette.
2553
+ * @param highlight - colours fenced code; omitted draws every block plain,
2554
+ * which is also what a block whose language has no grammar here draws as.
2555
+ * @returns a complete pi-tui Markdown theme.
2556
+ */
2557
+ function markdownTheme(palette, highlight) {
2558
+ return {
2559
+ highlightCode: (code, lang) => highlight?.lines(code, lang) ?? code.split("\n"),
2560
+ heading: (text) => palette.bold(palette.heading(text)),
2561
+ link: (text) => palette.underline(palette.link(text)),
2562
+ linkUrl: palette.dim,
2563
+ code: palette.link,
2564
+ codeBlock: (text) => text,
2565
+ codeBlockBorder: palette.dim,
2566
+ quote: (text) => palette.italic(palette.dim(text)),
2567
+ quoteBorder: palette.dim,
2568
+ hr: palette.dim,
2569
+ listBullet: palette.heading,
2570
+ bold: palette.bold,
2571
+ italic: palette.italic,
2572
+ strikethrough: palette.strikethrough,
2573
+ underline: palette.underline
2574
+ };
2575
+ }
2576
+ /**
2577
+ * The select-list theme derived from the palette.
2578
+ * @param palette - the active palette.
2579
+ * @returns a complete pi-tui select-list theme.
2580
+ */
2581
+ function selectListTheme(palette) {
2582
+ return {
2583
+ selectedPrefix: palette.accent,
2584
+ selectedText: (text) => palette.bold(palette.accent(text)),
2585
+ description: palette.dim,
2586
+ scrollInfo: palette.dim,
2587
+ noMatch: palette.dim
2588
+ };
2589
+ }
2590
+ /**
2591
+ * The editor theme derived from the palette.
2592
+ * @param palette - the active palette.
2593
+ * @returns a complete pi-tui editor theme.
2594
+ */
2595
+ function editorTheme(palette) {
2596
+ return {
2597
+ borderColor: palette.dim,
2598
+ selectList: selectListTheme(palette)
2599
+ };
2600
+ }
2327
2601
  /** Control Sequence Introducer. */
2328
2602
  const CSI$2 = "\x1B[";
2329
2603
  /**
@@ -2391,8 +2665,7 @@ function resolveFadeCapability(input) {
2391
2665
  if (env.NO_COLOR !== void 0 && env.NO_COLOR !== "") return "none";
2392
2666
  const term = env.TERM ?? "";
2393
2667
  if (term === "dumb") return "none";
2394
- const colorterm = (env.COLORTERM ?? "").toLowerCase();
2395
- if (colorterm === "truecolor" || colorterm === "24bit") return "truecolor";
2668
+ if (declaresTruecolor(env)) return "truecolor";
2396
2669
  return term.includes("256color") ? "ansi256" : "dim";
2397
2670
  }
2398
2671
  /**
@@ -3455,213 +3728,6 @@ var TailWrappedText = class {
3455
3728
  }
3456
3729
  };
3457
3730
  //#endregion
3458
- //#region lib/types/style.js
3459
- /**
3460
- * The terminal palette: one table of SGR open/close pairs behind named roles,
3461
- * so components never emit raw escape codes. A disabled palette returns text
3462
- * unchanged for dumb terminals and captured output. The palette also says
3463
- * whether the keys a surface names are clickable, because it is what every
3464
- * surface draws a key chip with.
3465
- * @module @deepseek-ai/dsh-tui-app/style
3466
- */
3467
- const ESC = "\x1B[";
3468
- /** SGR open/close code pairs by role. */
3469
- const SGR = {
3470
- dim: ["2", "22"],
3471
- bold: ["1", "22"],
3472
- italic: ["3", "23"],
3473
- underline: ["4", "24"],
3474
- strikethrough: ["9", "29"],
3475
- accent: ["36", "39"],
3476
- heading: ["38;5;215", "39"],
3477
- link: ["38;5;141", "39"],
3478
- success: ["32", "39"],
3479
- warning: ["33", "39"],
3480
- error: ["31", "39"],
3481
- inverse: ["7", "27"],
3482
- band: ["48;5;236", "49"],
3483
- injectedBand: ["48;5;234", "49"],
3484
- addedBand: ["48;5;22", "49"],
3485
- removedBand: ["48;5;52", "49"],
3486
- addedSign: ["38;5;120", "39"],
3487
- removedSign: ["38;5;210", "39"]
3488
- };
3489
- /**
3490
- * Build the palette.
3491
- * @param enabled - whether escape sequences are emitted; false makes every role the identity.
3492
- * @param clickableKeys - whether key chips carry click marks; false by default.
3493
- * @returns the palette.
3494
- */
3495
- function createPalette(enabled, clickableKeys = false) {
3496
- const role = (name) => {
3497
- const [open, close] = SGR[name];
3498
- return enabled ? (text) => `${ESC}${open}m${text}${ESC}${close}m` : (text) => text;
3499
- };
3500
- return {
3501
- dim: role("dim"),
3502
- bold: role("bold"),
3503
- italic: role("italic"),
3504
- underline: role("underline"),
3505
- strikethrough: role("strikethrough"),
3506
- accent: role("accent"),
3507
- heading: role("heading"),
3508
- link: role("link"),
3509
- success: role("success"),
3510
- warning: role("warning"),
3511
- error: role("error"),
3512
- inverse: role("inverse"),
3513
- band: role("band"),
3514
- injectedBand: role("injectedBand"),
3515
- addedBand: role("addedBand"),
3516
- removedBand: role("removedBand"),
3517
- addedSign: role("addedSign"),
3518
- removedSign: role("removedSign"),
3519
- enabled,
3520
- clickableKeys
3521
- };
3522
- }
3523
- /**
3524
- * Paint added and removed diff rows while leaving context and metadata rows
3525
- * unchanged. `source` stays plain so syntax-colored rows can be classified.
3526
- * @param rows - rows after optional syntax highlighting.
3527
- * @param source - corresponding plain rows carrying the diff prefixes.
3528
- * @param palette - active terminal palette.
3529
- * @returns the rows with additions green and removals red.
3530
- */
3531
- function paintDiffRows(rows, source, palette) {
3532
- return rows.map((row, index) => {
3533
- const plain = source[index];
3534
- if (plain?.startsWith("+ ") === true) return palette.success(row);
3535
- if (plain?.startsWith("- ") === true) return palette.error(row);
3536
- return row;
3537
- });
3538
- }
3539
- /**
3540
- * Lay one row on a background tint across the full width.
3541
- * @param palette - the active palette.
3542
- * @param row - the styled row, at most `width` columns.
3543
- * @param width - the columns the band spans.
3544
- * @param band - the tint; {@link Palette.band} by default.
3545
- * @returns the row padded to `width` under the tint; the row unchanged, with
3546
- * no padding, when the palette is disabled.
3547
- */
3548
- function bandRow(palette, row, width, band = palette.band) {
3549
- return palette.enabled ? band(`${row}${" ".repeat(Math.max(0, width - visibleWidth(row)))}`) : row;
3550
- }
3551
- /**
3552
- * The `+` or `-` of a changed row, painted apart from the tint the row is
3553
- * filled with. The sign sits in the plain row's own prefix - the file line
3554
- * number, when the diff carries one, then the sign and a space - and syntax
3555
- * colour starts after it, so the styled row opens with the same characters.
3556
- * @param row - the styled row.
3557
- * @param plain - the same row before any syntax colour.
3558
- * @param mark - whether the row is an addition or a removal.
3559
- * @param palette - the active palette.
3560
- * @returns the row with its sign painted, or unchanged when the styled row
3561
- * does not open with the plain prefix.
3562
- */
3563
- function paintDiffSign(row, plain, mark, palette) {
3564
- const sign = mark === "added" ? "+" : "-";
3565
- const at = plain.indexOf(`${sign} `);
3566
- if (at === -1 || !row.startsWith(plain.slice(0, at + 1))) return row;
3567
- const paint = mark === "added" ? palette.addedSign : palette.removedSign;
3568
- return `${row.slice(0, at)}${paint(sign)}${row.slice(at + 1)}`;
3569
- }
3570
- /**
3571
- * Wrap rows to `width` and fill each changed row edge to edge with its own
3572
- * background tint - green for an addition, red for a removal - so a run of
3573
- * changes reads as one region without spending a column on a border. The `+`
3574
- * and `-` are painted in their own lighter colour, apart from the fill, and a
3575
- * wrapped continuation carries the tint with no sign of its own. Every
3576
- * returned line is at most `width` columns, and every filled line is exactly
3577
- * `width`; a disabled palette pads nothing and returns the rows as they are.
3578
- * @param rows - the styled rows.
3579
- * @param plain - the same rows before any syntax colour, which carry the signs.
3580
- * @param marks - per row, whether it is an addition or a removal; undefined
3581
- * for a row no tint fills.
3582
- * @param width - the columns the rows fit.
3583
- * @param palette - the active palette.
3584
- * @returns the wrapped rows, the changed ones filled.
3585
- */
3586
- function bandDiffRows(rows, plain, marks, width, palette) {
3587
- const columns = Math.max(1, width);
3588
- const out = [];
3589
- for (const [index, row] of rows.entries()) {
3590
- const mark = marks[index];
3591
- if (mark === void 0) {
3592
- out.push(...wrapTextWithAnsi(row, columns));
3593
- continue;
3594
- }
3595
- const fill = mark === "added" ? palette.addedBand : palette.removedBand;
3596
- const signed = paintDiffSign(row, plain[index] ?? "", mark, palette);
3597
- for (const part of wrapTextWithAnsi(signed, columns)) out.push(palette.enabled ? fill(`${part}${" ".repeat(Math.max(0, columns - visibleWidth(part)))}`) : part);
3598
- }
3599
- return out;
3600
- }
3601
- /**
3602
- * Decide whether the terminal gets color: `NO_COLOR` (any non-empty value)
3603
- * wins, then a non-empty non-zero `FORCE_COLOR`, then whether stdout is a TTY.
3604
- * @param env - the process environment.
3605
- * @param isTty - whether stdout is a terminal.
3606
- * @returns true when SGR styling should be emitted.
3607
- */
3608
- function colorEnabled(env, isTty) {
3609
- if (env.NO_COLOR !== void 0 && env.NO_COLOR !== "") return false;
3610
- if (env.FORCE_COLOR !== void 0 && env.FORCE_COLOR !== "" && env.FORCE_COLOR !== "0") return true;
3611
- return isTty;
3612
- }
3613
- /**
3614
- * The Markdown theme derived from the palette.
3615
- * @param palette - the active palette.
3616
- * @param highlight - colours fenced code; omitted draws every block plain,
3617
- * which is also what a block whose language has no grammar here draws as.
3618
- * @returns a complete pi-tui Markdown theme.
3619
- */
3620
- function markdownTheme(palette, highlight) {
3621
- return {
3622
- highlightCode: (code, lang) => highlight?.lines(code, lang) ?? code.split("\n"),
3623
- heading: (text) => palette.bold(palette.heading(text)),
3624
- link: (text) => palette.underline(palette.link(text)),
3625
- linkUrl: palette.dim,
3626
- code: palette.link,
3627
- codeBlock: (text) => text,
3628
- codeBlockBorder: palette.dim,
3629
- quote: (text) => palette.italic(palette.dim(text)),
3630
- quoteBorder: palette.dim,
3631
- hr: palette.dim,
3632
- listBullet: palette.heading,
3633
- bold: palette.bold,
3634
- italic: palette.italic,
3635
- strikethrough: palette.strikethrough,
3636
- underline: palette.underline
3637
- };
3638
- }
3639
- /**
3640
- * The select-list theme derived from the palette.
3641
- * @param palette - the active palette.
3642
- * @returns a complete pi-tui select-list theme.
3643
- */
3644
- function selectListTheme(palette) {
3645
- return {
3646
- selectedPrefix: palette.accent,
3647
- selectedText: (text) => palette.bold(palette.accent(text)),
3648
- description: palette.dim,
3649
- scrollInfo: palette.dim,
3650
- noMatch: palette.dim
3651
- };
3652
- }
3653
- /**
3654
- * The editor theme derived from the palette.
3655
- * @param palette - the active palette.
3656
- * @returns a complete pi-tui editor theme.
3657
- */
3658
- function editorTheme(palette) {
3659
- return {
3660
- borderColor: palette.dim,
3661
- selectList: selectListTheme(palette)
3662
- };
3663
- }
3664
- //#endregion
3665
3731
  //#region lib/types/blocks.js
3666
3732
  /**
3667
3733
  * Transcript components: one pi-tui component per rendered fact (a user
@@ -4829,7 +4895,7 @@ var ToolBlock = class {
4829
4895
  marker: 0
4830
4896
  };
4831
4897
  }
4832
- const header = `${this.statusStyle()(TOOL_GLYPH)} ${palette.bold(this.toolName)}${this.call.title === "" ? "" : ` ${palette.link(this.call.title)}`}`;
4898
+ const header = `${this.statusStyle()(TOOL_GLYPH)} ${palette.bold(palette.tool(this.toolName))}${this.call.title === "" ? "" : ` ${palette.subject(this.call.title)}`}`;
4833
4899
  const loading = this.status === "running" ? ["…"] : [];
4834
4900
  const body = [
4835
4901
  ...this.call.lines,
@@ -4899,7 +4965,7 @@ var ToolBlock = class {
4899
4965
  }
4900
4966
  /**
4901
4967
  * The one row a folded subagent card draws, led by the status-coloured
4902
- * {@link SUBAGENT_RUNNING_GLYPH}. A running row carries the accent tool
4968
+ * {@link SUBAGENT_RUNNING_GLYPH}. A running row carries the cyan tool
4903
4969
  * name; a settled row is dim and ends on its outcome tag at the right edge:
4904
4970
  * `[failed]` for an error, `[started]` for a call that handed the child to
4905
4971
  * the background, whose result reads `started …` and whose glyph is dim,
@@ -4913,7 +4979,7 @@ var ToolBlock = class {
4913
4979
  const meta = facts.meta.length === 0 ? "" : ` ${palette.dim(facts.meta.join(" · "))}`;
4914
4980
  const description = facts.description === "" ? "" : ` ${facts.description}`;
4915
4981
  if (this.status === "running") {
4916
- const name = palette.bold(palette.accent(this.toolName));
4982
+ const name = palette.bold(palette.tool(this.toolName));
4917
4983
  return truncateToWidth(`${palette.warning("◆")} ${name}${description}${meta}`, width, "…");
4918
4984
  }
4919
4985
  const started = this.status === "done" && this.resultLines[0]?.startsWith("started ") === true;
@@ -6438,12 +6504,12 @@ function hotRow(usage, palette, frame) {
6438
6504
  */
6439
6505
  function categoryStyle(palette, id) {
6440
6506
  switch (id) {
6441
- case "system": return palette.dim;
6442
- case "tools": return palette.accent;
6443
- case "instructions": return palette.heading;
6444
- case "skills": return palette.warning;
6445
- case "context": return palette.success;
6446
- case "messages": return palette.link;
6507
+ case "system": return palette.hue.blue;
6508
+ case "tools": return palette.hue.cyan;
6509
+ case "instructions": return palette.hue.orange;
6510
+ case "skills": return palette.hue.yellow;
6511
+ case "context": return palette.hue.green;
6512
+ case "messages": return palette.hue.magenta;
6447
6513
  /* v8 ignore next 2 -- closed-union exhaustiveness guard */
6448
6514
  default: return assertNever(id, "context category");
6449
6515
  }
@@ -10541,7 +10607,7 @@ function unfocusedLine(segments, palette, width, queue) {
10541
10607
  return palette.dim(segment.label);
10542
10608
  });
10543
10609
  const drawn = middleFacts(facts, rest.length - facts.length, width - visibleWidth(model) - reserved);
10544
- const left = [model === "" ? "" : palette.accent(model), ...drawn].filter((token) => token !== "").join(palette.dim(SEPARATOR$2));
10610
+ const left = [model === "" ? "" : palette.model(model), ...drawn].filter((token) => token !== "").join(palette.dim(SEPARATOR$2));
10545
10611
  if (hint === "") return fitLine(left, width);
10546
10612
  return fitLine(`${left}${" ".repeat(Math.max(1, width - visibleWidth(left) - visibleWidth(hint)))}${paintKeys(palette, hint, palette.link)}`, width);
10547
10613
  }
@@ -11133,7 +11199,7 @@ function sectionName(block, part) {
11133
11199
  function restingHeader(block, part, palette) {
11134
11200
  const glyph = sectionGlyph(block, part);
11135
11201
  const name = sectionName(block, part);
11136
- if (block.blockKind === "tool" && part.kind === "call") return `${(settledTool(block) ? palette.success : palette.warning)(glyph)} ${palette.bold(block.name)}${palette.link(name.slice(block.name.length))}`;
11202
+ if (block.blockKind === "tool" && part.kind === "call") return `${(settledTool(block) ? palette.success : palette.warning)(glyph)} ${palette.bold(palette.tool(block.name))}${palette.subject(name.slice(block.name.length))}`;
11137
11203
  if (block.blockKind === "assistant" && part.kind === "reply") return `${palette.accent(glyph)} ${name}`;
11138
11204
  return palette.dim(`${glyph} ${name}`);
11139
11205
  }
@@ -12737,8 +12803,7 @@ function resolveColorDepth(input) {
12737
12803
  if (!input.paletteEnabled) return "none";
12738
12804
  const term = input.env.TERM ?? "";
12739
12805
  if (term === "dumb") return "none";
12740
- const colorterm = (input.env.COLORTERM ?? "").toLowerCase();
12741
- if (colorterm === "truecolor" || colorterm === "24bit") return "truecolor";
12806
+ if (declaresTruecolor(input.env)) return "truecolor";
12742
12807
  return term.includes("256color") ? "ansi256" : "none";
12743
12808
  }
12744
12809
  /**
@@ -13712,6 +13777,162 @@ function renderSubagentPanel(view, render) {
13712
13777
  return lines.join("\n");
13713
13778
  }
13714
13779
  //#endregion
13780
+ //#region lib/types/quit.js
13781
+ /**
13782
+ * The terminal's quit sequence: the census of what quitting stops, the order
13783
+ * and bound of the stop, and the report the runner turns into stderr lines and
13784
+ * an exit code. It touches no process facility: the runner supplies the output
13785
+ * sink, the force signal and the budget, and the timers are the global ones.
13786
+ * @module @deepseek-ai/dsh-tui-app/quit
13787
+ */
13788
+ /** The census of a terminal with nothing running. */
13789
+ const NO_WORK = {
13790
+ commands: 0,
13791
+ jobs: 0,
13792
+ subagents: 0
13793
+ };
13794
+ /**
13795
+ * Period of the "still stopping" notices. A presentation choice of this
13796
+ * terminal surface, not a deployment setting.
13797
+ */
13798
+ const QUIT_NOTICE_MS = 2e3;
13799
+ /**
13800
+ * Whether a census names no work.
13801
+ * @param work - the census.
13802
+ * @returns true when every count is zero.
13803
+ */
13804
+ function workIsIdle(work) {
13805
+ return work.commands === 0 && work.jobs === 0 && work.subagents === 0;
13806
+ }
13807
+ /**
13808
+ * Read a census that only words a notice: a registry already torn down counts
13809
+ * as nothing running.
13810
+ * @param read - the census source.
13811
+ * @returns the census, or {@link NO_WORK} when reading it throws.
13812
+ */
13813
+ function safeWork(read) {
13814
+ try {
13815
+ return read();
13816
+ } catch (_censusFailed) {
13817
+ return NO_WORK;
13818
+ }
13819
+ }
13820
+ function count(n, noun) {
13821
+ return `${String(n)} ${noun}${n === 1 ? "" : "s"}`;
13822
+ }
13823
+ /**
13824
+ * Word a census for a notice: commands, background jobs, then subagents, the
13825
+ * non-zero parts joined by `, `.
13826
+ * @param work - the census.
13827
+ * @returns the wording, or an empty string when nothing runs.
13828
+ */
13829
+ function describeWork(work) {
13830
+ const parts = [];
13831
+ if (work.commands > 0) parts.push(count(work.commands, "command"));
13832
+ if (work.jobs > 0) parts.push(count(work.jobs, "background job"));
13833
+ if (work.subagents > 0) parts.push(count(work.subagents, "subagent"));
13834
+ return parts.join(", ");
13835
+ }
13836
+ /**
13837
+ * Stop the session tree and report how it went. The order is cancel the
13838
+ * turn, wait for the Agent to go idle, flush the log, dispose the binding
13839
+ * (which stops owned jobs and subagents); each step is contained, so a failed
13840
+ * flush never skips dispose. The sequence is bounded by `graceMs` and ends
13841
+ * early when `forced` settles; whatever is still running then is left to the
13842
+ * caller's exit, and its late results are ignored.
13843
+ * @param env - the process facilities and budget.
13844
+ * @param initial - the census taken before anything stopped.
13845
+ * @returns the report; it never rejects.
13846
+ */
13847
+ async function runQuit(env, initial) {
13848
+ const say = (line) => {
13849
+ try {
13850
+ env.say(line);
13851
+ } catch (_sinkClosed) {}
13852
+ };
13853
+ const census = () => safeWork(() => env.work());
13854
+ if (!workIsIdle(initial)) say(`dsh: stopping ${describeWork(initial)} (Ctrl+C to force)`);
13855
+ const failures = [];
13856
+ let saved = false;
13857
+ const attempt = async (step, run) => {
13858
+ try {
13859
+ await run();
13860
+ return true;
13861
+ } catch (cause) {
13862
+ failures.push({
13863
+ step,
13864
+ cause
13865
+ });
13866
+ return false;
13867
+ }
13868
+ };
13869
+ const { agent } = env.bound;
13870
+ const sequence = (async () => {
13871
+ await attempt("cancel", () => {
13872
+ agent.cancel({ kind: "user" });
13873
+ return Promise.resolve();
13874
+ });
13875
+ await attempt("idle", () => agent.whenIdle());
13876
+ saved = await attempt("flush", () => env.flush());
13877
+ await attempt("dispose", () => env.bound.dispose());
13878
+ })();
13879
+ let budget;
13880
+ let notices;
13881
+ let winner;
13882
+ try {
13883
+ const timedOut = new Promise((resolve) => {
13884
+ budget = setTimeout(() => {
13885
+ resolve("timeout");
13886
+ }, env.graceMs);
13887
+ });
13888
+ notices = setInterval(() => {
13889
+ const work = census();
13890
+ if (!workIsIdle(work)) say(`dsh: still stopping ${describeWork(work)} (Ctrl+C to force)`);
13891
+ }, env.noticeMs);
13892
+ winner = await Promise.race([
13893
+ sequence.then(() => "done"),
13894
+ timedOut,
13895
+ env.forced
13896
+ ]);
13897
+ } finally {
13898
+ clearTimeout(budget);
13899
+ clearInterval(notices);
13900
+ }
13901
+ const forcedWork = typeof winner === "object" ? winner : void 0;
13902
+ return {
13903
+ timedOut: winner === "timeout",
13904
+ interrupted: forcedWork !== void 0,
13905
+ failures: [...failures],
13906
+ saved,
13907
+ remaining: forcedWork ?? census()
13908
+ };
13909
+ }
13910
+ /**
13911
+ * Map a report to what the user is told and how the process exits.
13912
+ * @param report - how the sequence ended.
13913
+ * @param details - the session to name in the hint, the budget the sequence ran under, and why the terminal quit.
13914
+ * @returns the stderr lines and the exit code: 130 when forced, 129 for a hangup, 1 for a timeout or a failed step, else 0.
13915
+ */
13916
+ function quitOutcome(report, details) {
13917
+ const lines = [];
13918
+ for (const failure of report.failures) {
13919
+ const what = failure.step === "flush" ? "saving the session failed" : "stopping failed";
13920
+ lines.push(`dsh: ${what}: ${describeFailure(failure.cause)}`);
13921
+ }
13922
+ const left = workIsIdle(report.remaining) ? "" : `; ${describeWork(report.remaining)} may still be running`;
13923
+ if (report.timedOut) lines.push(`dsh: gave up waiting after ${String(Math.round(details.graceMs / 1e3))}s${left}`);
13924
+ if (report.interrupted) lines.push(`dsh: forcing exit${left}`);
13925
+ if (report.saved) lines.push(`dsh: session ${details.sessionId} saved; resume with: dsh --profile tui --resume ${details.sessionId}`);
13926
+ let code = 0;
13927
+ if (report.interrupted) code = 130;
13928
+ else if (details.cause === "hangup") code = 129;
13929
+ else if (report.timedOut || report.failures.length > 0) code = 1;
13930
+ return {
13931
+ lines,
13932
+ code
13933
+ };
13934
+ }
13935
+ //#endregion
13715
13936
  //#region lib/types/toast.js
13716
13937
  /**
13717
13938
  * The transient key-feedback line: a framed notice that floats over the
@@ -13731,6 +13952,15 @@ function renderSubagentPanel(view, render) {
13731
13952
  * the tests that pin them read the same words.
13732
13953
  */
13733
13954
  const QUIT_TOAST = "press Ctrl+C again to quit";
13955
+ /**
13956
+ * What the line says while the quit is armed: {@link QUIT_TOAST}, followed
13957
+ * by what quitting would stop when anything runs.
13958
+ * @param work - the census taken when the quit was armed.
13959
+ * @returns the line, e.g. `press Ctrl+C again to quit · stops 1 command`.
13960
+ */
13961
+ function quitToast(work) {
13962
+ return workIsIdle(work) ? QUIT_TOAST : `${QUIT_TOAST} · stops ${describeWork(work)}`;
13963
+ }
13734
13964
  /** What the line says when the transcript holds nothing the reader could open. */
13735
13965
  const NOTHING_TO_READ_TOAST = "nothing in the transcript to read yet";
13736
13966
  /**
@@ -13930,8 +14160,6 @@ var ToastPane = class {
13930
14160
  * without discarding the terminal's scrollback (`./screen.ts`).
13931
14161
  * @module @deepseek-ai/dsh-tui-app/app
13932
14162
  */
13933
- /** A second Ctrl+C inside this window quits. */
13934
- const QUIT_DOUBLE_PRESS_MS = 600;
13935
14163
  /** Text drawn in the terminal's own colors, as a footer segment's detail rows are. */
13936
14164
  const plainText = (text) => text;
13937
14165
  /** What input reports while the host is opening another session. */
@@ -14450,6 +14678,8 @@ var TuiApp = class {
14450
14678
  escapeQuietUntil = 0;
14451
14679
  /** Until when a second editor `Escape` stops the running turn. */
14452
14680
  stopArmedUntil = 0;
14681
+ /** Until when a second `Ctrl+C` quits; the next key of any other kind drops the arm. */
14682
+ quitArmedUntil = 0;
14453
14683
  /** Abort of the in-flight user `!` command, when one is running. */
14454
14684
  shellAbort;
14455
14685
  /** Abort of the `/compact` this terminal dispatched and still waits on; `Esc` cancels it. */
@@ -14517,8 +14747,13 @@ var TuiApp = class {
14517
14747
  loaderActivity = "thinking";
14518
14748
  /** Tool names still streamed or executing, in first-seen order. */
14519
14749
  pendingToolNames = /* @__PURE__ */ new Map();
14520
- lastCtrlC = 0;
14521
14750
  stopped = false;
14751
+ /**
14752
+ * The root session handed to the host on quit. The quit releases the views
14753
+ * that named the root, and the census the host keeps reading while the stop
14754
+ * runs still counts under this one.
14755
+ */
14756
+ quitRoot;
14522
14757
  constructor(deps) {
14523
14758
  this.deps = deps;
14524
14759
  const palette = deps.palette;
@@ -14729,7 +14964,65 @@ var TuiApp = class {
14729
14964
  }
14730
14965
  /** Release the terminal and tell the host to exit; later calls are no-ops. */
14731
14966
  stop() {
14967
+ this.quit("user");
14968
+ }
14969
+ /**
14970
+ * Quit because the terminal went away (SIGHUP). It releases the terminal
14971
+ * and tells the host to exit as {@link TuiApp.stop} does, but the terminal
14972
+ * is taken to be gone: every write the quit makes to it, pi-tui's own
14973
+ * teardown included, is attempted and a failure is dropped. A no-op once the
14974
+ * terminal stopped.
14975
+ */
14976
+ hangup() {
14977
+ this.quit("hangup");
14978
+ }
14979
+ /**
14980
+ * Count what quitting stops right now, across the session tree: the root
14981
+ * session and every Agent the registry lists as owned by it or by one of
14982
+ * its descendants. The user's running `!` command and each live job a
14983
+ * foreground tool call registered for itself are commands; every other
14984
+ * live job of the tree is a background job, counted once although each
14985
+ * member's listing repeats the unowned ones; a descendant running a turn is
14986
+ * a subagent. It reads the registries synchronously and changes nothing; a
14987
+ * composition without a job registry counts no jobs. After the quit it
14988
+ * keeps counting under the root handed to the host.
14989
+ * @returns the census.
14990
+ */
14991
+ liveWork() {
14992
+ const { ctx } = this.deps;
14993
+ const family = [(this.quitRoot ?? this.parents[0] ?? this.bound).agent];
14994
+ const agents = ctx.get("agents");
14995
+ if (agents !== void 0) {
14996
+ const live = agents.list();
14997
+ for (const owner of family) for (const candidate of live) if (agents.isOwnedBy(candidate.id, owner)) family.push(candidate);
14998
+ }
14999
+ let commands = this.shellAbort === void 0 ? 0 : 1;
15000
+ let background = 0;
15001
+ const jobs = ctx.get("jobs");
15002
+ if (jobs !== void 0) {
15003
+ const counted = /* @__PURE__ */ new Set();
15004
+ for (const member of family) for (const job of jobs.list(member.session.id)) {
15005
+ if (!isLive(job) || counted.has(job.id)) continue;
15006
+ counted.add(job.id);
15007
+ if (this.backgrounder.isInner(job.id)) commands += 1;
15008
+ else background += 1;
15009
+ }
15010
+ }
15011
+ const subagents = family.slice(1).filter((member) => member.status === "running").length;
15012
+ return {
15013
+ commands,
15014
+ jobs: background,
15015
+ subagents
15016
+ };
15017
+ }
15018
+ /**
15019
+ * Release the terminal and hand the root session to the host, once.
15020
+ * @param cause - why the terminal quits; `hangup` takes the terminal to be gone.
15021
+ */
15022
+ quit(cause) {
14732
15023
  if (this.stopped) return;
15024
+ const work = this.liveWork();
15025
+ const gone = cause === "hangup";
14733
15026
  this.dropUserShell();
14734
15027
  this.dropCompaction();
14735
15028
  this.restoreQueueDraft();
@@ -14740,20 +15033,48 @@ var TuiApp = class {
14740
15033
  this.cancelPickers();
14741
15034
  for (const dispose of this.disposers.splice(0)) dispose();
14742
15035
  this.modals.withdrawActive();
14743
- this.dropReader();
15036
+ this.writeOnQuit(gone, () => {
15037
+ this.dropReader();
15038
+ });
14744
15039
  this.hideToast();
14745
- this.deps.terminal.write(SET_TERMINAL_DEFAULT_CURSOR);
14746
- this.tui.stop();
15040
+ this.writeOnQuit(gone, () => {
15041
+ this.deps.terminal.write(SET_TERMINAL_DEFAULT_CURSOR);
15042
+ });
15043
+ this.writeOnQuit(gone, () => {
15044
+ this.tui.stop();
15045
+ });
14747
15046
  this.deps.releaseInput();
14748
15047
  const [root, ...views] = [...this.parents, this.bound];
15048
+ this.quitRoot = root;
14749
15049
  for (const view of views.reverse()) view.dispose().catch((error) => {
14750
- this.deps.terminal.write(`releasing a subagent view failed: ${describeFailure(error)}\n`);
15050
+ this.writeOnQuit(gone, () => {
15051
+ this.deps.terminal.write(`releasing a subagent view failed: ${describeFailure(error)}\n`);
15052
+ });
14751
15053
  });
14752
15054
  this.parents.length = 0;
14753
15055
  this.viewLabels.length = 0;
14754
15056
  this.asides.clear();
14755
15057
  this.readOnlyViews.clear();
14756
- this.deps.onQuit(root);
15058
+ this.deps.onQuit(root, {
15059
+ work,
15060
+ cause
15061
+ });
15062
+ }
15063
+ /**
15064
+ * Run one quit step that writes to the terminal. After a hangup the
15065
+ * terminal can already be closed, so a failing step is dropped and the quit
15066
+ * goes on; otherwise the failure propagates.
15067
+ * @param gone - whether the terminal went away.
15068
+ * @param step - the step.
15069
+ */
15070
+ writeOnQuit(gone, step) {
15071
+ if (!gone) {
15072
+ step();
15073
+ return;
15074
+ }
15075
+ try {
15076
+ step();
15077
+ } catch (_terminalGone) {}
14757
15078
  }
14758
15079
  /** Draw `next` as the terminal's session: clear the transcript and replay its history. */
14759
15080
  bind(next) {
@@ -16102,6 +16423,9 @@ var TuiApp = class {
16102
16423
  */
16103
16424
  onKey(data) {
16104
16425
  if (isKeyRelease(data)) return { consume: true };
16426
+ const quitArmed = this.deps.now() < this.quitArmedUntil;
16427
+ this.quitArmedUntil = 0;
16428
+ if (quitArmed && !matchesKey(data, "ctrl+c")) this.hideToast();
16105
16429
  if (this.modals.isActive()) {
16106
16430
  if (!matchesKey(data, "ctrl+c")) return void 0;
16107
16431
  this.modals.withdrawActive();
@@ -16123,14 +16447,12 @@ var TuiApp = class {
16123
16447
  this.notice("queued prompt edit canceled");
16124
16448
  return { consume: true };
16125
16449
  }
16126
- const now = Date.now();
16127
- if (now - this.lastCtrlC < QUIT_DOUBLE_PRESS_MS) {
16450
+ if (quitArmed) {
16128
16451
  this.stop();
16129
16452
  return { consume: true };
16130
16453
  }
16131
- this.lastCtrlC = now;
16132
16454
  this.editor.setText("");
16133
- this.showToast(QUIT_TOAST);
16455
+ this.quitArmedUntil = this.deps.now() + this.showToast(quitToast(this.liveWork()));
16134
16456
  return { consume: true };
16135
16457
  }
16136
16458
  if (matchesKey(data, "ctrl+d")) {
@@ -19107,6 +19429,7 @@ const Config = z.object({
19107
19429
  readerMinColumns: z.natural().min(40).default(60),
19108
19430
  codeHighlight: z.boolean().default(true),
19109
19431
  toastMs: z.natural().min(500).default(TOAST_MS),
19432
+ quitGraceMs: z.natural().min(1e3).default(1e4),
19110
19433
  liveRefreshMs: z.natural().min(100).default(1e3),
19111
19434
  streamFadeSteps: z.natural().min(2).default(24),
19112
19435
  streamFadeStepMs: z.natural().min(16).default(16),
@@ -19129,8 +19452,21 @@ const internals = {
19129
19452
  },
19130
19453
  stderr: process.stderr,
19131
19454
  color: colorEnabled(process.env, process.stdout.isTTY),
19455
+ depth: paletteDepth(process.env),
19132
19456
  canOpenUrl: () => canOpenNativePath(),
19133
- openUrl: openNativeUrl
19457
+ openUrl: openNativeUrl,
19458
+ /* v8 ignore start -- process signals and streams are the host's; tests substitute recorders */
19459
+ onSignal: (signal, handler) => {
19460
+ process.on(signal, handler);
19461
+ return () => {
19462
+ process.off(signal, handler);
19463
+ };
19464
+ },
19465
+ swallowStreamErrors: () => {
19466
+ const ignore = () => {};
19467
+ process.stdout.on("error", ignore);
19468
+ process.stderr.on("error", ignore);
19469
+ }
19134
19470
  };
19135
19471
  /**
19136
19472
  * Events the terminal binds after the Agent has taken the write handle.
@@ -19375,12 +19711,12 @@ async function run(ctx, config, host) {
19375
19711
  const sessions = sessionHost(ctx, core, cwd, config);
19376
19712
  const initial = config.resume === void 0 ? await sessions.create() : await sessions.resume(brandString(config.resume));
19377
19713
  const openUrl = config.openBrowser && host.canOpenUrl() && !launchedThroughSsh(launchEnvironmentOf(ctx)) ? (url) => host.openUrl(url) : void 0;
19378
- new TuiApp({
19714
+ const app = new TuiApp({
19379
19715
  ctx,
19380
19716
  host: sessions,
19381
19717
  initial,
19382
19718
  terminal: host.createTerminal(),
19383
- palette: createPalette(host.color, config.mouse),
19719
+ palette: createPalette(host.color, config.mouse, host.depth),
19384
19720
  toolPreviewLines: config.toolPreviewLines,
19385
19721
  contextPreviewLines: config.contextPreviewLines,
19386
19722
  focusPreviewLines: config.focusPreviewLines,
@@ -19411,20 +19747,51 @@ async function run(ctx, config, host) {
19411
19747
  releaseInput: () => {
19412
19748
  host.releaseInput();
19413
19749
  },
19414
- onQuit: (bound) => {
19750
+ onQuit: (bound, request) => {
19415
19751
  (async () => {
19416
19752
  const { agent } = bound;
19417
- agent.cancel({ kind: "user" });
19418
- await agent.whenIdle();
19419
- await core.sessions.flush(agent.session);
19420
- host.stderr.write(`dsh: session ${agent.session.id} saved; resume with: dsh --profile tui --resume ${agent.session.id}\n`);
19421
- await bound.dispose();
19422
- host.exit(0);
19753
+ const interrupts = Promise.withResolvers();
19754
+ const stopListening = ctx.effect(() => host.onSignal("SIGINT", () => {
19755
+ interrupts.resolve(safeWork(() => app.liveWork()));
19756
+ }), "tui-app: quit interrupt");
19757
+ let outcome;
19758
+ try {
19759
+ outcome = quitOutcome(await runQuit({
19760
+ bound,
19761
+ work: () => app.liveWork(),
19762
+ flush: async () => {
19763
+ await core.sessions.flush(agent.session);
19764
+ },
19765
+ say: (line) => {
19766
+ host.stderr.write(`${line}\n`);
19767
+ },
19768
+ graceMs: config.quitGraceMs,
19769
+ noticeMs: QUIT_NOTICE_MS,
19770
+ forced: interrupts.promise
19771
+ }, request.work), {
19772
+ sessionId: agent.session.id,
19773
+ graceMs: config.quitGraceMs,
19774
+ cause: request.cause
19775
+ });
19776
+ } finally {
19777
+ stopListening();
19778
+ }
19779
+ for (const line of outcome.lines) host.stderr.write(`${line}\n`);
19780
+ host.exit(outcome.code);
19423
19781
  })().catch((error) => {
19424
19782
  fail(host, error);
19425
19783
  });
19426
19784
  }
19427
- }).start(config.prompt);
19785
+ });
19786
+ app.start(config.prompt);
19787
+ ctx.effect(() => host.onSignal("SIGHUP", () => {
19788
+ host.swallowStreamErrors();
19789
+ try {
19790
+ app.hangup();
19791
+ } catch (error) {
19792
+ fail(host, error);
19793
+ }
19794
+ }), "tui-app: terminal hangup");
19428
19795
  }
19429
19796
  /**
19430
19797
  * Mount the terminal runner.
@@ -19439,8 +19806,11 @@ function apply(ctx, config) {
19439
19806
  releaseInput: internals.releaseInput,
19440
19807
  stderr: internals.stderr,
19441
19808
  color: internals.color,
19809
+ depth: internals.depth,
19442
19810
  canOpenUrl: internals.canOpenUrl,
19443
19811
  openUrl: internals.openUrl,
19812
+ onSignal: internals.onSignal,
19813
+ swallowStreamErrors: internals.swallowStreamErrors,
19444
19814
  exit
19445
19815
  };
19446
19816
  run(ctx, config, host).catch((error) => {