@songtonyli/dsh-cli 0.1.81 → 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 +25 -8
  38. package/node_modules/@deepseek-ai/dsh-tui-app/README.zh.md +25 -8
  39. package/node_modules/@deepseek-ai/dsh-tui-app/lib/index.js +325 -22
  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
@@ -13777,6 +13777,162 @@ function renderSubagentPanel(view, render) {
13777
13777
  return lines.join("\n");
13778
13778
  }
13779
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
13780
13936
  //#region lib/types/toast.js
13781
13937
  /**
13782
13938
  * The transient key-feedback line: a framed notice that floats over the
@@ -13796,6 +13952,15 @@ function renderSubagentPanel(view, render) {
13796
13952
  * the tests that pin them read the same words.
13797
13953
  */
13798
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
+ }
13799
13964
  /** What the line says when the transcript holds nothing the reader could open. */
13800
13965
  const NOTHING_TO_READ_TOAST = "nothing in the transcript to read yet";
13801
13966
  /**
@@ -13995,8 +14160,6 @@ var ToastPane = class {
13995
14160
  * without discarding the terminal's scrollback (`./screen.ts`).
13996
14161
  * @module @deepseek-ai/dsh-tui-app/app
13997
14162
  */
13998
- /** A second Ctrl+C inside this window quits. */
13999
- const QUIT_DOUBLE_PRESS_MS = 600;
14000
14163
  /** Text drawn in the terminal's own colors, as a footer segment's detail rows are. */
14001
14164
  const plainText = (text) => text;
14002
14165
  /** What input reports while the host is opening another session. */
@@ -14515,6 +14678,8 @@ var TuiApp = class {
14515
14678
  escapeQuietUntil = 0;
14516
14679
  /** Until when a second editor `Escape` stops the running turn. */
14517
14680
  stopArmedUntil = 0;
14681
+ /** Until when a second `Ctrl+C` quits; the next key of any other kind drops the arm. */
14682
+ quitArmedUntil = 0;
14518
14683
  /** Abort of the in-flight user `!` command, when one is running. */
14519
14684
  shellAbort;
14520
14685
  /** Abort of the `/compact` this terminal dispatched and still waits on; `Esc` cancels it. */
@@ -14582,8 +14747,13 @@ var TuiApp = class {
14582
14747
  loaderActivity = "thinking";
14583
14748
  /** Tool names still streamed or executing, in first-seen order. */
14584
14749
  pendingToolNames = /* @__PURE__ */ new Map();
14585
- lastCtrlC = 0;
14586
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;
14587
14757
  constructor(deps) {
14588
14758
  this.deps = deps;
14589
14759
  const palette = deps.palette;
@@ -14794,7 +14964,65 @@ var TuiApp = class {
14794
14964
  }
14795
14965
  /** Release the terminal and tell the host to exit; later calls are no-ops. */
14796
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) {
14797
15023
  if (this.stopped) return;
15024
+ const work = this.liveWork();
15025
+ const gone = cause === "hangup";
14798
15026
  this.dropUserShell();
14799
15027
  this.dropCompaction();
14800
15028
  this.restoreQueueDraft();
@@ -14805,20 +15033,48 @@ var TuiApp = class {
14805
15033
  this.cancelPickers();
14806
15034
  for (const dispose of this.disposers.splice(0)) dispose();
14807
15035
  this.modals.withdrawActive();
14808
- this.dropReader();
15036
+ this.writeOnQuit(gone, () => {
15037
+ this.dropReader();
15038
+ });
14809
15039
  this.hideToast();
14810
- this.deps.terminal.write(SET_TERMINAL_DEFAULT_CURSOR);
14811
- 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
+ });
14812
15046
  this.deps.releaseInput();
14813
15047
  const [root, ...views] = [...this.parents, this.bound];
15048
+ this.quitRoot = root;
14814
15049
  for (const view of views.reverse()) view.dispose().catch((error) => {
14815
- 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
+ });
14816
15053
  });
14817
15054
  this.parents.length = 0;
14818
15055
  this.viewLabels.length = 0;
14819
15056
  this.asides.clear();
14820
15057
  this.readOnlyViews.clear();
14821
- 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) {}
14822
15078
  }
14823
15079
  /** Draw `next` as the terminal's session: clear the transcript and replay its history. */
14824
15080
  bind(next) {
@@ -16167,6 +16423,9 @@ var TuiApp = class {
16167
16423
  */
16168
16424
  onKey(data) {
16169
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();
16170
16429
  if (this.modals.isActive()) {
16171
16430
  if (!matchesKey(data, "ctrl+c")) return void 0;
16172
16431
  this.modals.withdrawActive();
@@ -16188,14 +16447,12 @@ var TuiApp = class {
16188
16447
  this.notice("queued prompt edit canceled");
16189
16448
  return { consume: true };
16190
16449
  }
16191
- const now = Date.now();
16192
- if (now - this.lastCtrlC < QUIT_DOUBLE_PRESS_MS) {
16450
+ if (quitArmed) {
16193
16451
  this.stop();
16194
16452
  return { consume: true };
16195
16453
  }
16196
- this.lastCtrlC = now;
16197
16454
  this.editor.setText("");
16198
- this.showToast(QUIT_TOAST);
16455
+ this.quitArmedUntil = this.deps.now() + this.showToast(quitToast(this.liveWork()));
16199
16456
  return { consume: true };
16200
16457
  }
16201
16458
  if (matchesKey(data, "ctrl+d")) {
@@ -19172,6 +19429,7 @@ const Config = z.object({
19172
19429
  readerMinColumns: z.natural().min(40).default(60),
19173
19430
  codeHighlight: z.boolean().default(true),
19174
19431
  toastMs: z.natural().min(500).default(TOAST_MS),
19432
+ quitGraceMs: z.natural().min(1e3).default(1e4),
19175
19433
  liveRefreshMs: z.natural().min(100).default(1e3),
19176
19434
  streamFadeSteps: z.natural().min(2).default(24),
19177
19435
  streamFadeStepMs: z.natural().min(16).default(16),
@@ -19196,7 +19454,19 @@ const internals = {
19196
19454
  color: colorEnabled(process.env, process.stdout.isTTY),
19197
19455
  depth: paletteDepth(process.env),
19198
19456
  canOpenUrl: () => canOpenNativePath(),
19199
- 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
+ }
19200
19470
  };
19201
19471
  /**
19202
19472
  * Events the terminal binds after the Agent has taken the write handle.
@@ -19441,7 +19711,7 @@ async function run(ctx, config, host) {
19441
19711
  const sessions = sessionHost(ctx, core, cwd, config);
19442
19712
  const initial = config.resume === void 0 ? await sessions.create() : await sessions.resume(brandString(config.resume));
19443
19713
  const openUrl = config.openBrowser && host.canOpenUrl() && !launchedThroughSsh(launchEnvironmentOf(ctx)) ? (url) => host.openUrl(url) : void 0;
19444
- new TuiApp({
19714
+ const app = new TuiApp({
19445
19715
  ctx,
19446
19716
  host: sessions,
19447
19717
  initial,
@@ -19477,20 +19747,51 @@ async function run(ctx, config, host) {
19477
19747
  releaseInput: () => {
19478
19748
  host.releaseInput();
19479
19749
  },
19480
- onQuit: (bound) => {
19750
+ onQuit: (bound, request) => {
19481
19751
  (async () => {
19482
19752
  const { agent } = bound;
19483
- agent.cancel({ kind: "user" });
19484
- await agent.whenIdle();
19485
- await core.sessions.flush(agent.session);
19486
- host.stderr.write(`dsh: session ${agent.session.id} saved; resume with: dsh --profile tui --resume ${agent.session.id}\n`);
19487
- await bound.dispose();
19488
- 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);
19489
19781
  })().catch((error) => {
19490
19782
  fail(host, error);
19491
19783
  });
19492
19784
  }
19493
- }).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");
19494
19795
  }
19495
19796
  /**
19496
19797
  * Mount the terminal runner.
@@ -19508,6 +19809,8 @@ function apply(ctx, config) {
19508
19809
  depth: internals.depth,
19509
19810
  canOpenUrl: internals.canOpenUrl,
19510
19811
  openUrl: internals.openUrl,
19812
+ onSignal: internals.onSignal,
19813
+ swallowStreamErrors: internals.swallowStreamErrors,
19511
19814
  exit
19512
19815
  };
19513
19816
  run(ctx, config, host).catch((error) => {
@@ -1,16 +1,17 @@
1
1
  import {Duplex} from 'node:stream';
2
2
  import {callbackify} from 'node:util';
3
3
  import {BINARY_ENCODINGS} from '../arguments/encoding-option.js';
4
+ import {getFromStream, getToStream} from '../arguments/fd-options.js';
4
5
  import {copyOptions, checkBooleanOption} from '../utils/options.js';
6
+ import {addConcurrentStream} from './concurrent.js';
5
7
  import {
6
- getSubprocessStdout,
7
8
  getReadableOptions,
8
9
  getReadableMethods,
9
10
  onStdoutFinished,
10
11
  onReadableDestroy,
11
12
  } from './readable.js';
12
13
  import {
13
- getSubprocessStdin,
14
+ addWritableConcurrentStreams,
14
15
  getWritableMethods,
15
16
  onStdinFinished,
16
17
  onWritableDestroy,
@@ -22,8 +23,11 @@ export const createDuplex = ({subprocess, concurrentStreams, encoding}, options)
22
23
  checkBooleanOption(binaryOption, 'binary');
23
24
  checkBooleanOption(preserveNewlines, 'preserveNewlines');
24
25
  const binary = binaryOption || BINARY_ENCODINGS.has(encoding);
25
- const {subprocessStdout, waitReadableDestroy} = getSubprocessStdout(subprocess, from, concurrentStreams);
26
- const {subprocessStdin, waitWritableFinal, waitWritableDestroy} = getSubprocessStdin(subprocess, to, concurrentStreams);
26
+ // Validate both directions before registering lifecycle waits, since a thrown option error must not leave a concurrent stream behind.
27
+ const subprocessStdout = getFromStream(subprocess, from);
28
+ const subprocessStdin = getToStream(subprocess, to);
29
+ const waitReadableDestroy = addConcurrentStream(concurrentStreams, subprocessStdout, 'readableDestroy');
30
+ const {waitWritableFinal, waitWritableDestroy} = addWritableConcurrentStreams(concurrentStreams, subprocessStdin);
27
31
  const {readableEncoding, readableObjectMode, readableHighWaterMark} = getReadableOptions(subprocessStdout, binary);
28
32
  const {read, onStdoutDataDone} = getReadableMethods({
29
33
  subprocessStdout,
@@ -19,7 +19,9 @@ export const createReadable = ({subprocess, concurrentStreams, encoding}, option
19
19
  checkBooleanOption(binaryOption, 'binary');
20
20
  checkBooleanOption(preserveNewlines, 'preserveNewlines');
21
21
  const binary = binaryOption || BINARY_ENCODINGS.has(encoding);
22
- const {subprocessStdout, waitReadableDestroy} = getSubprocessStdout(subprocess, from, concurrentStreams);
22
+ // Retrieve `stdout` (or other stream depending on `from`)
23
+ const subprocessStdout = getFromStream(subprocess, from);
24
+ const waitReadableDestroy = addConcurrentStream(concurrentStreams, subprocessStdout, 'readableDestroy');
23
25
  const {readableEncoding, readableObjectMode, readableHighWaterMark} = getReadableOptions(subprocessStdout, binary);
24
26
  const {read, onStdoutDataDone} = getReadableMethods({
25
27
  subprocessStdout,
@@ -44,13 +46,6 @@ export const createReadable = ({subprocess, concurrentStreams, encoding}, option
44
46
  return readable;
45
47
  };
46
48
 
47
- // Retrieve `stdout` (or other stream depending on `from`)
48
- export const getSubprocessStdout = (subprocess, from, concurrentStreams) => {
49
- const subprocessStdout = getFromStream(subprocess, from);
50
- const waitReadableDestroy = addConcurrentStream(concurrentStreams, subprocessStdout, 'readableDestroy');
51
- return {subprocessStdout, waitReadableDestroy};
52
- };
53
-
54
49
  export const getReadableOptions = ({readableEncoding, readableObjectMode, readableHighWaterMark}, binary) => binary
55
50
  ? {readableEncoding, readableObjectMode, readableHighWaterMark}
56
51
  : {readableEncoding, readableObjectMode: true, readableHighWaterMark: DEFAULT_OBJECT_HIGH_WATER_MARK};
@@ -14,7 +14,9 @@ import {
14
14
  // Create a `Writable` stream that forwards to `stdin` and awaits the subprocess
15
15
  export const createWritable = ({subprocess, concurrentStreams}, options) => {
16
16
  const {to} = copyOptions(options);
17
- const {subprocessStdin, waitWritableFinal, waitWritableDestroy} = getSubprocessStdin(subprocess, to, concurrentStreams);
17
+ // Retrieve `stdin` (or other stream depending on `to`)
18
+ const subprocessStdin = getToStream(subprocess, to);
19
+ const {waitWritableFinal, waitWritableDestroy} = addWritableConcurrentStreams(concurrentStreams, subprocessStdin);
18
20
  const writable = new Writable({
19
21
  ...getWritableMethods(subprocessStdin, subprocess, waitWritableFinal),
20
22
  destroy: callbackify(onWritableDestroy.bind(undefined, {
@@ -30,12 +32,11 @@ export const createWritable = ({subprocess, concurrentStreams}, options) => {
30
32
  return writable;
31
33
  };
32
34
 
33
- // Retrieve `stdin` (or other stream depending on `to`)
34
- export const getSubprocessStdin = (subprocess, to, concurrentStreams) => {
35
- const subprocessStdin = getToStream(subprocess, to);
35
+ // Register both writable lifecycle waits for an already validated stream.
36
+ export const addWritableConcurrentStreams = (concurrentStreams, subprocessStdin) => {
36
37
  const waitWritableFinal = addConcurrentStream(concurrentStreams, subprocessStdin, 'writableFinal');
37
38
  const waitWritableDestroy = addConcurrentStream(concurrentStreams, subprocessStdin, 'writableDestroy');
38
- return {subprocessStdin, waitWritableFinal, waitWritableDestroy};
39
+ return {waitWritableFinal, waitWritableDestroy};
39
40
  };
40
41
 
41
42
  export const getWritableMethods = (subprocessStdin, subprocess, waitWritableFinal) => ({
@@ -17,7 +17,8 @@ const getInputFdNumbers = fileDescriptors => new Set(Object.entries(fileDescript
17
17
  const addInputOptionSync = (fileDescriptors, fdNumber, options) => {
18
18
  const {stdioItems} = fileDescriptors[fdNumber];
19
19
  const allStdioItems = stdioItems.filter(({contents}) => contents !== undefined);
20
- if (allStdioItems.length === 0) {
20
+ // Even without an input source, generators must run so that `final` can produce input or report errors.
21
+ if (allStdioItems.length === 0 && stdioItems.every(({type}) => type !== 'generator')) {
21
22
  return;
22
23
  }
23
24
 
@@ -63,7 +63,8 @@ const getMaxBufferInfo = (error, maxBuffer) => {
63
63
  // The native `maxBuffer` option passed to `spawnSync()` does not allow differentiating values per file descriptor, so we use `stdout`'s.
64
64
  // Since each other file descriptor's own limit is capped by `stdout`'s, this is also the highest one.
65
65
  // Node.js applies it to the total output of all piped file descriptors, not to each of them. When it is hit, the subprocess is killed and a `ENOBUFS` error is thrown.
66
- export const getMaxBufferSync = ([, stdoutMaxBuffer]) => stdoutMaxBuffer;
66
+ // Node.js disables its limit at zero, so use the smallest positive value to reject the first output byte.
67
+ export const getMaxBufferSync = ([, stdoutMaxBuffer]) => stdoutMaxBuffer === 0 ? Number.MIN_VALUE : stdoutMaxBuffer;
67
68
 
68
69
  // File descriptors with a limit lower than `spawnSync()`'s native `maxBuffer` are enforced from the output, after the subprocess exits.
69
70
  // Since no native error was thrown, we create the `ENOBUFS` error ourselves.
@@ -83,7 +83,8 @@ const runOutputGeneratorsSync = (chunks, stdioItems, encoding) => {
83
83
  // `error` is set, so that a polluted `Object.prototype.error` is not read when destructuring
84
84
  return {chunks: runGeneratorsSync(chunks, stdioItems, encoding, false), error: undefined};
85
85
  } catch (error) {
86
- return {chunks, error};
86
+ // Raw output must not bypass a failed transform, which might be filtering sensitive data.
87
+ return {chunks: [], error};
87
88
  }
88
89
  };
89
90
 
@@ -50,6 +50,13 @@ const parseArguments = ({mapArguments, firstArgument, nextArguments, deepOptions
50
50
  : [firstArgument, ...nextArguments];
51
51
  const [initialFile, initialArguments, initialOptions] = normalizeParameters(...callArguments);
52
52
  const mergedOptions = mergeOptions(mergeOptions(deepOptions, boundOptions), initialOptions);
53
+ // Explicit `undefined` resets to the method's default, including on pipe destinations.
54
+ for (const [optionName, optionValue] of Object.entries(deepOptions)) {
55
+ if (mergedOptions[optionName] === undefined) {
56
+ mergedOptions[optionName] = optionValue;
57
+ }
58
+ }
59
+
53
60
  // `mapArguments()` returns a plain object, so its result is read from a null-prototype copy.
54
61
  // Otherwise a polluted `Object.prototype` would replace every option, or switch the execution mode.
55
62
  const {
@@ -32,7 +32,7 @@ const getDefaultNodeOptions = () => {
32
32
 
33
33
  // Those options are followed by a separate value, which is removed too
34
34
  const REMOVED_OPTIONS_WITH_VALUE = new Set(['-e', '--eval', '-p', '--print', '-pe', '--input-type', '--inspect-port']);
35
- const IGNORED_OPTIONS_REGEXP = /^--(?:inspect|eval=|input-type=)/;
35
+ const IGNORED_OPTIONS_REGEXP = /^--(?:inspect|eval=|print=|input-type=)/;
36
36
 
37
37
  // Applies the `node: true` option, and the related `nodePath`/`nodeOptions` options.
38
38
  // Modifies the file commands/arguments to ensure the same Node binary and flags are re-used.
@@ -11,10 +11,10 @@ export const mapScriptAsync = ({options}) => getScriptOptions(options);
11
11
  const mapScriptSync = ({options}) => ({...getScriptOptions(options), isSync: true});
12
12
 
13
13
  // `$` is like `execa` but with script-friendly options: `{stdin: 'inherit', preferLocal: true}`
14
- const getScriptOptions = options => ({options: {__proto__: null, ...getScriptStdinOption(options), ...options}});
14
+ const getScriptOptions = options => ({options: {__proto__: null, ...options, ...getScriptStdinOption(options)}});
15
15
 
16
- const getScriptStdinOption = ({input, inputFile, stdio}) => input === undefined && inputFile === undefined && stdio === undefined
17
- ? {stdin: 'inherit'}
16
+ const getScriptStdinOption = ({stdin = 'inherit', input, inputFile, stdio}) => input === undefined && inputFile === undefined && stdio === undefined
17
+ ? {stdin}
18
18
  : {};
19
19
 
20
20
  // When using $(...).pipe(...), most script-friendly options should apply to both commands.
@@ -32,7 +32,8 @@ export const waitForAllStream = ({subprocess, all, encoding, buffer, maxBuffer,
32
32
  maxBuffer: maxBuffer[1] + maxBuffer[2],
33
33
  lines: lines[1] || lines[2],
34
34
  allFds: getAllFds(subprocess, buffer),
35
- allMixed: getAllMixed(subprocess, all),
35
+ // A single buffered descriptor keeps its own object mode, even when the merged stream has mixed modes.
36
+ allMixed: stream === all && getAllMixed(subprocess, all),
36
37
  stripFinalNewline,
37
38
  verboseInfo,
38
39
  streamInfo,
@@ -1,5 +1,6 @@
1
1
  import {once} from 'node:events';
2
2
  import {isStream as isNodeStream} from 'is-stream';
3
+ import {MaxBufferError} from 'get-stream';
3
4
  import {throwOnTimeout} from '../terminate/timeout.js';
4
5
  import {throwOnCancel} from '../terminate/cancel.js';
5
6
  import {throwOnGracefulCancel} from '../terminate/graceful.js';
@@ -114,6 +115,11 @@ export const waitForSubprocessResult = async ({
114
115
  ]);
115
116
  } catch (error) {
116
117
  context.terminationReason ??= 'other';
118
+ // Closing the output stream does not stop a subprocess that stays alive without writing again.
119
+ if (error instanceof MaxBufferError) {
120
+ kill();
121
+ }
122
+
117
123
  return Promise.all([
118
124
  {error},
119
125
  exitPromise,
@@ -68,7 +68,7 @@ const addPropertiesAsync = {
68
68
  asyncGenerator: generatorToInputStream,
69
69
  fileUrl: ({value}) => ({stream: createReadStream(value)}),
70
70
  filePath: ({value: {file}}) => ({stream: createReadStream(file)}),
71
- webStream: ({value}) => ({stream: Readable.fromWeb(value)}),
71
+ webStream: ({value}, options, objectMode) => ({stream: Readable.fromWeb(value, {objectMode})}),
72
72
  iterable: ({value, optionName}, options, objectMode) => ({stream: Readable.from(objectMode ? value : validateIterable(value, optionName))}),
73
73
  asyncIterable: ({value, optionName}, options, objectMode) => ({stream: Readable.from(objectMode ? value : validateAsyncIterable(value, optionName))}),
74
74
  string: ({value}) => ({stream: readableFromChunk(value)}),
@@ -78,7 +78,8 @@ const addPropertiesAsync = {
78
78
  ...addProperties,
79
79
  fileUrl: ({value}) => ({stream: createWriteStream(value)}),
80
80
  filePath: ({value: {file, append}}) => ({stream: createWriteStream(file, append ? {flags: 'a'} : {})}),
81
- webStream: ({value}) => ({stream: Writable.fromWeb(value)}),
81
+ // Web writers accept arbitrary chunks, including when a shared writer receives both bytes and objects.
82
+ webStream: ({value}) => ({stream: Writable.fromWeb(value, {objectMode: true})}),
82
83
  iterable: forbiddenIfAsync,
83
84
  asyncIterable: forbiddenIfAsync,
84
85
  string: forbiddenIfAsync,