@aiwayds/dsh-opentui 0.9.6 → 0.9.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,27 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [0.9.8] - 2026-11-12
9
+
10
+ ### Fixed
11
+
12
+ - Upgrading from pre-0.9.x profiles no longer breaks plugin installs: a leftover `patchedDependencies` entry whose package is gone is retired automatically during provisioning.
13
+ - Provisioning no longer retries plugin installs that can never succeed (e.g. `ERR_PNPM_UNUSED_PATCH`); those now fail fast with an actionable hint while transient network failures keep retrying.
14
+
15
+ ## [0.9.7] - 2026-11-12
16
+
17
+ ### Fixed
18
+
19
+ - **Picking a model now applies it** — the picked route was read back through the staged value but the application step swallowed it, so a selection could silently fall back to the catalog default. Selection failures now surface in the transcript instead of vanishing into a console log, and bare `/model` asks for the effort level as one flow (`esc` abandons the whole pick).
20
+ - **The spin attention feed is back** — the per-turn attention feed lost in an earlier refactor is restored, refreshed at most once every 5 seconds.
21
+ - **The client bundle packs reliably** — the attention feed's optional probe import tripped the bundle leak guard in prepack; the probe specifier is now pinned so packaging succeeds, and a missing `@aiwayds/dsh-jev-core` still degrades silently at runtime.
22
+ - **Cold install retries a failed plugin add** — one flaky `pnpm add` used to be warned about and skipped, leaving the profile short a plugin; each failed spec is retried up to 3 times with a 5-second backoff and a final failure stays loud.
23
+ - **`ctrl+alt+f` opens session search** — keybind parity with `dsh-tui-pi`; `page.down` keeps pagedown.
24
+
25
+ ### Changed
26
+
27
+ - **Cold plugin installs no longer false-fail on slow networks** — the e2e install wait for the npm-installed bin leg now allows up to 10 minutes (registry served 1.7–2.1 KB/s when measured), replacing the 3-minute timeout that fired before the 14-package install finished; the e2e round-limit staging also targets the profile `config.json` top-level keys the client ladder actually reads.
28
+
8
29
  ## [0.9.6] - 2026-11-11
9
30
 
10
31
  ### Added
@@ -6277,6 +6277,22 @@ var init_remote_attachments = __esm(() => {
6277
6277
 
6278
6278
  // src/client/remote-btw.ts
6279
6279
  import { randomUUID as randomUUID2 } from "crypto";
6280
+ import { appendFileSync } from "fs";
6281
+ function btwTrace(message) {
6282
+ const line = `[btw ${new Date().toISOString().slice(11, 23)}] ${message}
6283
+ `;
6284
+ if (process.env.DSH_OPENTUI_DEBUG)
6285
+ process.stderr.write(line);
6286
+ const path = process.env.DSH_OPENTUI_TRACE_FILE;
6287
+ if (!path)
6288
+ return;
6289
+ try {
6290
+ appendFileSync(path, line);
6291
+ } catch {}
6292
+ }
6293
+ function btwOutPreview(out) {
6294
+ return `out len=${out.length} head=${JSON.stringify(out.slice(0, 40))} tail=${JSON.stringify(out.slice(-40))}`;
6295
+ }
6280
6296
  async function askBtw(options) {
6281
6297
  const timeoutMs = options.timeoutMs ?? 120000;
6282
6298
  let sessionId = options.previousSessionId ?? "";
@@ -6297,6 +6313,10 @@ async function askBtw(options) {
6297
6313
  let pump;
6298
6314
  let timer;
6299
6315
  let promptFailure;
6316
+ let deltas = 0;
6317
+ let turnEnds = 0;
6318
+ let streamEnds = 0;
6319
+ let streamFails = 0;
6300
6320
  const settle = (errorText) => {
6301
6321
  if (settled)
6302
6322
  return;
@@ -6309,11 +6329,13 @@ async function askBtw(options) {
6309
6329
  }).catch(() => {});
6310
6330
  };
6311
6331
  const answer = await new Promise((resolve) => {
6312
- const finish = (errorText) => {
6332
+ const finish = (errorText, why) => {
6333
+ if (!settled)
6334
+ btwTrace(`settle why=${why} err=${errorText !== undefined} deltas=${deltas} turnEnds=${turnEnds} streamEnds=${streamEnds} streamFails=${streamFails} ${btwOutPreview(out)}${deltas === 0 && errorText === undefined ? " EARLY-EMPTY-SETTLE" : ""}`);
6313
6335
  settle(errorText);
6314
6336
  resolve(errorText !== undefined ? errorText : out.trim());
6315
6337
  };
6316
- timer = setTimeout(() => finish(undefined), timeoutMs);
6338
+ timer = setTimeout(() => finish(undefined, "timeout"), timeoutMs);
6317
6339
  timer.unref?.();
6318
6340
  pump = openRemoteStream(options.socketFactory, "session/follow", { request: { address: { kind: "session", sessionId }, assistantStream: true } }, {
6319
6341
  onItem: (value) => {
@@ -6325,6 +6347,7 @@ async function askBtw(options) {
6325
6347
  const chunk = typeof streamFrame.chunk === "object" && streamFrame.chunk !== null ? streamFrame.chunk : {};
6326
6348
  if (chunk.type === "text-delta" && typeof chunk.text === "string" && chunk.text) {
6327
6349
  out += chunk.text;
6350
+ deltas += 1;
6328
6351
  try {
6329
6352
  options.onDelta?.(out);
6330
6353
  } catch {}
@@ -6337,16 +6360,26 @@ async function askBtw(options) {
6337
6360
  return;
6338
6361
  const data = typeof event.data === "object" && event.data !== null ? event.data : {};
6339
6362
  const reason = typeof data.reason === "object" && data.reason !== null ? data.reason : {};
6363
+ turnEnds += 1;
6364
+ btwTrace(`recv turn/end #${turnEnds} reason=${JSON.stringify(reason.kind ?? null)} out=${out.length}`);
6340
6365
  if (reason.kind === "error") {
6341
6366
  const err = typeof reason.error === "object" && reason.error !== null ? reason.error : {};
6342
- finish(`error: ${String(err.message ?? "unknown").slice(0, 200)}`);
6367
+ finish(`error: ${String(err.message ?? "unknown").slice(0, 200)}`, "turn-end-error");
6343
6368
  return;
6344
6369
  }
6345
- finish(undefined);
6370
+ finish(undefined, "turn-end");
6346
6371
  }
6347
6372
  },
6348
- onEnd: () => finish(undefined),
6349
- onFailed: () => finish(undefined)
6373
+ onEnd: () => {
6374
+ streamEnds += 1;
6375
+ btwTrace(`recv stream-end #${streamEnds} out=${out.length}`);
6376
+ finish(undefined, "stream-end");
6377
+ },
6378
+ onFailed: (error) => {
6379
+ streamFails += 1;
6380
+ btwTrace(`recv stream-failed #${streamFails} ${btwOutPreview(out)} err=${String(error?.message ?? error)}`);
6381
+ finish(undefined, "stream-failed");
6382
+ }
6350
6383
  });
6351
6384
  const snap = options.snapshot.length > 0 ? `Recent conversation context (for reference only):
6352
6385
  ${options.snapshot.join(`
@@ -6362,7 +6395,7 @@ ${options.snapshot.join(`
6362
6395
  }
6363
6396
  }).then(() => {}, (error) => {
6364
6397
  promptFailure = { error };
6365
- finish(undefined);
6398
+ finish(undefined, "prompt-rejected");
6366
6399
  });
6367
6400
  });
6368
6401
  if (promptFailure !== undefined) {
@@ -6617,6 +6650,131 @@ var init_subagent_policy = __esm(() => {
6617
6650
  FOREGROUND_LABEL_PREFIXES = ["[fg] ", "[use_agent foreground] "];
6618
6651
  });
6619
6652
 
6653
+ // src/spin-attention.ts
6654
+ async function loadJevCore() {
6655
+ try {
6656
+ const mod = await import("@aiwayds/dsh-jev-core");
6657
+ if (typeof mod.classify !== "function" || typeof mod.isConfigured !== "function")
6658
+ return null;
6659
+ return mod;
6660
+ } catch {
6661
+ return null;
6662
+ }
6663
+ }
6664
+ function buildSpinQuestions(id8s) {
6665
+ const questions = {};
6666
+ for (const id8 of id8s) {
6667
+ questions[`spin_${id8}`] = {
6668
+ type: "noul",
6669
+ criteria: {
6670
+ true: "work is UNPRODUCTIVE \u2014 repeating the same tools or circling without forward motion",
6671
+ false: "work is productive \u2014 measurable forward progress"
6672
+ }
6673
+ };
6674
+ }
6675
+ return questions;
6676
+ }
6677
+ function buildSpinState(views, cap, now) {
6678
+ const lines = views.map((view) => {
6679
+ const parts = [
6680
+ `${view.childId.slice(0, 8)} ${view.label.slice(0, SPIN_LABEL_MAX_CHARS)}`,
6681
+ `rounds ${view.rounds}/${cap > 0 ? cap : "\u221E"}`,
6682
+ ...view.startedAt !== undefined ? [`elapsed ${Math.round(Math.max(0, now - view.startedAt) / 1000)}s`] : []
6683
+ ];
6684
+ return `- ${parts.join(" | ")}`;
6685
+ });
6686
+ const head = "Subagents under supervision; judge each child on the question keyed by its id.";
6687
+ return `${head}
6688
+ ${lines.join(`
6689
+ `)}`.slice(0, SPIN_STATE_MAX_CHARS);
6690
+ }
6691
+ function parseSpinAnswers(answers, id8ToChild) {
6692
+ const out = [];
6693
+ for (const [id8, childId] of id8ToChild) {
6694
+ const answer = answers[`spin_${id8}`];
6695
+ if (answer === undefined || typeof answer.value !== "number" || !Number.isFinite(answer.value))
6696
+ continue;
6697
+ out.push([childId, answer.value]);
6698
+ }
6699
+ return out;
6700
+ }
6701
+ function spinAttentionEnabled(value) {
6702
+ if (value === null || typeof value !== "object")
6703
+ return true;
6704
+ return value.spinAttention !== false;
6705
+ }
6706
+ function spinAttentionEnabledFromRows(rows) {
6707
+ for (const row of rows) {
6708
+ if (row?.ns === "dsh-opentui")
6709
+ return spinAttentionEnabled(row.value);
6710
+ }
6711
+ return true;
6712
+ }
6713
+ function createSpinAttentionSource(options) {
6714
+ const now = options.now ?? Date.now;
6715
+ const minIntervalMs = options.minIntervalMs ?? SPIN_JEV_MIN_INTERVAL_MS;
6716
+ const env = options.env ?? process.env;
6717
+ let core;
6718
+ let loading;
6719
+ let lastDispatchAt = -Infinity;
6720
+ let inFlight = false;
6721
+ let failureCount = 0;
6722
+ const ensureLoaded = () => {
6723
+ if (options.module !== undefined)
6724
+ return Promise.resolve(options.module);
6725
+ if (core !== undefined)
6726
+ return Promise.resolve(core);
6727
+ loading ??= loadJevCore().then((mod) => {
6728
+ core = mod;
6729
+ return mod;
6730
+ });
6731
+ return loading;
6732
+ };
6733
+ return {
6734
+ failures: () => failureCount,
6735
+ tick(views, cap) {
6736
+ if (inFlight)
6737
+ return;
6738
+ if (!options.enabledReader())
6739
+ return;
6740
+ const live = views.filter((view) => view.running && view.childId);
6741
+ if (live.length === 0)
6742
+ return;
6743
+ const at = now();
6744
+ if (at - lastDispatchAt < minIntervalMs)
6745
+ return;
6746
+ ensureLoaded().then((mod) => {
6747
+ if (mod === null)
6748
+ return;
6749
+ if (!mod.isConfigured({ env }))
6750
+ return;
6751
+ const running = views.filter((view) => view.running && view.childId);
6752
+ if (running.length === 0)
6753
+ return;
6754
+ const id8ToChild = new Map(running.map((view) => [view.childId.slice(0, 8), view.childId]));
6755
+ const questions = buildSpinQuestions([...id8ToChild.keys()]);
6756
+ const state = buildSpinState(running, cap, now());
6757
+ if (state.trim() === "")
6758
+ return;
6759
+ inFlight = true;
6760
+ lastDispatchAt = at;
6761
+ mod.classify({ questions, state, env, timeoutMs: SPIN_JEV_TIMEOUT_MS }).then((result) => {
6762
+ for (const [childId, score] of parseSpinAnswers(result.answers, id8ToChild)) {
6763
+ try {
6764
+ options.onVerdict(childId, score);
6765
+ } catch {}
6766
+ }
6767
+ }).catch(() => {
6768
+ failureCount += 1;
6769
+ }).finally(() => {
6770
+ inFlight = false;
6771
+ });
6772
+ });
6773
+ }
6774
+ };
6775
+ }
6776
+ var SPIN_JEV_MIN_INTERVAL_MS = 30000, SPIN_JEV_TIMEOUT_MS = 8000, SPIN_STATE_MAX_CHARS = 1000, SPIN_LABEL_MAX_CHARS = 40;
6777
+
6620
6778
  // src/client/remote-subagents.ts
6621
6779
  import { randomUUID as randomUUID3 } from "crypto";
6622
6780
 
@@ -6627,6 +6785,7 @@ class RemoteSubagentPanel {
6627
6785
  #pumps = new Map;
6628
6786
  #stopped = false;
6629
6787
  #policy;
6788
+ #spinAttention;
6630
6789
  constructor(options) {
6631
6790
  this.#options = options;
6632
6791
  if (options.limits !== undefined) {
@@ -6670,6 +6829,13 @@ class RemoteSubagentPanel {
6670
6829
  }
6671
6830
  });
6672
6831
  }
6832
+ if (options.spinEnabled !== undefined) {
6833
+ this.#spinAttention = createSpinAttentionSource({
6834
+ enabledReader: options.spinEnabled,
6835
+ onVerdict: (childId, score) => this.noteSpinVerdict(childId, score),
6836
+ ...options.spinModule !== undefined ? { module: options.spinModule } : {}
6837
+ });
6838
+ }
6673
6839
  }
6674
6840
  foldParentRecord(entry) {
6675
6841
  if (entry.type === "tool-workflow/agent-start") {
@@ -6957,6 +7123,7 @@ class RemoteSubagentPanel {
6957
7123
  if (this.#policy !== undefined && options.feedLadder) {
6958
7124
  this.#options.refreshLimits?.();
6959
7125
  this.#policy.onRoundCount(id, next.rounds, next.label);
7126
+ this.#tickSpinAttention();
6960
7127
  }
6961
7128
  for (const line of text.split(`
6962
7129
  `))
@@ -6986,6 +7153,19 @@ class RemoteSubagentPanel {
6986
7153
  log.shift();
6987
7154
  return changed;
6988
7155
  }
7156
+ #tickSpinAttention() {
7157
+ if (this.#spinAttention === undefined)
7158
+ return;
7159
+ const cap = this.#options.limits?.().maxRounds ?? 0;
7160
+ const views = [];
7161
+ for (const [childId, view] of this.#children) {
7162
+ if (view.status !== "running")
7163
+ continue;
7164
+ views.push({ childId, label: view.label, rounds: view.rounds, running: true, startedAt: view.startedAt });
7165
+ }
7166
+ if (views.length > 0)
7167
+ this.#spinAttention.tick(views, cap);
7168
+ }
6989
7169
  #emit() {
6990
7170
  try {
6991
7171
  this.#options.onUpdate?.(this.views());
@@ -7192,6 +7372,7 @@ __export(exports_remote_host_session, {
7192
7372
  REATTACH_MAX_ATTEMPTS: () => REATTACH_MAX_ATTEMPTS,
7193
7373
  REATTACH_RETRY_MS: () => REATTACH_RETRY_MS,
7194
7374
  RemoteHostSession: () => RemoteHostSession,
7375
+ SPIN_REFRESH_TTL_MS: () => SPIN_REFRESH_TTL_MS,
7195
7376
  openRemoteStream: () => openRemoteStream
7196
7377
  });
7197
7378
  import { randomUUID as randomUUID4 } from "crypto";
@@ -7204,6 +7385,9 @@ function trace(message) {
7204
7385
  process.stderr.write(`[rhs ${new Date().toISOString().slice(11, 23)}] ${message}
7205
7386
  `);
7206
7387
  }
7388
+ function selectionErrorText(error) {
7389
+ return String(error instanceof Error ? error.message : error).slice(0, 150);
7390
+ }
7207
7391
 
7208
7392
  class RemoteHostSession {
7209
7393
  label = "dsh-host";
@@ -7245,6 +7429,7 @@ class RemoteHostSession {
7245
7429
  #promptInFlight = false;
7246
7430
  #interrupted = false;
7247
7431
  #pendingModel;
7432
+ #selectionError;
7248
7433
  #turns = 0;
7249
7434
  #turnStartedAt = 0;
7250
7435
  #turnUsageStart = { prompt: 0, completion: 0 };
@@ -7281,6 +7466,10 @@ class RemoteHostSession {
7281
7466
  #lastRestartPid;
7282
7467
  #btwBusy = false;
7283
7468
  #subagents;
7469
+ #spinAttentionOn = true;
7470
+ #spinAttentionRefreshing = false;
7471
+ #spinRefreshTtlMs;
7472
+ #spinCheckedAt = -Infinity;
7284
7473
  #overlayCache;
7285
7474
  constructor(options) {
7286
7475
  this.#connection = options.connection;
@@ -7293,6 +7482,7 @@ class RemoteHostSession {
7293
7482
  this.#restartHost = options.restartHost;
7294
7483
  this.#reattachRetryMs = options.reattachRetryMs ?? REATTACH_RETRY_MS;
7295
7484
  this.#reattachMaxAttempts = options.reattachMaxAttempts ?? REATTACH_MAX_ATTEMPTS;
7485
+ this.#spinRefreshTtlMs = options.spinRefreshTtlMs ?? SPIN_REFRESH_TTL_MS;
7296
7486
  this.#socketFactory = options.socketFactory ?? ((path) => this.#openMuxSocket(path));
7297
7487
  }
7298
7488
  #openMuxSocket(path) {
@@ -7569,8 +7759,12 @@ class RemoteHostSession {
7569
7759
  }
7570
7760
  this.#modelClient().selectModel(sessionId, selection).catch((error) => {
7571
7761
  console.error("[remote-host-session] selectModel failed:", error);
7762
+ this.#selectionError = selectionErrorText(error);
7572
7763
  });
7573
7764
  }
7765
+ lastSelectionError() {
7766
+ return this.#selectionError;
7767
+ }
7574
7768
  async selectModel(selection) {
7575
7769
  this.label = `${selection.provider}/${selection.model}${selection.reasoningEffort ? ` (${selection.reasoningEffort})` : ""}`;
7576
7770
  const sessionId = this.#sessionId;
@@ -7579,6 +7773,7 @@ class RemoteHostSession {
7579
7773
  return selection;
7580
7774
  }
7581
7775
  const selected = await this.#modelClient().selectModel(sessionId, selection);
7776
+ this.#selectionError = undefined;
7582
7777
  this.#invalidateContextProjections();
7583
7778
  return selected;
7584
7779
  }
@@ -7591,7 +7786,7 @@ class RemoteHostSession {
7591
7786
  async currentModelSelection() {
7592
7787
  const sessionId = this.#sessionId;
7593
7788
  if (sessionId === undefined)
7594
- return this.defaultModelSelection();
7789
+ return this.#pendingModel ?? await this.defaultModelSelection();
7595
7790
  return this.#modelClient().sessionSelection(sessionId);
7596
7791
  }
7597
7792
  async initializeDefaultModel() {
@@ -8161,6 +8356,8 @@ class RemoteHostSession {
8161
8356
  socketFactory: this.#socketFactory,
8162
8357
  parentId: () => this.#sessionId,
8163
8358
  limits: () => parseSubagentRoundLimits(this.configLoad()),
8359
+ refreshLimits: () => this.#refreshSpinAttention(),
8360
+ spinEnabled: () => this.#spinAttentionOn,
8164
8361
  onHardStop: (record) => console.info(`[subagent-policy] force-stopped child ${record.childId} at round ${record.round} (cap ${record.cap} + grace ${record.grace})`),
8165
8362
  onUpdate: (views) => {
8166
8363
  for (const listener of this.#subagentListeners) {
@@ -8176,6 +8373,20 @@ class RemoteHostSession {
8176
8373
  }
8177
8374
  return this.#subagents;
8178
8375
  }
8376
+ #refreshSpinAttention() {
8377
+ if (this.#spinAttentionRefreshing)
8378
+ return;
8379
+ const now = performance.now();
8380
+ if (now - this.#spinCheckedAt < this.#spinRefreshTtlMs)
8381
+ return;
8382
+ this.#spinAttentionRefreshing = true;
8383
+ this.#spinCheckedAt = now;
8384
+ this.settingsDescribe().then((rows) => {
8385
+ this.#spinAttentionOn = spinAttentionEnabledFromRows(rows);
8386
+ }).catch(() => {}).finally(() => {
8387
+ this.#spinAttentionRefreshing = false;
8388
+ });
8389
+ }
8179
8390
  childTranscript(id) {
8180
8391
  return this.#subagentPanel().transcript(id);
8181
8392
  }
@@ -8285,8 +8496,10 @@ class RemoteHostSession {
8285
8496
  this.#pendingModel = undefined;
8286
8497
  try {
8287
8498
  await this.#modelClient().selectModel(this.#sessionId, staged);
8499
+ this.#selectionError = undefined;
8288
8500
  } catch (error) {
8289
8501
  console.error("[remote-host-session] staged selectModel failed:", error);
8502
+ this.#selectionError = `staged ${staged.provider}/${staged.model} \u2014 ${selectionErrorText(error)}`;
8290
8503
  }
8291
8504
  }
8292
8505
  const opening = await this.#attachFollow(false);
@@ -8718,7 +8931,7 @@ function asPermissionOptions(value) {
8718
8931
  ];
8719
8932
  });
8720
8933
  }
8721
- var REATTACH_RETRY_MS = 1000, REATTACH_MAX_ATTEMPTS = 30, PRESET_ENGLISH_NAMES;
8934
+ var REATTACH_RETRY_MS = 1000, REATTACH_MAX_ATTEMPTS = 30, SPIN_REFRESH_TTL_MS = 5000, PRESET_ENGLISH_NAMES;
8722
8935
  var init_remote_host_session = __esm(() => {
8723
8936
  init_loop();
8724
8937
  init_remote_follow();
@@ -20843,7 +21056,7 @@ var init_keybind = __esm(() => {
20843
21056
  "variant.cycle": keybind("ctrl+t", "Cycle model variants"),
20844
21057
  "variant.list": keybind("none", "List model variants"),
20845
21058
  "session.page.up": keybind("pageup,ctrl+alt+b", "Scroll messages up by one page"),
20846
- "session.page.down": keybind("pagedown,ctrl+alt+f", "Scroll messages down by one page"),
21059
+ "session.page.down": keybind("pagedown", "Scroll messages down by one page"),
20847
21060
  "session.line.up": keybind("ctrl+alt+y", "Scroll messages up by one line"),
20848
21061
  "session.line.down": keybind("ctrl+alt+e", "Scroll messages down by one line"),
20849
21062
  "session.half.page.up": keybind("ctrl+alt+u", "Scroll messages up by half page"),
@@ -39918,15 +40131,32 @@ function ComposerContext(props) {
39918
40131
  return label().length > 0;
39919
40132
  },
39920
40133
  get children() {
39921
- var _el$ = createElement("box"), _el$2 = createElement("text");
40134
+ var _el$ = createElement("box"), _el$2 = createElement("box"), _el$3 = createElement("box"), _el$4 = createElement("text");
39922
40135
  insertNode(_el$, _el$2);
40136
+ insertNode(_el$, _el$3);
39923
40137
  setProp(_el$, "flexShrink", 0);
39924
- setProp(_el$, "height", 1);
40138
+ setProp(_el$, "flexDirection", "column");
39925
40139
  setProp(_el$, "width", "100%");
39926
- setProp(_el$, "paddingLeft", 1);
39927
- setProp(_el$2, "wrapMode", "none");
39928
- insert(_el$2, label);
39929
- effect((_$p) => setProp(_el$2, "fg", theme?.text.muted ?? "#565f89", _$p));
40140
+ setProp(_el$2, "flexShrink", 0);
40141
+ setProp(_el$2, "height", 1);
40142
+ setProp(_el$2, "width", "100%");
40143
+ setProp(_el$2, "border", ["top"]);
40144
+ insertNode(_el$3, _el$4);
40145
+ setProp(_el$3, "flexShrink", 0);
40146
+ setProp(_el$3, "height", 1);
40147
+ setProp(_el$3, "width", "100%");
40148
+ setProp(_el$3, "paddingLeft", 1);
40149
+ setProp(_el$4, "wrapMode", "none");
40150
+ insert(_el$4, label);
40151
+ effect((_p$) => {
40152
+ var _v$ = theme?.border.base ?? "#7aa2f7", _v$2 = theme?.text.muted ?? "#565f89";
40153
+ _v$ !== _p$.e && (_p$.e = setProp(_el$2, "borderColor", _v$, _p$.e));
40154
+ _v$2 !== _p$.t && (_p$.t = setProp(_el$4, "fg", _v$2, _p$.t));
40155
+ return _p$;
40156
+ }, {
40157
+ e: undefined,
40158
+ t: undefined
40159
+ });
39930
40160
  return _el$;
39931
40161
  }
39932
40162
  });
@@ -49026,6 +49256,9 @@ function persistHints(seam) {
49026
49256
  console.error("[commands] hints persist failed:", error);
49027
49257
  }
49028
49258
  }
49259
+ function seamFailureReason(error) {
49260
+ return String(error instanceof Error ? error.message : error).slice(0, 150);
49261
+ }
49029
49262
  function presetNextRow(rows, currentId) {
49030
49263
  if (rows.length <= 1)
49031
49264
  return;
@@ -49144,8 +49377,12 @@ function coreCommands() {
49144
49377
  },
49145
49378
  {
49146
49379
  name: "/model",
49147
- description: "switch model (bare opens the picker)",
49380
+ description: "switch model (bare opens the picker, then the effort picker)",
49148
49381
  async run(ctx, argText) {
49382
+ const pendingSelectionError = ctx.seam.lastSelectionError?.();
49383
+ if (pendingSelectionError) {
49384
+ ctx.say(`model note: the last staged switch failed \u2014 ${pendingSelectionError}`);
49385
+ }
49149
49386
  const arg = argText.trim();
49150
49387
  if (arg) {
49151
49388
  const [providerID, modelID] = arg.split("/");
@@ -49153,7 +49390,12 @@ function coreCommands() {
49153
49390
  ctx.say(`usage: /model or /model provider/model (got "${arg}")`);
49154
49391
  return;
49155
49392
  }
49156
- await ctx.seam.selectModel(providerID, modelID);
49393
+ try {
49394
+ await ctx.seam.selectModel(providerID, modelID);
49395
+ } catch (error) {
49396
+ ctx.say(`model switch failed \u2014 ${seamFailureReason(error)}`);
49397
+ return;
49398
+ }
49157
49399
  ctx.say(`model \u2192 ${providerID}/${modelID}`);
49158
49400
  ctx.refreshFooter?.();
49159
49401
  return;
@@ -49172,8 +49414,65 @@ function coreCommands() {
49172
49414
  if (!picked)
49173
49415
  return;
49174
49416
  const [providerID, modelID] = picked.split("/");
49175
- await ctx.seam.selectModel(providerID, modelID);
49417
+ const thinking = ctx.seam.thinking;
49418
+ let ladder = [];
49419
+ try {
49420
+ ladder = await thinking?.effortsFor?.(providerID, modelID) ?? [];
49421
+ } catch {
49422
+ ladder = [];
49423
+ }
49424
+ if (ladder.length === 0) {
49425
+ const keptEffort = current?.providerID === providerID ? await thinking?.currentEffort() : undefined;
49426
+ try {
49427
+ await ctx.seam.selectModel(providerID, modelID);
49428
+ } catch (error) {
49429
+ ctx.say(`model switch failed \u2014 ${seamFailureReason(error)}`);
49430
+ return;
49431
+ }
49432
+ ctx.say(`model \u2192 ${picked} (no think levels)`);
49433
+ if (keptEffort !== undefined) {
49434
+ try {
49435
+ await thinking?.selectEffort(keptEffort);
49436
+ } catch (error) {
49437
+ ctx.say(`thinking switch failed \u2014 ${seamFailureReason(error)}`);
49438
+ ctx.refreshFooter?.();
49439
+ return;
49440
+ }
49441
+ ctx.say(`thinking \u2192 ${keptEffort} (next turn)`);
49442
+ }
49443
+ ctx.refreshFooter?.();
49444
+ return;
49445
+ }
49446
+ const effortNow = await thinking?.currentEffort();
49447
+ const effortPicked = await ctx.pickOne(`Select reasoning effort \u2014 ${picked}`, [
49448
+ { title: "(model default)", value: MODEL_DEFAULT_EFFORT_PICK },
49449
+ ...ladder.map((effort) => ({
49450
+ title: effort.name,
49451
+ value: effort.id,
49452
+ description: effort.id === effortNow ? "current" : effort.description
49453
+ }))
49454
+ ]);
49455
+ if (!effortPicked) {
49456
+ ctx.say("model unchanged");
49457
+ return;
49458
+ }
49459
+ const effort = effortPicked === MODEL_DEFAULT_EFFORT_PICK ? undefined : effortPicked;
49460
+ ctx.invalidateFooter?.();
49461
+ try {
49462
+ await ctx.seam.selectModel(providerID, modelID);
49463
+ } catch (error) {
49464
+ ctx.say(`model switch failed \u2014 ${seamFailureReason(error)}`);
49465
+ return;
49466
+ }
49176
49467
  ctx.say(`model \u2192 ${picked}`);
49468
+ try {
49469
+ await thinking?.selectEffort(effort);
49470
+ } catch (error) {
49471
+ ctx.say(`thinking switch failed \u2014 ${seamFailureReason(error)}`);
49472
+ ctx.refreshFooter?.();
49473
+ return;
49474
+ }
49475
+ ctx.say(`thinking \u2192 ${effortPicked === MODEL_DEFAULT_EFFORT_PICK ? "model default" : effortPicked} (next turn)`);
49177
49476
  ctx.refreshFooter?.();
49178
49477
  }
49179
49478
  },
@@ -49378,7 +49677,12 @@ function coreCommands() {
49378
49677
  if (!picked || picked === current)
49379
49678
  return;
49380
49679
  ctx.invalidateFooter?.();
49381
- await thinking.selectEffort(picked);
49680
+ try {
49681
+ await thinking.selectEffort(picked);
49682
+ } catch (error) {
49683
+ ctx.say(`thinking switch failed \u2014 ${seamFailureReason(error)}`);
49684
+ return;
49685
+ }
49382
49686
  ctx.say(`thinking \u2192 ${picked} (next turn)`);
49383
49687
  ctx.refreshFooter?.();
49384
49688
  }
@@ -49584,6 +49888,7 @@ function dispatchLine(commands, line) {
49584
49888
  function unknownCommandRow(name) {
49585
49889
  return `unknown command: ${name} (try /help)`;
49586
49890
  }
49891
+ var MODEL_DEFAULT_EFFORT_PICK = "__model_default__";
49587
49892
  var init_commands = __esm(() => {
49588
49893
  init_hotkeys();
49589
49894
  init_login();
@@ -53621,7 +53926,10 @@ function BtwPanel(props) {
53621
53926
  get fallback() {
53622
53927
  return (() => {
53623
53928
  var _el$0 = createElement("text");
53624
- insert(_el$0, () => run().answer);
53929
+ insert(_el$0, (() => {
53930
+ var _c$2 = memo2(() => run().answer === "");
53931
+ return () => _c$2() ? "(empty answer)" : run().answer;
53932
+ })());
53625
53933
  return _el$0;
53626
53934
  })();
53627
53935
  },
@@ -54146,10 +54454,11 @@ class RemoteSessionSeam {
54146
54454
  selectModel(providerID, modelID) {
54147
54455
  return this.#session.selectModel({ provider: providerID, model: modelID }).then(() => {
54148
54456
  return;
54149
- }).catch((error) => {
54150
- console.error("[session-seam-adapter] selectModel failed:", error);
54151
54457
  });
54152
54458
  }
54459
+ lastSelectionError() {
54460
+ return this.#session.lastSelectionError();
54461
+ }
54153
54462
  thinking = {
54154
54463
  efforts: async () => {
54155
54464
  try {
@@ -54171,6 +54480,7 @@ class RemoteSessionSeam {
54171
54480
  return [];
54172
54481
  }
54173
54482
  },
54483
+ effortsFor: (providerID, modelID) => this.#session.modelEfforts(providerID, modelID),
54174
54484
  currentEffort: async () => {
54175
54485
  const selection = await this.#session.currentModelSelection();
54176
54486
  return selection?.reasoningEffort;
@@ -54186,8 +54496,6 @@ class RemoteSessionSeam {
54186
54496
  });
54187
54497
  }).then(() => {
54188
54498
  return;
54189
- }).catch((error) => {
54190
- console.error("[session-seam-adapter] selectEffort failed:", error);
54191
54499
  });
54192
54500
  }
54193
54501
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aiwayds/dsh-opentui",
3
- "version": "0.9.6",
3
+ "version": "0.9.8",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "bin": {
@@ -153,6 +153,119 @@ export function pluginAddCommand(profile, specs) {
153
153
  return ['dsh', ...pluginAddArgs(profile, specs)].join(' ')
154
154
  }
155
155
 
156
+ // ---------------------------------------------------------------------------
157
+ // Plugin-add failure classification (the bounded retry policy)
158
+ //
159
+ // The script's per-spec fallback retry (PLUGIN_ADD_ATTEMPTS x
160
+ // PLUGIN_ADD_BACKOFF_MS) used to treat every failure as transient. Real 0.9.7
161
+ // upgrades said otherwise: one orphan patchedDependencies entry makes every
162
+ // `pnpm add` exit at once with ERR_PNPM_UNUSED_PATCH, so each spec burned 3
163
+ // attempts x 5s and repeated the same red error. A DETERMINISTIC failure can
164
+ // never succeed on a retry; the classification below reads only the captured
165
+ // stderr / spawn-error text (where `dsh plugin add` surfaces pnpm's codes) and
166
+ // maps the known shapes:
167
+ // deterministic — ERR_PNPM_UNUSED_PATCH, ERR_PNPM_NO_MATCHING_VERSION,
168
+ // 404-class (but NOT ERR_PNPM_META_FETCH_FAIL, which is
169
+ // registry-side flakiness), ENOTFOUND, EACCES, EPERM
170
+ // transient — ECONNRESET, ETIMEDOUT, ECONNREFUSED, socket disconnected,
171
+ // TLS/SSL, HTTP 5xx, ERR_PNPM_META_FETCH_FAIL
172
+ // unknown — anything else, retried: an unrecognized error is never
173
+ // treated as deterministic (conservative).
174
+ // ERR_PNPM_META_FETCH_FAIL is checked FIRST: its cause chain may print
175
+ // ENOTFOUND/404, but pnpm's own code is authoritative for transientness.
176
+ // ---------------------------------------------------------------------------
177
+
178
+ /** Deterministic failure → one actionable fix line each. The 404 rule pairs
179
+ * the status with "not found" prose (or the ERR_PNPM_FETCH_404 code) so
180
+ * coincidental numbers in progress output ("reused 404") cannot stop a retry. */
181
+ const PLUGIN_ADD_DETERMINISTIC_RULES = [
182
+ {
183
+ code: 'ERR_PNPM_UNUSED_PATCH',
184
+ re: /ERR_PNPM_UNUSED_PATCH/,
185
+ hint: 'a patchedDependencies entry in pnpm-workspace.yaml no longer matches any dependency — remove that entry, then re-run',
186
+ },
187
+ {
188
+ code: 'ERR_PNPM_NO_MATCHING_VERSION',
189
+ re: /ERR_PNPM_NO_MATCHING_VERSION/,
190
+ hint: 'no registry version matches the requested spec — check the pinned version against the registry, then re-run',
191
+ },
192
+ {
193
+ code: 'HTTP 404',
194
+ re: /ERR_PNPM_FETCH_404|(?<![\d.])404(?![\d.])[^\n]{0,80}not[ -]?found|not[ -]?found[^\n]{0,80}(?<![\d.])404(?![\d.])/i,
195
+ hint: 'the package or version was not found on the registry (404) — check the spec and the registry URL, then re-run',
196
+ },
197
+ {
198
+ code: 'ENOTFOUND',
199
+ re: /\bENOTFOUND\b/,
200
+ hint: 'a registry host did not resolve (ENOTFOUND) — check the registry URL and DNS, then re-run',
201
+ },
202
+ {
203
+ code: 'EACCES',
204
+ re: /\bEACCES\b/,
205
+ hint: 'permission denied (EACCES) — check ownership of the profile directory (node_modules, pnpm-workspace.yaml), then re-run',
206
+ },
207
+ {
208
+ code: 'EPERM',
209
+ re: /\bEPERM\b/,
210
+ hint: 'operation not permitted (EPERM) — check file permissions or locks in the profile directory, then re-run',
211
+ },
212
+ ]
213
+
214
+ const PLUGIN_ADD_TRANSIENT_RULES = [
215
+ { code: 'ECONNRESET', re: /\bECONNRESET\b/ },
216
+ { code: 'ETIMEDOUT', re: /\bETIMEDOUT\b/ },
217
+ { code: 'ECONNREFUSED', re: /\bECONNREFUSED\b/ },
218
+ { code: 'disconnected', re: /disconnect/i },
219
+ { code: 'TLS/SSL', re: /\bTLS\b|\bSSL\b/ },
220
+ { code: 'HTTP 5xx', re: /(?<![\d.])5\d\d(?![\d.])/ },
221
+ ]
222
+
223
+ /** Classify one failed `dsh plugin add` attempt. Pure: the captured run
224
+ * output in, `{ kind, code, hint }` out. `hint` is a non-null actionable
225
+ * fix only for deterministic failures. */
226
+ export function classifyPluginAddFailure({ stderr = '', error = null } = {}) {
227
+ const text = [
228
+ typeof stderr === 'string' ? stderr : Buffer.isBuffer(stderr) ? stderr.toString() : '',
229
+ error?.code ?? '',
230
+ error?.message ?? '',
231
+ ]
232
+ .filter(Boolean)
233
+ .join('\n')
234
+ if (/ERR_PNPM_META_FETCH_FAIL/.test(text)) {
235
+ return { kind: 'transient', code: 'ERR_PNPM_META_FETCH_FAIL', hint: null }
236
+ }
237
+ for (const rule of PLUGIN_ADD_DETERMINISTIC_RULES) {
238
+ if (rule.re.test(text)) return { kind: 'deterministic', code: rule.code, hint: rule.hint }
239
+ }
240
+ for (const rule of PLUGIN_ADD_TRANSIENT_RULES) {
241
+ if (rule.re.test(text)) return { kind: 'transient', code: rule.code, hint: null }
242
+ }
243
+ return { kind: 'unknown', code: null, hint: null }
244
+ }
245
+
246
+ /** The next step of the bounded per-spec retry after one attempt. Pure: the
247
+ * spawnSync result of one `dsh plugin add` run in, a decision out.
248
+ * { action: 'installed' }
249
+ * { action: 'retry' } — transient/unknown and attempts remain
250
+ * { action: 'failed', failure } — deterministic (never retried), or the
251
+ * attempt budget is exhausted
252
+ */
253
+ export function pluginAddRetryDecision(run, { attempt, attempts } = {}) {
254
+ if (!run?.error && run?.status === 0) return { action: 'installed' }
255
+ const failure = classifyPluginAddFailure({ stderr: run?.stderr, error: run?.error })
256
+ if (failure.kind !== 'deterministic' && attempt < attempts) return { action: 'retry' }
257
+ return { action: 'failed', failure }
258
+ }
259
+
260
+ /** Terminal per-spec failures for the summary, DETERMINISTIC FIRST (each
261
+ * carries the one-line fix; a stable sort keeps install order within the
262
+ * groups). */
263
+ export function orderPluginAddFailures(failures) {
264
+ return [...failures].sort(
265
+ (a, b) => (a.failure.kind === 'deterministic' ? 0 : 1) - (b.failure.kind === 'deterministic' ? 0 : 1),
266
+ )
267
+ }
268
+
156
269
  /** Format one progress line: `[n/m] label` with the value column aligned.
157
270
  * Mirrors dsh-tui-pi's onboarding output, with the script name as prefix. */
158
271
  export function formatStep(step, label, value = '') {
@@ -336,6 +449,131 @@ export function cleanupDependencies(dependencies, retire = RETIRED_PROFILE_ENTRI
336
449
  return { dependencies: next, removed }
337
450
  }
338
451
 
452
+ // ---------------------------------------------------------------------------
453
+ // Orphan pnpm patches (ERR_PNPM_UNUSED_PATCH)
454
+ //
455
+ // The plugin-mode installer (retired with 0.9.7) registered
456
+ // `patchedDependencies: solid-js@1.9.17: patches/...` in the profile's
457
+ // pnpm-workspace.yaml to pin the host bundle's solid-js client build. That
458
+ // dependency is gone from 0.9.7 profiles, and pnpm hard-fails EVERY install
459
+ // with ERR_PNPM_UNUSED_PATCH while a patchedDependencies entry names a package
460
+ // outside the dependency graph — one stale line blocks all plugin installs on
461
+ // upgraded profiles. The cleanup below drops exactly those orphan entries and
462
+ // never touches the patch files themselves (patches/ is kept for the record).
463
+ //
464
+ // The reader is a port of the retired solid-js-pin.mjs parsePatchBlocks (the
465
+ // shape it merged on real 0.4.3→0.5.0 migrations), because pnpm's
466
+ // patchedDependencies IS a flat `pkg@version: relpath` string map and no YAML
467
+ // parser is available in this dependency-free script.
468
+ // ---------------------------------------------------------------------------
469
+
470
+ const PATCH_HEADER_RE = /^patchedDependencies:\s*$/
471
+ // A flat-map entry line: ` <key>: <value>` (keys like `solid-js@1.9.17`
472
+ // carry no colon; values are patch relpaths). Nested-map or list lines do
473
+ // NOT match, and a bare `key:` with no value (nested-map form) has an empty
474
+ // value — both mark the block opaque.
475
+ const PATCH_ENTRY_RE = /^[ \t]+([^:\s][^:]*):(?:[ \t]+(.*))?$/
476
+
477
+ /** The package a patch key patches: `solid-js@1.9.17` → `solid-js`,
478
+ * `@scope/pkg@1.2.3` → `@scope/pkg` (the LAST `@` separates the version; a
479
+ * bare `pkg` key names itself). A YAML-quoted key (`'@scope/pkg@1.2.3'`) is
480
+ * unquoted first — the quotes are syntax, never part of the name. */
481
+ export function patchTargetName(key) {
482
+ const name = String(key).replace(/^(['"])(.*)\1$/, '$2')
483
+ const at = name.lastIndexOf('@')
484
+ return at > 0 ? name.slice(0, at) : name
485
+ }
486
+
487
+ /** Parse every top-level `patchedDependencies:` block in the yaml into its
488
+ * flat `pkg@version: relpath` entries, in first-seen order (a duplicated key
489
+ * keeps its first occurrence), plus the [start, end) line range of each
490
+ * block, and `opaque: true` when some block holds lines this reader cannot
491
+ * reproduce — an unparseable line, or an entry with NO inline value (a
492
+ * nested-map form such as pnpm's `key:` + `path:`/`hashed:` rows). The
493
+ * caller must not rewrite what it cannot reproduce: flattening a nested
494
+ * block would corrupt the file. */
495
+ export function parsePatchedDependencies(lines) {
496
+ const entries = []
497
+ const seen = new Set()
498
+ const ranges = []
499
+ let opaque = false
500
+ let i = 0
501
+ while (i < lines.length) {
502
+ if (!PATCH_HEADER_RE.test(lines[i])) {
503
+ i += 1
504
+ continue
505
+ }
506
+ const start = i
507
+ i += 1
508
+ while (i < lines.length && /^[ \t]+\S/.test(lines[i])) {
509
+ const match = PATCH_ENTRY_RE.exec(lines[i])
510
+ const value = match ? (match[2] ?? '').trim() : ''
511
+ if (!match || value === '') {
512
+ opaque = true
513
+ break
514
+ }
515
+ const key = match[1].trim()
516
+ if (!seen.has(key)) {
517
+ seen.add(key)
518
+ entries.push([key, value])
519
+ }
520
+ i += 1
521
+ }
522
+ ranges.push([start, i])
523
+ }
524
+ return { entries, ranges, opaque }
525
+ }
526
+
527
+ /**
528
+ * Plan the orphan-patch cleanup for one pnpm-workspace.yaml text. Pure: text
529
+ * in, plan + rewritten text out.
530
+ *
531
+ * A patch entry is an ORPHAN when its target package (`patchTargetName(key)`)
532
+ * is not among `dependencyNames` — the caller passes the profile's FINAL
533
+ * dependency set (after retired-entry cleanup and this run's installs), the
534
+ * same set pnpm checks when it raises ERR_PNPM_UNUSED_PATCH.
535
+ *
536
+ * With removals, ONE block is written back at the first block's position (the
537
+ * duplicate-block collapse of the retired installer's merge); every other
538
+ * line is preserved byte-for-byte, and no entry left means no block at all.
539
+ * An opaque block is returned untouched. With nothing to remove the text is
540
+ * returned byte-identical.
541
+ *
542
+ * @param {string} text
543
+ * @param {string[]} dependencyNames
544
+ * @returns {{removed: Array<[string,string]>, kept: Array<[string,string]>, text: string, changed: boolean, opaque: boolean}}
545
+ */
546
+ export function planOrphanPatchCleanup(text, dependencyNames = []) {
547
+ const source = String(text ?? '')
548
+ const lines = source.split('\n')
549
+ const { entries, ranges, opaque } = parsePatchedDependencies(lines)
550
+ if (opaque) return { removed: [], kept: entries, text: source, changed: false, opaque: true }
551
+ const names = new Set(dependencyNames)
552
+ const removed = entries.filter(([key]) => !names.has(patchTargetName(key)))
553
+ if (removed.length === 0) {
554
+ return { removed, kept: entries, text: source, changed: false, opaque: false }
555
+ }
556
+ const removedKeys = new Set(removed.map(([key]) => key))
557
+ const kept = entries.filter(([key]) => !removedKeys.has(key))
558
+ const mergedBlock = [
559
+ 'patchedDependencies:',
560
+ ...kept.map(([key, value]) => ` ${key}:${value ? ` ${value}` : ''}`),
561
+ ]
562
+ const out = []
563
+ let range = 0
564
+ for (let i = 0; i < lines.length; ) {
565
+ if (range < ranges.length && i === ranges[range][0]) {
566
+ if (range === 0 && kept.length > 0) out.push(...mergedBlock)
567
+ i = ranges[range][1]
568
+ range += 1
569
+ continue
570
+ }
571
+ out.push(lines[i])
572
+ i += 1
573
+ }
574
+ return { removed, kept, text: out.join('\n'), changed: true, opaque: false }
575
+ }
576
+
339
577
  // ---------------------------------------------------------------------------
340
578
  // Profile patch rows for the model-facing web tools
341
579
  //
@@ -30,7 +30,13 @@
30
30
  // narrows the set, `--plugins=none` installs nothing.
31
31
  // [4/5] bundles — clean retired entries out of `dsh.profile.bundles` /
32
32
  // `dependencies` and append missing managed bundles in
33
- // install order (ask-router first).
33
+ // install order (ask-router first). Also retires
34
+ // orphan patchedDependencies entries from the profile's
35
+ // pnpm-workspace.yaml — a patch whose target package is
36
+ // no longer a dependency fails every pnpm install with
37
+ // ERR_PNPM_UNUSED_PATCH (the plugin-mode installer
38
+ // registered a solid-js patch that 0.9.7 profiles no
39
+ // longer need). The patch files in patches/ are kept.
34
40
  // [5/5] verify — `dsh opentui --dump-config`; "skipping profile
35
41
  // bundle" lines become WARN lines, never a failure.
36
42
  //
@@ -43,8 +49,14 @@
43
49
  // satisfied — a local development pin is never replaced by a registry version.
44
50
  // Missing deps/versions → ONE batched `dsh plugin --profile opentui add
45
51
  // <specs...>`; on failure the pnpm build-script skeleton is approved and each
46
- // package is retried once on its own; a still-failing package is a WARN, never
47
- // a hard stop (the client still launches).
52
+ // package is installed on its own with bounded spaced retries (a transient
53
+ // registry failure — TLS reset / ERR_PNPM_META_FETCH_FAIL — dies in seconds,
54
+ // a re-attempt after a short gap rides the burst out). A DETERMINISTIC
55
+ // failure (ERR_PNPM_UNUSED_PATCH, ERR_PNPM_NO_MATCHING_VERSION, 404-class,
56
+ // EACCES/EPERM — classifyPluginAddFailure) skips the retries outright and is
57
+ // reported first with an actionable hint; unknown failures still retry.
58
+ // A still-failing package is a WARN, never a hard stop (the client still
59
+ // launches).
48
60
  //
49
61
  // Step 4 reparses the profile manifest after the install: `dsh plugin add`
50
62
  // already reconciles bundles for new dependencies, so this only fills the gaps
@@ -74,18 +86,33 @@ import {
74
86
  formatStep,
75
87
  isDryRun,
76
88
  mergeBundles,
89
+ orderPluginAddFailures,
77
90
  parseDumpConfig,
78
91
  parseTier,
79
92
  planMcpPatch,
93
+ planOrphanPatchCleanup,
80
94
  planPluginInstall,
81
95
  planToolPatch,
82
96
  pluginAddArgs,
83
97
  pluginAddCommand,
98
+ pluginAddRetryDecision,
84
99
  selectPlugins,
85
100
  } from './lib/provision-plan.mjs'
86
101
 
87
102
  const TEMPLATE = 'web'
88
103
  const INSTALL_TIMEOUT_MS = 10 * 60 * 1000
104
+ // Bounded retry schedule for a single-spec install that failed (the fallback
105
+ // loop below). A transient registry failure (TLS reset / ERR_PNPM_META_FETCH_
106
+ // FAIL) exits within seconds, so 3 attempts spaced 5s apart ride the burst
107
+ // out without meaningfully extending a healthy provisioning run: the worst
108
+ // case adds ~2 fast failures + 2 x 5s per FAILING spec, and a hung `dsh
109
+ // plugin add` is still bounded by INSTALL_TIMEOUT_MS per invocation.
110
+ // DETERMINISTIC failures (ERR_PNPM_UNUSED_PATCH, ERR_PNPM_NO_MATCHING_VERSION,
111
+ // 404/ENOTFOUND, EACCES/EPERM — see classifyPluginAddFailure) are exempt:
112
+ // retrying cannot fix them, so the spec gives up on the first hit and the
113
+ // summary reports it first with an actionable hint.
114
+ const PLUGIN_ADD_ATTEMPTS = 3
115
+ const PLUGIN_ADD_BACKOFF_MS = 5000
89
116
 
90
117
  const args = process.argv.slice(2)
91
118
  /** --name=value or --name value. */
@@ -332,15 +359,33 @@ function approvePrintedBuilds(names) {
332
359
  }
333
360
  }
334
361
 
335
- function runPluginAdd(specs) {
362
+ function runPluginAdd(specs, { captureStderr = false } = {}) {
336
363
  return spawnSync('dsh', pluginAddArgs(PROFILE, specs), {
337
- stdio: 'inherit',
364
+ // The per-spec retry captures stderr (the batch install keeps it live) so
365
+ // the failure classifier can read pnpm's error codes; the captured text
366
+ // is echoed back right after the run so nothing the user used to see is
367
+ // swallowed.
368
+ stdio: captureStderr ? ['inherit', 'inherit', 'pipe'] : 'inherit',
338
369
  env: { ...process.env, DSH_HOME: dshHome },
339
370
  timeout: INSTALL_TIMEOUT_MS,
371
+ maxBuffer: 16 * 1024 * 1024,
340
372
  })
341
373
  }
342
374
 
343
- const failedInstalls = []
375
+ /** Echo a captured stderr back to the terminal (tail only — pnpm banners can
376
+ * be long, the error code is at the end). */
377
+ function echoCapturedStderr(stderr) {
378
+ const text = typeof stderr === 'string' ? stderr : stderr?.toString() ?? ''
379
+ if (text.trim()) console.error(text.trimEnd().slice(-2000))
380
+ }
381
+
382
+ /** Synchronous pause (this script is spawnSync end to end; there is no event
383
+ * loop to await on). */
384
+ function pauseSync(ms) {
385
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms)
386
+ }
387
+
388
+ const failedInstalls = [] // { spec, failure: { kind, code, hint } }
344
389
  let installedCount = 0
345
390
 
346
391
  if (tier === 'none') {
@@ -374,16 +419,45 @@ if (tier === 'none') {
374
419
  say(3, 'plugins', 'approved the printed build scripts (pnpm allowBuilds) — retrying one by one…')
375
420
  }
376
421
  // Single-package fallback: one bad package must not sink the rest.
422
+ // Each failing spec gets bounded spaced retries (PLUGIN_ADD_ATTEMPTS /
423
+ // PLUGIN_ADD_BACKOFF_MS): a transient registry failure rides the burst
424
+ // out instead of WARN-ing the plugin away on the first drop. A
425
+ // DETERMINISTIC failure (pluginAddRetryDecision) is exempt — retrying
426
+ // cannot fix it, so the spec gives up on the first hit. The terminal
427
+ // failure stays a WARN + failedInstalls entry — never a silent pass
428
+ // (the e2e npm-install boot leg asserts the delivered set).
377
429
  for (const spec of specs) {
378
- const retry = runPluginAdd([spec])
379
- if (!retry.error && retry.status === 0) {
380
- installedCount += 1
381
- } else {
382
- failedInstalls.push(spec)
383
- warn(`could not install ${spec}${retry.error ? `: ${retry.error.message}` : ` (exit ${retry.status})`} — continuing`)
430
+ let installed = false
431
+ for (let attempt = 1; attempt <= PLUGIN_ADD_ATTEMPTS && !installed; attempt += 1) {
432
+ if (attempt > 1) {
433
+ say(3, 'plugins', `${spec} failed — retry ${attempt - 1}/${PLUGIN_ADD_ATTEMPTS - 1} in ${PLUGIN_ADD_BACKOFF_MS / 1000}s…`)
434
+ pauseSync(PLUGIN_ADD_BACKOFF_MS)
435
+ }
436
+ const retry = runPluginAdd([spec], { captureStderr: true })
437
+ echoCapturedStderr(retry.stderr)
438
+ const decision = pluginAddRetryDecision(retry, { attempt, attempts: PLUGIN_ADD_ATTEMPTS })
439
+ if (decision.action === 'installed') {
440
+ installedCount += 1
441
+ installed = true
442
+ } else if (decision.action === 'failed') {
443
+ const detail = retry.error ? retry.error.message : `(exit ${retry.status})`
444
+ failedInstalls.push({ spec, failure: decision.failure, detail })
445
+ if (decision.failure.kind === 'deterministic') {
446
+ say(3, 'plugins', `${spec}: ${decision.failure.code} — deterministic, not retrying`)
447
+ }
448
+ break
449
+ }
384
450
  }
385
451
  }
386
452
  }
453
+ // Summary: deterministic failures first, each with its one-line fix; the
454
+ // retried-then-failed ones follow without a hint.
455
+ for (const { spec, failure, detail } of orderPluginAddFailures(failedInstalls)) {
456
+ warn(
457
+ `could not install ${spec}${failure.code ? `: ${failure.code}` : ` ${detail}`}` +
458
+ ` — continuing${failure.hint ? ` — ${failure.hint}` : ''}`,
459
+ )
460
+ }
387
461
  const failedSuffix = failedInstalls.length > 0 ? `, failed ${failedInstalls.length}` : ''
388
462
  say(3, 'plugins', `installed ${installedCount}, skipped ${skipped}${failedSuffix}`)
389
463
  }
@@ -391,7 +465,9 @@ if (tier === 'none') {
391
465
 
392
466
  // ---------------------------------------------------------------------------
393
467
  // 4. Bundles: clean retired entries, append missing managed bundles in the
394
- // install order (ask-router first).
468
+ // install order (ask-router first); retire orphan pnpm patches whose
469
+ // target package left the dependency graph (they hard-fail every install
470
+ // with ERR_PNPM_UNUSED_PATCH).
395
471
  // ---------------------------------------------------------------------------
396
472
  {
397
473
  const parsedManifest = readManifest()
@@ -412,6 +488,20 @@ if (tier === 'none') {
412
488
  const merged = mergeBundles(manifestBundles(manifest), { managedOrder, retire: RETIRED_PROFILE_ENTRIES })
413
489
  const changed = depClean.removed.length > 0 || merged.removed.length > 0 || merged.appended.length > 0 || merged.reordered
414
490
 
491
+ // Orphan pnpm patches: a patchedDependencies entry whose target package is
492
+ // no longer a dependency makes every `pnpm` install fail with
493
+ // ERR_PNPM_UNUSED_PATCH (the retired plugin-mode installer registered such
494
+ // a solid-js patch). The check runs against the post-cleanup dependency
495
+ // set — the same set pnpm sees — and is orthogonal to the manifest write
496
+ // below: bundles can be up to date while a stale patch still blocks
497
+ // installs. The patch FILE in patches/ is kept (record of what was applied);
498
+ // only the workspace registration is dropped. No pnpm-workspace.yaml means
499
+ // nothing to clean — none is created.
500
+ const workspacePath = join(profileDir, 'pnpm-workspace.yaml')
501
+ const patchPlan = parsedManifest !== null && existsSync(workspacePath)
502
+ ? planOrphanPatchCleanup(readFileSync(workspacePath, 'utf8'), Object.keys(depClean.dependencies))
503
+ : null
504
+
415
505
  if (parsedManifest === null && existsSync(manifestPath)) {
416
506
  warn(`${manifestPath} is not a valid JSON manifest — leaving it untouched`)
417
507
  say(4, 'bundles', 'skipped (unreadable profile manifest)')
@@ -446,6 +536,27 @@ if (tier === 'none') {
446
536
  }
447
537
  if (!reported) say(4, 'bundles', `up to date (${merged.bundles.length} entries)`)
448
538
  }
539
+
540
+ // Retire orphan patches AFTER the manifest write: the logs read as bundle
541
+ // summary first, orphan-patch retirement second. `patchPlan` is null
542
+ // without a readable manifest or without a pnpm-workspace.yaml — both are
543
+ // no-ops (a corrupt manifest already warned above; no workspace file is
544
+ // ever created here).
545
+ if (patchPlan?.opaque) {
546
+ warn('pnpm-workspace.yaml patchedDependencies is not a flat map — leaving it untouched')
547
+ } else if (patchPlan?.removed.length > 0) {
548
+ if (dryRun) {
549
+ say(4, 'bundles', `would retire ${patchPlan.removed.length} orphan patch (${patchPlan.removed.map(([key]) => key).join(', ')}) (dry run)`)
550
+ } else {
551
+ const backupPath = `${workspacePath}.bak-${Date.now()}`
552
+ renameSync(workspacePath, backupPath)
553
+ console.log(`${PREFIX}backed up ${workspacePath} to ${backupPath}`)
554
+ writeFileSync(workspacePath, patchPlan.text)
555
+ for (const [key] of patchPlan.removed) {
556
+ say(4, 'bundles', `retired orphan patch ${key} (its target is no longer a dependency)`)
557
+ }
558
+ }
559
+ }
449
560
  }
450
561
 
451
562
  // ---------------------------------------------------------------------------