@aiwayds/dsh-opentui 0.9.5 → 0.9.7

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.
@@ -740,6 +740,225 @@ var init_boot_shared = __esm(() => {
740
740
  bootCallOrder = [];
741
741
  });
742
742
 
743
+ // src/client/mux-frame.ts
744
+ function openEventsStreamFrame(streamId) {
745
+ return { type: "open", streamId, endpoint: "$events", payload: { args: {} } };
746
+ }
747
+ function parseMuxFrame(text) {
748
+ let decoded;
749
+ try {
750
+ decoded = JSON.parse(text);
751
+ } catch (cause) {
752
+ throw new MuxFrameError("mux frame is not JSON", { cause });
753
+ }
754
+ if (!isRecord(decoded))
755
+ throw new MuxFrameError("mux frame must be an object");
756
+ const value = decoded;
757
+ const type = value.type;
758
+ const streamId = value.streamId;
759
+ if (typeof streamId !== "string" || streamId.length === 0) {
760
+ throw new MuxFrameError("mux frame streamId is missing or empty");
761
+ }
762
+ if (type === "item") {
763
+ if (!exactKeys(value, ["type", "streamId"]) && !exactKeys(value, ["type", "streamId", "value"])) {
764
+ throw new MuxFrameError("item frame must carry exactly type, streamId [, value]");
765
+ }
766
+ return { type: "item", streamId, value: value.value };
767
+ }
768
+ if (type === "end") {
769
+ if (!exactKeys(value, ["type", "streamId"])) {
770
+ throw new MuxFrameError("end frame must carry exactly type, streamId");
771
+ }
772
+ return { type: "end", streamId };
773
+ }
774
+ if (type === "error") {
775
+ if (!exactKeys(value, ["type", "streamId", "error"])) {
776
+ throw new MuxFrameError("error frame must carry exactly type, streamId, error");
777
+ }
778
+ return { type: "error", streamId, error: parseRemoteErrorFields(value.error) };
779
+ }
780
+ throw new MuxFrameError(`unknown mux frame type: ${String(type)}`);
781
+ }
782
+ function parseEventsReady(value) {
783
+ if (!isPlainRecord(value) || !exactKeys(value, ["type", "clientId", "host"])) {
784
+ throw new MuxFrameError("$events opening item must carry exactly type, clientId, host");
785
+ }
786
+ const record = value;
787
+ if (record.type !== "ready") {
788
+ throw new MuxFrameError(`$events opening item must be ready, got: ${String(record.type)}`);
789
+ }
790
+ if (typeof record.clientId !== "string" || record.clientId.length === 0) {
791
+ throw new MuxFrameError("$events ready clientId must be a non-empty string");
792
+ }
793
+ const host = record.host;
794
+ if (!isPlainRecord(host) || !exactKeys(host, ["home"]) || typeof host.home !== "string") {
795
+ throw new MuxFrameError("$events ready host must carry exactly home: string");
796
+ }
797
+ return { type: "ready", clientId: record.clientId, host: { home: host.home } };
798
+ }
799
+ function parseEventsItem(value) {
800
+ if (!isPlainRecord(value))
801
+ throw new MuxFrameError("$events item must be a plain object");
802
+ const record = value;
803
+ if (record.type === "cancel") {
804
+ if (!exactKeys(record, ["type", "eventId"]) || typeof record.eventId !== "string" || record.eventId.length === 0) {
805
+ throw new MuxFrameError("$events cancel item must carry exactly type, eventId: string");
806
+ }
807
+ return { type: "cancel", eventId: record.eventId };
808
+ }
809
+ if (record.type === "emit") {
810
+ if (!exactKeys(record, ["type", "event", "args"]) || typeof record.event !== "string" || record.event.length === 0 || !Array.isArray(record.args) || !isRemoteJson(record.args)) {
811
+ throw new MuxFrameError("$events emit item must carry exactly type, event: string, args: JSON[]");
812
+ }
813
+ return { type: "emit", event: record.event, args: record.args };
814
+ }
815
+ if (record.type === "waterfall") {
816
+ const request = record.request;
817
+ if (!exactKeys(record, ["type", "event", "eventId", "agentId", "request"]) || typeof record.event !== "string" || record.event.length === 0 || typeof record.eventId !== "string" || record.eventId.length === 0 || typeof record.agentId !== "string" || record.agentId.length === 0 || !isPlainRecord(request) || Object.hasOwn(request, "agent") || Object.hasOwn(request, "signal") || !isRemoteJson(request)) {
818
+ throw new MuxFrameError("$events waterfall item has an invalid frame shape");
819
+ }
820
+ return {
821
+ type: "waterfall",
822
+ event: record.event,
823
+ eventId: record.eventId,
824
+ agentId: record.agentId,
825
+ request
826
+ };
827
+ }
828
+ throw new MuxFrameError(`unknown $events item type: ${String(record.type)}`);
829
+ }
830
+ function parseRemoteErrorFields(value) {
831
+ if (!isPlainRecord(value) || !exactKeys(value, ["code", "message", "details"])) {
832
+ throw new MuxFrameError("remote error must carry exactly code, message, details");
833
+ }
834
+ const record = value;
835
+ if (typeof record.code !== "string" || typeof record.message !== "string" || !isPlainRecord(record.details)) {
836
+ throw new MuxFrameError("remote error code/message must be strings and details an object");
837
+ }
838
+ if (!isRemoteJson(record.details)) {
839
+ throw new MuxFrameError("remote error details must be JSON data");
840
+ }
841
+ return record;
842
+ }
843
+ function isRecord(value) {
844
+ return typeof value === "object" && value !== null && !Array.isArray(value);
845
+ }
846
+ function isPlainRecord(value) {
847
+ if (!isRecord(value))
848
+ return false;
849
+ const prototype = Object.getPrototypeOf(value);
850
+ return prototype === Object.prototype || prototype === null;
851
+ }
852
+ function exactKeys(value, expected) {
853
+ return Reflect.ownKeys(value).length === expected.length && expected.every((key) => Object.hasOwn(value, key));
854
+ }
855
+ function isRemoteJson(value) {
856
+ if (value === null)
857
+ return true;
858
+ const kind = typeof value;
859
+ if (kind === "boolean" || kind === "number" || kind === "string")
860
+ return true;
861
+ if (Array.isArray(value))
862
+ return value.every(isRemoteJson);
863
+ if (isPlainRecord(value))
864
+ return Object.values(value).every(isRemoteJson);
865
+ return false;
866
+ }
867
+ var MuxFrameError;
868
+ var init_mux_frame = __esm(() => {
869
+ MuxFrameError = class MuxFrameError extends Error {
870
+ constructor(message, options) {
871
+ super(message, options);
872
+ this.name = "MuxFrameError";
873
+ }
874
+ };
875
+ });
876
+
877
+ // src/client/host-probe.ts
878
+ import { randomUUID } from "crypto";
879
+ import WS from "ws";
880
+ function validAuthority(authority) {
881
+ return typeof authority === "string" && authority.length > 0 && !/[\r\n/]/.test(authority);
882
+ }
883
+ async function probeHostHttp(options) {
884
+ if (!validAuthority(options.authority))
885
+ return false;
886
+ const timeoutMs = options.timeoutMs ?? DEFAULT_HOST_PROBE_TIMEOUT_MS;
887
+ try {
888
+ const response = await fetch(`http://${options.authority}/`, {
889
+ headers: { cookie: options.cookieHeader },
890
+ signal: AbortSignal.timeout(timeoutMs)
891
+ });
892
+ try {
893
+ await response.body?.cancel();
894
+ } catch {}
895
+ return response.status >= 200 && response.status < 400;
896
+ } catch {
897
+ return false;
898
+ }
899
+ }
900
+ async function probeHostMux(options) {
901
+ if (!validAuthority(options.authority))
902
+ return false;
903
+ const timeoutMs = options.timeoutMs ?? DEFAULT_HOST_PROBE_TIMEOUT_MS;
904
+ return await new Promise((resolve) => {
905
+ let settled = false;
906
+ let socket;
907
+ const timer = setTimeout(() => done(false), timeoutMs);
908
+ function done(ok) {
909
+ if (settled)
910
+ return;
911
+ settled = true;
912
+ clearTimeout(timer);
913
+ try {
914
+ socket?.removeAllListeners();
915
+ socket?.terminate();
916
+ } catch {}
917
+ resolve(ok);
918
+ }
919
+ try {
920
+ socket = new WS(`ws://${options.authority}/api/remote.mux`, {
921
+ headers: { cookie: options.cookieHeader }
922
+ });
923
+ } catch {
924
+ done(false);
925
+ return;
926
+ }
927
+ socket.on("open", () => {
928
+ try {
929
+ socket?.send(JSON.stringify(openEventsStreamFrame(randomUUID())));
930
+ } catch {
931
+ done(false);
932
+ }
933
+ });
934
+ socket.on("message", (data) => {
935
+ try {
936
+ const frame = parseMuxFrame(String(data));
937
+ if (frame.type !== "item") {
938
+ done(false);
939
+ return;
940
+ }
941
+ const value = frame.value;
942
+ done(value?.type === "ready");
943
+ } catch {
944
+ done(false);
945
+ }
946
+ });
947
+ socket.on("unexpected-response", (_request, response) => {
948
+ try {
949
+ response.resume();
950
+ } catch {}
951
+ done(false);
952
+ });
953
+ socket.on("error", () => done(false));
954
+ socket.on("close", () => done(false));
955
+ });
956
+ }
957
+ var DEFAULT_HOST_PROBE_TIMEOUT_MS = 2000;
958
+ var init_host_probe = __esm(() => {
959
+ init_mux_frame();
960
+ });
961
+
743
962
  // src/client/cookie-mint.ts
744
963
  import { createHash, createHmac } from "crypto";
745
964
  import { readFileSync as readFileSync2, statSync as statSync2 } from "fs";
@@ -990,6 +1209,7 @@ __export(exports_lifecycle, {
990
1209
  HostBootTimeoutError: () => HostBootTimeoutError,
991
1210
  HostDiedError: () => HostDiedError,
992
1211
  HostLifecycleError: () => HostLifecycleError,
1212
+ HostNotServingError: () => HostNotServingError,
993
1213
  HostRespawnLoopError: () => HostRespawnLoopError,
994
1214
  HostSpawnError: () => HostSpawnError,
995
1215
  MintUnavailableError: () => MintUnavailableError,
@@ -1022,6 +1242,15 @@ function resolveIdleExitMs(explicitSec) {
1022
1242
  function resolveIdleExitSec(explicitSec) {
1023
1243
  return resolveIdleExitMs(explicitSec) / 1000;
1024
1244
  }
1245
+ function errorTail(outputTail) {
1246
+ const lines = outputTail.split(/\r?\n/).filter((line) => line.length > 0);
1247
+ if (lines.length === 0)
1248
+ return "";
1249
+ return `
1250
+ --- dsh host output (last ${Math.min(lines.length, ERROR_TAIL_LINES)} lines) ---
1251
+ ${lines.slice(-ERROR_TAIL_LINES).join(`
1252
+ `)}`;
1253
+ }
1025
1254
  function registryKey(dshHome, profile) {
1026
1255
  return `${dshHome}\x00${profile}`;
1027
1256
  }
@@ -1056,6 +1285,20 @@ function isListening(port) {
1056
1285
  socket.once("timeout", () => finish(false));
1057
1286
  });
1058
1287
  }
1288
+ async function httpResponds(port) {
1289
+ try {
1290
+ const response = await fetch(`http://127.0.0.1:${port}/`, {
1291
+ signal: AbortSignal.timeout(LISTEN_PROBE_TIMEOUT_MS),
1292
+ redirect: "manual"
1293
+ });
1294
+ try {
1295
+ await response.body?.cancel();
1296
+ } catch {}
1297
+ return true;
1298
+ } catch {
1299
+ return false;
1300
+ }
1301
+ }
1059
1302
  function getFreePort() {
1060
1303
  return new Promise((resolve, reject) => {
1061
1304
  const server = new Server((socket) => socket.destroy());
@@ -1277,7 +1520,8 @@ function readyFromUrl(urlText) {
1277
1520
  url: urlText,
1278
1521
  token: url.searchParams.get("token"),
1279
1522
  port,
1280
- authority: `${url.hostname}:${port}`
1523
+ authority: `${url.hostname}:${port}`,
1524
+ via: "url"
1281
1525
  };
1282
1526
  }
1283
1527
  function waitForReadiness(child, expectedPort, budgetMs, getTail) {
@@ -1306,13 +1550,14 @@ function waitForReadiness(child, expectedPort, budgetMs, getTail) {
1306
1550
  done(true, readyFromUrl(match[1]));
1307
1551
  });
1308
1552
  const poll = setInterval(() => {
1309
- isListening(expectedPort).then((up) => {
1553
+ httpResponds(expectedPort).then((up) => {
1310
1554
  if (up) {
1311
1555
  done(true, {
1312
1556
  url: null,
1313
1557
  token: null,
1314
1558
  port: expectedPort,
1315
- authority: `127.0.0.1:${expectedPort}`
1559
+ authority: `127.0.0.1:${expectedPort}`,
1560
+ via: "listener"
1316
1561
  });
1317
1562
  }
1318
1563
  });
@@ -1345,6 +1590,9 @@ function makeHandle(host) {
1345
1590
  get token() {
1346
1591
  return host.token;
1347
1592
  },
1593
+ diagnostics() {
1594
+ return errorTail(host.outputTail).replace(/^\n/, "");
1595
+ },
1348
1596
  get adopted() {
1349
1597
  return host.adopted;
1350
1598
  },
@@ -1427,9 +1675,18 @@ async function bootHost(o) {
1427
1675
  }
1428
1676
  if (lock && await lockIsFresh(lock, o.staleProbeMs)) {
1429
1677
  const adopted = adoptHost(lock, o);
1430
- respawnHistory.delete(o.key);
1431
1678
  adopted.cookieHeader = await mintCookieWithRetry(adopted);
1432
- return adopted;
1679
+ if (await probeHostHttp({
1680
+ authority: adopted.authority,
1681
+ cookieHeader: adopted.cookieHeader,
1682
+ timeoutMs: ADOPT_PROBE_TIMEOUT_MS
1683
+ })) {
1684
+ respawnHistory.delete(o.key);
1685
+ return adopted;
1686
+ }
1687
+ registry.delete(o.key);
1688
+ removeStaleLock(o.dshHome, o.profile, lock);
1689
+ continue;
1433
1690
  }
1434
1691
  if (lock)
1435
1692
  removeStaleLock(o.dshHome, o.profile, lock);
@@ -1497,6 +1754,24 @@ async function bootHost(o) {
1497
1754
  }
1498
1755
  host.authority = ready.authority;
1499
1756
  host.cookieHeader = await mintCookieWithRetry(host);
1757
+ if (ready.via === "listener") {
1758
+ const deadline = Date.now() + SERVE_PROBE_BUDGET_MS;
1759
+ let serving = false;
1760
+ while (Date.now() < deadline) {
1761
+ serving = await probeHostMux({
1762
+ authority: host.authority,
1763
+ cookieHeader: host.cookieHeader,
1764
+ timeoutMs: 1500
1765
+ });
1766
+ if (serving)
1767
+ break;
1768
+ if (!pidAlive(child.pid))
1769
+ break;
1770
+ await sleep(SERVE_PROBE_POLL_MS);
1771
+ }
1772
+ if (!serving)
1773
+ throw new HostNotServingError(host.outputTail);
1774
+ }
1500
1775
  if (!bootClaimIntact(o.dshHome, o.profile, claimStartedAt)) {
1501
1776
  throw new HostBootSupersededError;
1502
1777
  }
@@ -1610,8 +1885,9 @@ async function ensureHost(opts = {}) {
1610
1885
  attachHost(host);
1611
1886
  return makeHandle(host);
1612
1887
  }
1613
- var DEFAULT_PROFILE = "opentui", DEFAULT_IDLE_EXIT_MS = 5000, DEFAULT_IDLE_EXIT_SEC, ENV_IDLE_EXIT_MS = "DSH_OPENTUI_HOST_IDLE_MS", DEFAULT_READINESS_TIMEOUT_MS = 30000, DEFAULT_STALE_PROBE_MS = 8000, BOOT_JOIN_MARGIN_MS = 20000, BOOT_JOIN_POLL_MS = 200, RESPAWN_WINDOW_MS = 15000, MAX_RAPID_RESPAWNS = 3, LISTEN_PROBE_TIMEOUT_MS = 750, LISTEN_POLL_MS = 200, KILL_GRACE_MS = 5000, KILL_ESCALATE_MS = 2000, OUTPUT_TAIL_CAP = 8000, URL_LINE, HostLifecycleError, HostBootTimeoutError, HostDiedError, HostSpawnError, HostRespawnLoopError, HostBootSupersededError, ProfileMissingError, MintUnavailableError, registry, pendingBoots, respawnHistory, sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)), realMintPromise = null, RETRYABLE_MINT_ERRORS, MINT_RETRY_BUDGET_MS = 15000, MINT_RETRY_INTERVAL_MS = 250, FFI_FLAG = "--experimental-ffi", __internals;
1888
+ var DEFAULT_PROFILE = "opentui", DEFAULT_IDLE_EXIT_MS = 5000, DEFAULT_IDLE_EXIT_SEC, ENV_IDLE_EXIT_MS = "DSH_OPENTUI_HOST_IDLE_MS", DEFAULT_READINESS_TIMEOUT_MS = 30000, DEFAULT_STALE_PROBE_MS = 8000, BOOT_JOIN_MARGIN_MS = 20000, BOOT_JOIN_POLL_MS = 200, RESPAWN_WINDOW_MS = 15000, MAX_RAPID_RESPAWNS = 3, LISTEN_PROBE_TIMEOUT_MS = 750, LISTEN_POLL_MS = 200, ADOPT_PROBE_TIMEOUT_MS = 2000, SERVE_PROBE_POLL_MS = 250, SERVE_PROBE_BUDGET_MS = 20000, ERROR_TAIL_LINES = 12, KILL_GRACE_MS = 5000, KILL_ESCALATE_MS = 2000, OUTPUT_TAIL_CAP = 8000, URL_LINE, HostLifecycleError, HostBootTimeoutError, HostDiedError, HostNotServingError, HostSpawnError, HostRespawnLoopError, HostBootSupersededError, ProfileMissingError, MintUnavailableError, registry, pendingBoots, respawnHistory, sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)), realMintPromise = null, RETRYABLE_MINT_ERRORS, MINT_RETRY_BUDGET_MS = 15000, MINT_RETRY_INTERVAL_MS = 250, FFI_FLAG = "--experimental-ffi", __internals;
1614
1889
  var init_lifecycle = __esm(() => {
1890
+ init_host_probe();
1615
1891
  DEFAULT_IDLE_EXIT_SEC = DEFAULT_IDLE_EXIT_MS / 1000;
1616
1892
  URL_LINE = /dsh web: (https?:\/\/\S+)/;
1617
1893
  HostLifecycleError = class HostLifecycleError extends Error {
@@ -1626,7 +1902,7 @@ var init_lifecycle = __esm(() => {
1626
1902
  budgetMs;
1627
1903
  outputTail;
1628
1904
  constructor(budgetMs, outputTail) {
1629
- super("host-boot-timeout", `dsh host did not become ready within ${budgetMs}ms`);
1905
+ super("host-boot-timeout", `dsh host did not become ready within ${budgetMs}ms${errorTail(outputTail)}`);
1630
1906
  this.budgetMs = budgetMs;
1631
1907
  this.outputTail = outputTail;
1632
1908
  }
@@ -1636,12 +1912,19 @@ var init_lifecycle = __esm(() => {
1636
1912
  signal;
1637
1913
  outputTail;
1638
1914
  constructor(exitCode, signal, outputTail) {
1639
- super("host-died", `dsh host exited before readiness (code=${exitCode ?? "null"}, signal=${signal ?? "null"})`);
1915
+ super("host-died", `dsh host exited before readiness (code=${exitCode ?? "null"}, signal=${signal ?? "null"})${errorTail(outputTail)}`);
1640
1916
  this.exitCode = exitCode;
1641
1917
  this.signal = signal;
1642
1918
  this.outputTail = outputTail;
1643
1919
  }
1644
1920
  };
1921
+ HostNotServingError = class HostNotServingError extends HostLifecycleError {
1922
+ outputTail;
1923
+ constructor(outputTail) {
1924
+ super("host-not-serving", `dsh host is listening but never served the client mux (${SERVE_PROBE_BUDGET_MS}ms budget)${errorTail(outputTail)}`);
1925
+ this.outputTail = outputTail;
1926
+ }
1927
+ };
1645
1928
  HostSpawnError = class HostSpawnError extends HostLifecycleError {
1646
1929
  cause;
1647
1930
  constructor(cause) {
@@ -3533,140 +3816,6 @@ var init_lib2 = __esm(() => {
3533
3816
  };
3534
3817
  });
3535
3818
 
3536
- // src/client/mux-frame.ts
3537
- function openEventsStreamFrame(streamId) {
3538
- return { type: "open", streamId, endpoint: "$events", payload: { args: {} } };
3539
- }
3540
- function parseMuxFrame(text) {
3541
- let decoded;
3542
- try {
3543
- decoded = JSON.parse(text);
3544
- } catch (cause) {
3545
- throw new MuxFrameError("mux frame is not JSON", { cause });
3546
- }
3547
- if (!isRecord(decoded))
3548
- throw new MuxFrameError("mux frame must be an object");
3549
- const value = decoded;
3550
- const type = value.type;
3551
- const streamId = value.streamId;
3552
- if (typeof streamId !== "string" || streamId.length === 0) {
3553
- throw new MuxFrameError("mux frame streamId is missing or empty");
3554
- }
3555
- if (type === "item") {
3556
- if (!exactKeys(value, ["type", "streamId"]) && !exactKeys(value, ["type", "streamId", "value"])) {
3557
- throw new MuxFrameError("item frame must carry exactly type, streamId [, value]");
3558
- }
3559
- return { type: "item", streamId, value: value.value };
3560
- }
3561
- if (type === "end") {
3562
- if (!exactKeys(value, ["type", "streamId"])) {
3563
- throw new MuxFrameError("end frame must carry exactly type, streamId");
3564
- }
3565
- return { type: "end", streamId };
3566
- }
3567
- if (type === "error") {
3568
- if (!exactKeys(value, ["type", "streamId", "error"])) {
3569
- throw new MuxFrameError("error frame must carry exactly type, streamId, error");
3570
- }
3571
- return { type: "error", streamId, error: parseRemoteErrorFields(value.error) };
3572
- }
3573
- throw new MuxFrameError(`unknown mux frame type: ${String(type)}`);
3574
- }
3575
- function parseEventsReady(value) {
3576
- if (!isPlainRecord(value) || !exactKeys(value, ["type", "clientId", "host"])) {
3577
- throw new MuxFrameError("$events opening item must carry exactly type, clientId, host");
3578
- }
3579
- const record = value;
3580
- if (record.type !== "ready") {
3581
- throw new MuxFrameError(`$events opening item must be ready, got: ${String(record.type)}`);
3582
- }
3583
- if (typeof record.clientId !== "string" || record.clientId.length === 0) {
3584
- throw new MuxFrameError("$events ready clientId must be a non-empty string");
3585
- }
3586
- const host = record.host;
3587
- if (!isPlainRecord(host) || !exactKeys(host, ["home"]) || typeof host.home !== "string") {
3588
- throw new MuxFrameError("$events ready host must carry exactly home: string");
3589
- }
3590
- return { type: "ready", clientId: record.clientId, host: { home: host.home } };
3591
- }
3592
- function parseEventsItem(value) {
3593
- if (!isPlainRecord(value))
3594
- throw new MuxFrameError("$events item must be a plain object");
3595
- const record = value;
3596
- if (record.type === "cancel") {
3597
- if (!exactKeys(record, ["type", "eventId"]) || typeof record.eventId !== "string" || record.eventId.length === 0) {
3598
- throw new MuxFrameError("$events cancel item must carry exactly type, eventId: string");
3599
- }
3600
- return { type: "cancel", eventId: record.eventId };
3601
- }
3602
- if (record.type === "emit") {
3603
- if (!exactKeys(record, ["type", "event", "args"]) || typeof record.event !== "string" || record.event.length === 0 || !Array.isArray(record.args) || !isRemoteJson(record.args)) {
3604
- throw new MuxFrameError("$events emit item must carry exactly type, event: string, args: JSON[]");
3605
- }
3606
- return { type: "emit", event: record.event, args: record.args };
3607
- }
3608
- if (record.type === "waterfall") {
3609
- const request = record.request;
3610
- if (!exactKeys(record, ["type", "event", "eventId", "agentId", "request"]) || typeof record.event !== "string" || record.event.length === 0 || typeof record.eventId !== "string" || record.eventId.length === 0 || typeof record.agentId !== "string" || record.agentId.length === 0 || !isPlainRecord(request) || Object.hasOwn(request, "agent") || Object.hasOwn(request, "signal") || !isRemoteJson(request)) {
3611
- throw new MuxFrameError("$events waterfall item has an invalid frame shape");
3612
- }
3613
- return {
3614
- type: "waterfall",
3615
- event: record.event,
3616
- eventId: record.eventId,
3617
- agentId: record.agentId,
3618
- request
3619
- };
3620
- }
3621
- throw new MuxFrameError(`unknown $events item type: ${String(record.type)}`);
3622
- }
3623
- function parseRemoteErrorFields(value) {
3624
- if (!isPlainRecord(value) || !exactKeys(value, ["code", "message", "details"])) {
3625
- throw new MuxFrameError("remote error must carry exactly code, message, details");
3626
- }
3627
- const record = value;
3628
- if (typeof record.code !== "string" || typeof record.message !== "string" || !isPlainRecord(record.details)) {
3629
- throw new MuxFrameError("remote error code/message must be strings and details an object");
3630
- }
3631
- if (!isRemoteJson(record.details)) {
3632
- throw new MuxFrameError("remote error details must be JSON data");
3633
- }
3634
- return record;
3635
- }
3636
- function isRecord(value) {
3637
- return typeof value === "object" && value !== null && !Array.isArray(value);
3638
- }
3639
- function isPlainRecord(value) {
3640
- if (!isRecord(value))
3641
- return false;
3642
- const prototype = Object.getPrototypeOf(value);
3643
- return prototype === Object.prototype || prototype === null;
3644
- }
3645
- function exactKeys(value, expected) {
3646
- return Reflect.ownKeys(value).length === expected.length && expected.every((key) => Object.hasOwn(value, key));
3647
- }
3648
- function isRemoteJson(value) {
3649
- if (value === null)
3650
- return true;
3651
- const kind = typeof value;
3652
- if (kind === "boolean" || kind === "number" || kind === "string")
3653
- return true;
3654
- if (Array.isArray(value))
3655
- return value.every(isRemoteJson);
3656
- if (isPlainRecord(value))
3657
- return Object.values(value).every(isRemoteJson);
3658
- return false;
3659
- }
3660
- var MuxFrameError;
3661
- var init_mux_frame = __esm(() => {
3662
- MuxFrameError = class MuxFrameError extends Error {
3663
- constructor(message, options) {
3664
- super(message, options);
3665
- this.name = "MuxFrameError";
3666
- }
3667
- };
3668
- });
3669
-
3670
3819
  // src/client/events-source.ts
3671
3820
  function createEventsPumpSource(openWebSocket, callbacks) {
3672
3821
  return async (signal, ready) => {
@@ -3821,10 +3970,11 @@ var exports_transport = {};
3821
3970
  __export(exports_transport, {
3822
3971
  ClientConnection: () => ClientConnection,
3823
3972
  ConnectionClosedError: () => ConnectionClosedError,
3973
+ ConnectionRetryExhaustedError: () => ConnectionRetryExhaustedError,
3824
3974
  RemoteRpcError: () => RemoteRpcError,
3825
3975
  RpcTransportError: () => RpcTransportError
3826
3976
  });
3827
- import WS from "ws";
3977
+ import WS2 from "ws";
3828
3978
 
3829
3979
  class ClientConnection {
3830
3980
  authority;
@@ -3839,6 +3989,12 @@ class ClientConnection {
3839
3989
  #stateListeners = new Set;
3840
3990
  #state = "connecting";
3841
3991
  #closed = false;
3992
+ #maxConnectAttempts;
3993
+ #connectBudgetMs;
3994
+ #diagnostics;
3995
+ #connectAttempts = 0;
3996
+ #connectedOnce = false;
3997
+ #budgetTimer;
3842
3998
  #transport;
3843
3999
  #recovery;
3844
4000
  #pumpCallbacks;
@@ -3854,7 +4010,7 @@ class ClientConnection {
3854
4010
  this.baseUrl = options.baseUrl ?? `http://${authority}`;
3855
4011
  this.#transport = {
3856
4012
  streamBaseUrl: this.baseUrl,
3857
- createWebSocket: (url) => new WS(url, { headers: { cookie: cookieHeader } }),
4013
+ createWebSocket: (url) => new WS2(url, { headers: { cookie: cookieHeader } }),
3858
4014
  fetch: (input, init) => {
3859
4015
  const url = new URL(input instanceof URL ? input.href : input, this.baseUrl).href;
3860
4016
  const headers = new Headers(init?.headers);
@@ -3863,6 +4019,9 @@ class ClientConnection {
3863
4019
  }
3864
4020
  };
3865
4021
  this.#recovery = options.recovery;
4022
+ this.#maxConnectAttempts = Math.max(0, options.maxConnectAttempts ?? DEFAULT_MAX_CONNECT_ATTEMPTS);
4023
+ this.#connectBudgetMs = Math.max(1, options.connectBudgetMs ?? DEFAULT_CONNECT_BUDGET_MS);
4024
+ this.#diagnostics = options.diagnostics;
3866
4025
  this.#pumpCallbacks = {
3867
4026
  onReady: (info) => {
3868
4027
  this.#readyInfo = info;
@@ -3890,12 +4049,33 @@ class ClientConnection {
3890
4049
  if (!handle)
3891
4050
  throw new RpcTransportError("connection service failed to install");
3892
4051
  this.#handle = handle;
3893
- handle.registerGenerationSource(createEventsPumpSource((path) => handle.openWebSocket(path), this.#pumpCallbacks));
4052
+ const pump = createEventsPumpSource((path) => handle.openWebSocket(path), this.#pumpCallbacks);
4053
+ handle.registerGenerationSource((signal, ready) => {
4054
+ if (!this.#connectedOnce) {
4055
+ this.#connectAttempts += 1;
4056
+ if (this.#connectAttempts > this.#maxConnectAttempts + 1) {
4057
+ this.#failConnect(new ConnectionRetryExhaustedError(this.#maxConnectAttempts, this.authority, this.#diagnostics?.()));
4058
+ return new Promise((resolve) => {
4059
+ if (signal.aborted)
4060
+ resolve();
4061
+ else
4062
+ signal.addEventListener("abort", () => resolve(), { once: true });
4063
+ });
4064
+ }
4065
+ }
4066
+ return pump(signal, ready);
4067
+ });
3894
4068
  return await new Promise((resolve, reject) => {
3895
4069
  this.#resolveConnect = resolve;
3896
4070
  this.#rejectConnect = reject;
4071
+ this.#budgetTimer = setTimeout(() => {
4072
+ this.#failConnect(new ConnectionRetryExhaustedError(Math.max(1, this.#connectAttempts), this.authority, this.#diagnostics?.()));
4073
+ }, this.#connectBudgetMs);
4074
+ this.#budgetTimer.unref?.();
3897
4075
  this.#loop = handle.start({
3898
4076
  onConnected: () => {
4077
+ this.#connectedOnce = true;
4078
+ this.#clearBudgetTimer();
3899
4079
  const info = this.#readyInfo;
3900
4080
  if (info)
3901
4081
  this.#resolveConnect?.(info);
@@ -3945,6 +4125,7 @@ class ClientConnection {
3945
4125
  if (this.#closed)
3946
4126
  return;
3947
4127
  this.#closed = true;
4128
+ this.#clearBudgetTimer();
3948
4129
  this.#loop?.stop();
3949
4130
  this.#loop = undefined;
3950
4131
  this.#rejectConnect?.(new ConnectionClosedError("connection closed before connecting"));
@@ -3954,6 +4135,24 @@ class ClientConnection {
3954
4135
  this.#publishState("disconnected");
3955
4136
  this.#stateListeners.clear();
3956
4137
  }
4138
+ #clearBudgetTimer() {
4139
+ if (this.#budgetTimer !== undefined) {
4140
+ clearTimeout(this.#budgetTimer);
4141
+ this.#budgetTimer = undefined;
4142
+ }
4143
+ }
4144
+ #failConnect(error) {
4145
+ this.#clearBudgetTimer();
4146
+ const loop = this.#loop;
4147
+ this.#loop = undefined;
4148
+ try {
4149
+ loop?.stop();
4150
+ } catch {}
4151
+ const reject = this.#rejectConnect;
4152
+ this.#resolveConnect = undefined;
4153
+ this.#rejectConnect = undefined;
4154
+ reject?.(error);
4155
+ }
3957
4156
  #dispatch(item) {
3958
4157
  for (const handler of [...this.#handlers]) {
3959
4158
  try {
@@ -3976,7 +4175,7 @@ class ClientConnection {
3976
4175
  }
3977
4176
  }
3978
4177
  }
3979
- var RemoteRpcError, RpcTransportError, ConnectionClosedError;
4178
+ var RemoteRpcError, RpcTransportError, ConnectionClosedError, ConnectionRetryExhaustedError, DEFAULT_MAX_CONNECT_ATTEMPTS = 3, DEFAULT_CONNECT_BUDGET_MS = 30000;
3980
4179
  var init_transport = __esm(() => {
3981
4180
  init_lib2();
3982
4181
  init_events_source();
@@ -4002,6 +4201,21 @@ var init_transport = __esm(() => {
4002
4201
  this.name = "ConnectionClosedError";
4003
4202
  }
4004
4203
  };
4204
+ ConnectionRetryExhaustedError = class ConnectionRetryExhaustedError extends Error {
4205
+ attempts;
4206
+ authority;
4207
+ diagnostics;
4208
+ code = "connection-retry-exhausted";
4209
+ constructor(attempts, authority, diagnostics) {
4210
+ const tail = diagnostics?.trim();
4211
+ super(`host ${authority} never accepted the client connection after ${attempts} retr${attempts === 1 ? "y" : "ies"}` + (tail ? `
4212
+ ${tail}` : ""));
4213
+ this.attempts = attempts;
4214
+ this.authority = authority;
4215
+ this.diagnostics = diagnostics;
4216
+ this.name = "ConnectionRetryExhaustedError";
4217
+ }
4218
+ };
4005
4219
  });
4006
4220
  // src/agent/tools.ts
4007
4221
  var init_tools = () => {};
@@ -6062,12 +6276,28 @@ var init_remote_attachments = __esm(() => {
6062
6276
  });
6063
6277
 
6064
6278
  // src/client/remote-btw.ts
6065
- import { randomUUID } from "crypto";
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
+ }
6066
6296
  async function askBtw(options) {
6067
6297
  const timeoutMs = options.timeoutMs ?? 120000;
6068
6298
  let sessionId = options.previousSessionId ?? "";
6069
6299
  if (!sessionId) {
6070
- const requested = randomUUID();
6300
+ const requested = randomUUID2();
6071
6301
  const value = await options.rpc("session/create", { request: { cwd: options.cwd, sessionId: requested } });
6072
6302
  sessionId = typeof value.sessionId === "string" ? value.sessionId : requested;
6073
6303
  if (options.stagedModel) {
@@ -6083,6 +6313,10 @@ async function askBtw(options) {
6083
6313
  let pump;
6084
6314
  let timer;
6085
6315
  let promptFailure;
6316
+ let deltas = 0;
6317
+ let turnEnds = 0;
6318
+ let streamEnds = 0;
6319
+ let streamFails = 0;
6086
6320
  const settle = (errorText) => {
6087
6321
  if (settled)
6088
6322
  return;
@@ -6095,11 +6329,13 @@ async function askBtw(options) {
6095
6329
  }).catch(() => {});
6096
6330
  };
6097
6331
  const answer = await new Promise((resolve) => {
6098
- 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" : ""}`);
6099
6335
  settle(errorText);
6100
6336
  resolve(errorText !== undefined ? errorText : out.trim());
6101
6337
  };
6102
- timer = setTimeout(() => finish(undefined), timeoutMs);
6338
+ timer = setTimeout(() => finish(undefined, "timeout"), timeoutMs);
6103
6339
  timer.unref?.();
6104
6340
  pump = openRemoteStream(options.socketFactory, "session/follow", { request: { address: { kind: "session", sessionId }, assistantStream: true } }, {
6105
6341
  onItem: (value) => {
@@ -6111,6 +6347,7 @@ async function askBtw(options) {
6111
6347
  const chunk = typeof streamFrame.chunk === "object" && streamFrame.chunk !== null ? streamFrame.chunk : {};
6112
6348
  if (chunk.type === "text-delta" && typeof chunk.text === "string" && chunk.text) {
6113
6349
  out += chunk.text;
6350
+ deltas += 1;
6114
6351
  try {
6115
6352
  options.onDelta?.(out);
6116
6353
  } catch {}
@@ -6123,16 +6360,26 @@ async function askBtw(options) {
6123
6360
  return;
6124
6361
  const data = typeof event.data === "object" && event.data !== null ? event.data : {};
6125
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}`);
6126
6365
  if (reason.kind === "error") {
6127
6366
  const err = typeof reason.error === "object" && reason.error !== null ? reason.error : {};
6128
- finish(`error: ${String(err.message ?? "unknown").slice(0, 200)}`);
6367
+ finish(`error: ${String(err.message ?? "unknown").slice(0, 200)}`, "turn-end-error");
6129
6368
  return;
6130
6369
  }
6131
- finish(undefined);
6370
+ finish(undefined, "turn-end");
6132
6371
  }
6133
6372
  },
6134
- onEnd: () => finish(undefined),
6135
- 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
+ }
6136
6383
  });
6137
6384
  const snap = options.snapshot.length > 0 ? `Recent conversation context (for reference only):
6138
6385
  ${options.snapshot.join(`
@@ -6141,14 +6388,14 @@ ${options.snapshot.join(`
6141
6388
  ` : "";
6142
6389
  options.rpc("session/prompt", {
6143
6390
  request: {
6144
- requestId: randomUUID(),
6391
+ requestId: randomUUID2(),
6145
6392
  sessionId,
6146
6393
  mode: "queue",
6147
6394
  content: [{ type: "text", text: `${snap}Side question (answer in one or two sentences, do not use tools): ${options.question}` }]
6148
6395
  }
6149
6396
  }).then(() => {}, (error) => {
6150
6397
  promptFailure = { error };
6151
- finish(undefined);
6398
+ finish(undefined, "prompt-rejected");
6152
6399
  });
6153
6400
  });
6154
6401
  if (promptFailure !== undefined) {
@@ -6403,8 +6650,133 @@ var init_subagent_policy = __esm(() => {
6403
6650
  FOREGROUND_LABEL_PREFIXES = ["[fg] ", "[use_agent foreground] "];
6404
6651
  });
6405
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
+
6406
6778
  // src/client/remote-subagents.ts
6407
- import { randomUUID as randomUUID2 } from "crypto";
6779
+ import { randomUUID as randomUUID3 } from "crypto";
6408
6780
 
6409
6781
  class RemoteSubagentPanel {
6410
6782
  #options;
@@ -6413,6 +6785,7 @@ class RemoteSubagentPanel {
6413
6785
  #pumps = new Map;
6414
6786
  #stopped = false;
6415
6787
  #policy;
6788
+ #spinAttention;
6416
6789
  constructor(options) {
6417
6790
  this.#options = options;
6418
6791
  if (options.limits !== undefined) {
@@ -6456,6 +6829,13 @@ class RemoteSubagentPanel {
6456
6829
  }
6457
6830
  });
6458
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
+ }
6459
6839
  }
6460
6840
  foldParentRecord(entry) {
6461
6841
  if (entry.type === "tool-workflow/agent-start") {
@@ -6557,7 +6937,7 @@ class RemoteSubagentPanel {
6557
6937
  try {
6558
6938
  await this.#options.rpc("subagents/prompt", {
6559
6939
  request: {
6560
- requestId: randomUUID2(),
6940
+ requestId: randomUUID3(),
6561
6941
  parentSessionId: parent,
6562
6942
  childSessionId: id,
6563
6943
  mode: "continuable",
@@ -6582,7 +6962,7 @@ class RemoteSubagentPanel {
6582
6962
  try {
6583
6963
  await this.#options.rpc("subagents/prompt", {
6584
6964
  request: {
6585
- requestId: randomUUID2(),
6965
+ requestId: randomUUID3(),
6586
6966
  parentSessionId: parent,
6587
6967
  childSessionId: id,
6588
6968
  mode: "continuable",
@@ -6743,6 +7123,7 @@ class RemoteSubagentPanel {
6743
7123
  if (this.#policy !== undefined && options.feedLadder) {
6744
7124
  this.#options.refreshLimits?.();
6745
7125
  this.#policy.onRoundCount(id, next.rounds, next.label);
7126
+ this.#tickSpinAttention();
6746
7127
  }
6747
7128
  for (const line of text.split(`
6748
7129
  `))
@@ -6772,6 +7153,19 @@ class RemoteSubagentPanel {
6772
7153
  log.shift();
6773
7154
  return changed;
6774
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
+ }
6775
7169
  #emit() {
6776
7170
  try {
6777
7171
  this.#options.onUpdate?.(this.views());
@@ -6978,18 +7372,22 @@ __export(exports_remote_host_session, {
6978
7372
  REATTACH_MAX_ATTEMPTS: () => REATTACH_MAX_ATTEMPTS,
6979
7373
  REATTACH_RETRY_MS: () => REATTACH_RETRY_MS,
6980
7374
  RemoteHostSession: () => RemoteHostSession,
7375
+ SPIN_REFRESH_TTL_MS: () => SPIN_REFRESH_TTL_MS,
6981
7376
  openRemoteStream: () => openRemoteStream
6982
7377
  });
6983
- import { randomUUID as randomUUID3 } from "crypto";
7378
+ import { randomUUID as randomUUID4 } from "crypto";
6984
7379
  import { existsSync as existsSync7, mkdirSync as mkdirSync4, readFileSync as readFileSync7, renameSync as renameSync5, rmSync as rmSync4, writeFileSync as writeFileSync6 } from "fs";
6985
7380
  import { join as joinPath } from "path";
6986
- import WS2 from "ws";
7381
+ import WS3 from "ws";
6987
7382
  function trace(message) {
6988
7383
  if (!process.env.DSH_OPENTUI_DEBUG)
6989
7384
  return;
6990
7385
  process.stderr.write(`[rhs ${new Date().toISOString().slice(11, 23)}] ${message}
6991
7386
  `);
6992
7387
  }
7388
+ function selectionErrorText(error) {
7389
+ return String(error instanceof Error ? error.message : error).slice(0, 150);
7390
+ }
6993
7391
 
6994
7392
  class RemoteHostSession {
6995
7393
  label = "dsh-host";
@@ -7031,6 +7429,7 @@ class RemoteHostSession {
7031
7429
  #promptInFlight = false;
7032
7430
  #interrupted = false;
7033
7431
  #pendingModel;
7432
+ #selectionError;
7034
7433
  #turns = 0;
7035
7434
  #turnStartedAt = 0;
7036
7435
  #turnUsageStart = { prompt: 0, completion: 0 };
@@ -7067,6 +7466,10 @@ class RemoteHostSession {
7067
7466
  #lastRestartPid;
7068
7467
  #btwBusy = false;
7069
7468
  #subagents;
7469
+ #spinAttentionOn = true;
7470
+ #spinAttentionRefreshing = false;
7471
+ #spinRefreshTtlMs;
7472
+ #spinCheckedAt = -Infinity;
7070
7473
  #overlayCache;
7071
7474
  constructor(options) {
7072
7475
  this.#connection = options.connection;
@@ -7079,10 +7482,11 @@ class RemoteHostSession {
7079
7482
  this.#restartHost = options.restartHost;
7080
7483
  this.#reattachRetryMs = options.reattachRetryMs ?? REATTACH_RETRY_MS;
7081
7484
  this.#reattachMaxAttempts = options.reattachMaxAttempts ?? REATTACH_MAX_ATTEMPTS;
7485
+ this.#spinRefreshTtlMs = options.spinRefreshTtlMs ?? SPIN_REFRESH_TTL_MS;
7082
7486
  this.#socketFactory = options.socketFactory ?? ((path) => this.#openMuxSocket(path));
7083
7487
  }
7084
7488
  #openMuxSocket(path) {
7085
- return new WS2(`${this.#baseUrl}${path}`, { headers: { cookie: this.#cookieHeader } });
7489
+ return new WS3(`${this.#baseUrl}${path}`, { headers: { cookie: this.#cookieHeader } });
7086
7490
  }
7087
7491
  async start() {
7088
7492
  if (this.#disposed)
@@ -7141,6 +7545,9 @@ class RemoteHostSession {
7141
7545
  currentSessionId() {
7142
7546
  return this.#sessionId;
7143
7547
  }
7548
+ stagedSessionId() {
7549
+ return this.#resumeId;
7550
+ }
7144
7551
  onJournalRecord(listener) {
7145
7552
  this.#journalListeners.push(listener);
7146
7553
  return () => {
@@ -7162,7 +7569,7 @@ class RemoteHostSession {
7162
7569
  this.#contextMeter.notePending(userText);
7163
7570
  await this.start();
7164
7571
  const sessionId = await this.#ensureSession();
7165
- const requestId = randomUUID3();
7572
+ const requestId = randomUUID4();
7166
7573
  const attachmentParts = this.#pendingUploads.map(imagePromptPart);
7167
7574
  this.#pendingUploads = [];
7168
7575
  await this.#rpc("session/prompt", {
@@ -7191,7 +7598,7 @@ class RemoteHostSession {
7191
7598
  return;
7192
7599
  this.#rpc("session/prompt", {
7193
7600
  request: {
7194
- requestId: randomUUID3(),
7601
+ requestId: randomUUID4(),
7195
7602
  sessionId,
7196
7603
  mode: "steer",
7197
7604
  content: [{ type: "text", text: userText }]
@@ -7352,8 +7759,12 @@ class RemoteHostSession {
7352
7759
  }
7353
7760
  this.#modelClient().selectModel(sessionId, selection).catch((error) => {
7354
7761
  console.error("[remote-host-session] selectModel failed:", error);
7762
+ this.#selectionError = selectionErrorText(error);
7355
7763
  });
7356
7764
  }
7765
+ lastSelectionError() {
7766
+ return this.#selectionError;
7767
+ }
7357
7768
  async selectModel(selection) {
7358
7769
  this.label = `${selection.provider}/${selection.model}${selection.reasoningEffort ? ` (${selection.reasoningEffort})` : ""}`;
7359
7770
  const sessionId = this.#sessionId;
@@ -7362,6 +7773,7 @@ class RemoteHostSession {
7362
7773
  return selection;
7363
7774
  }
7364
7775
  const selected = await this.#modelClient().selectModel(sessionId, selection);
7776
+ this.#selectionError = undefined;
7365
7777
  this.#invalidateContextProjections();
7366
7778
  return selected;
7367
7779
  }
@@ -7374,7 +7786,7 @@ class RemoteHostSession {
7374
7786
  async currentModelSelection() {
7375
7787
  const sessionId = this.#sessionId;
7376
7788
  if (sessionId === undefined)
7377
- return this.defaultModelSelection();
7789
+ return this.#pendingModel ?? await this.defaultModelSelection();
7378
7790
  return this.#modelClient().sessionSelection(sessionId);
7379
7791
  }
7380
7792
  async initializeDefaultModel() {
@@ -7944,6 +8356,8 @@ class RemoteHostSession {
7944
8356
  socketFactory: this.#socketFactory,
7945
8357
  parentId: () => this.#sessionId,
7946
8358
  limits: () => parseSubagentRoundLimits(this.configLoad()),
8359
+ refreshLimits: () => this.#refreshSpinAttention(),
8360
+ spinEnabled: () => this.#spinAttentionOn,
7947
8361
  onHardStop: (record) => console.info(`[subagent-policy] force-stopped child ${record.childId} at round ${record.round} (cap ${record.cap} + grace ${record.grace})`),
7948
8362
  onUpdate: (views) => {
7949
8363
  for (const listener of this.#subagentListeners) {
@@ -7959,6 +8373,20 @@ class RemoteHostSession {
7959
8373
  }
7960
8374
  return this.#subagents;
7961
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
+ }
7962
8390
  childTranscript(id) {
7963
8391
  return this.#subagentPanel().transcript(id);
7964
8392
  }
@@ -8046,7 +8474,7 @@ class RemoteHostSession {
8046
8474
  await this.#attachFollow(false);
8047
8475
  return this.#sessionId;
8048
8476
  }
8049
- const requestedId = this.#resumeId ?? randomUUID3();
8477
+ const requestedId = this.#resumeId ?? randomUUID4();
8050
8478
  this.#resumeId = undefined;
8051
8479
  const request = { cwd: this.#cwd, sessionId: requestedId };
8052
8480
  if (this.#presetId !== undefined)
@@ -8068,8 +8496,10 @@ class RemoteHostSession {
8068
8496
  this.#pendingModel = undefined;
8069
8497
  try {
8070
8498
  await this.#modelClient().selectModel(this.#sessionId, staged);
8499
+ this.#selectionError = undefined;
8071
8500
  } catch (error) {
8072
8501
  console.error("[remote-host-session] staged selectModel failed:", error);
8502
+ this.#selectionError = `staged ${staged.provider}/${staged.model} \u2014 ${selectionErrorText(error)}`;
8073
8503
  }
8074
8504
  }
8075
8505
  const opening = await this.#attachFollow(false);
@@ -8501,7 +8931,7 @@ function asPermissionOptions(value) {
8501
8931
  ];
8502
8932
  });
8503
8933
  }
8504
- 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;
8505
8935
  var init_remote_host_session = __esm(() => {
8506
8936
  init_loop();
8507
8937
  init_remote_follow();
@@ -11087,6 +11517,49 @@ var init_index_bun = __esm(() => {
11087
11517
  });
11088
11518
  });
11089
11519
 
11520
+ // ../tui-base/src/routes/session/terminal-size.ts
11521
+ function entryFor(renderer) {
11522
+ let entry = registry2.get(renderer);
11523
+ if (!entry) {
11524
+ const [size, setSize] = createSignal({ width: renderer.width, height: renderer.height });
11525
+ const created = {
11526
+ size,
11527
+ setSize,
11528
+ onResize: (width, height) => setSize({ width, height }),
11529
+ refs: 0,
11530
+ attached: false
11531
+ };
11532
+ registry2.set(renderer, created);
11533
+ entry = created;
11534
+ }
11535
+ return entry;
11536
+ }
11537
+ function useTerminalSize() {
11538
+ const renderer = useRenderer();
11539
+ const entry = entryFor(renderer);
11540
+ onMount(() => {
11541
+ entry.refs++;
11542
+ if (!entry.attached) {
11543
+ renderer.on("resize", entry.onResize);
11544
+ entry.attached = true;
11545
+ }
11546
+ });
11547
+ onCleanup(() => {
11548
+ entry.refs = Math.max(0, entry.refs - 1);
11549
+ if (entry.refs === 0 && entry.attached) {
11550
+ renderer.off("resize", entry.onResize);
11551
+ entry.attached = false;
11552
+ }
11553
+ });
11554
+ return entry.size;
11555
+ }
11556
+ var registry2;
11557
+ var init_terminal_size = __esm(() => {
11558
+ init_server();
11559
+ init_index_bun();
11560
+ registry2 = new WeakMap;
11561
+ });
11562
+
11090
11563
  // ../tui-base/src/routes/session/composer-state.ts
11091
11564
  class ComposerHistory {
11092
11565
  entries = [];
@@ -20583,7 +21056,7 @@ var init_keybind = __esm(() => {
20583
21056
  "variant.cycle": keybind("ctrl+t", "Cycle model variants"),
20584
21057
  "variant.list": keybind("none", "List model variants"),
20585
21058
  "session.page.up": keybind("pageup,ctrl+alt+b", "Scroll messages up by one page"),
20586
- "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"),
20587
21060
  "session.line.up": keybind("ctrl+alt+y", "Scroll messages up by one line"),
20588
21061
  "session.line.down": keybind("ctrl+alt+e", "Scroll messages down by one line"),
20589
21062
  "session.half.page.up": keybind("ctrl+alt+u", "Scroll messages up by half page"),
@@ -31670,7 +32143,7 @@ var init_hash = __esm(() => {
31670
32143
  // ../tui-base/src/vendor/util/src/flock.ts
31671
32144
  import path2 from "path";
31672
32145
  import os from "os";
31673
- import { randomBytes, randomUUID as randomUUID4 } from "crypto";
32146
+ import { randomBytes, randomUUID as randomUUID5 } from "crypto";
31674
32147
  import { mkdir, readFile as readFile2, rm, stat, utimes, writeFile } from "fs/promises";
31675
32148
  var Flock;
31676
32149
  var init_flock = __esm(() => {
@@ -31760,7 +32233,7 @@ var init_flock = __esm(() => {
31760
32233
  return now - dir.mtimeMs > staleMs;
31761
32234
  }
31762
32235
  async function tryAcquireLockDir(lockDir, opts) {
31763
- const token = randomUUID4?.() ?? randomBytes(16).toString("hex");
32236
+ const token = randomUUID5?.() ?? randomBytes(16).toString("hex");
31764
32237
  const metaPath = path2.join(lockDir, "meta.json");
31765
32238
  const heartbeatPath = path2.join(lockDir, "heartbeat");
31766
32239
  try {
@@ -39213,7 +39686,7 @@ import { measureEditText, RenderableEvents as RenderableEvents2 } from "@opentui
39213
39686
  function SessionComposer(props) {
39214
39687
  const FOOTER_HEIGHT = props.footerHint === false ? 0 : 1;
39215
39688
  const renderer = useRenderer();
39216
- const dimensions = useTerminalDimensions();
39689
+ const dimensions = useTerminalSize();
39217
39690
  const theme = useThemeOptional();
39218
39691
  let configCursorStyle;
39219
39692
  try {
@@ -39560,6 +40033,7 @@ var init_session_composer = __esm(() => {
39560
40033
  init_index_bun();
39561
40034
  init_server();
39562
40035
  init_index_bun();
40036
+ init_terminal_size();
39563
40037
  init_composer_keybinds();
39564
40038
  init_theme3();
39565
40039
  init_keymap();
@@ -39627,7 +40101,7 @@ function composerContextLabel(input) {
39627
40101
  return truncateLeft(branch ? `${dir} \xB7 ${branch}` : dir, input.maxColumns);
39628
40102
  }
39629
40103
  function ComposerContext(props) {
39630
- const dimensions = useTerminalDimensions();
40104
+ const dimensions = useTerminalSize();
39631
40105
  const theme = useThemeOptional();
39632
40106
  const [branch, setBranch] = createSignal("");
39633
40107
  let seq = 0;
@@ -39685,7 +40159,7 @@ var init_composer_context = __esm(() => {
39685
40159
  init_index_bun();
39686
40160
  init_index_bun();
39687
40161
  init_server();
39688
- init_index_bun();
40162
+ init_terminal_size();
39689
40163
  init_theme3();
39690
40164
  init_path_format();
39691
40165
  init_string_width();
@@ -45371,7 +45845,8 @@ function brandSegment(theme, presetLabel, mode = "dark") {
45371
45845
  const label = presetLabel ? `dsh(${presetLabel})` : "dsh";
45372
45846
  return {
45373
45847
  text: label,
45374
- bg: brandBlue(mode)
45848
+ bg: brandBlue(mode),
45849
+ priority: 100
45375
45850
  };
45376
45851
  }
45377
45852
  function providerSegment(provider, theme, mode = "dark") {
@@ -45381,11 +45856,13 @@ function providerSegment(provider, theme, mode = "dark") {
45381
45856
  if (!theme)
45382
45857
  return {
45383
45858
  text: label,
45384
- bg: POWERLINE_COLORS.provider
45859
+ bg: POWERLINE_COLORS.provider,
45860
+ priority: 60
45385
45861
  };
45386
45862
  return {
45387
45863
  text: label,
45388
- bg: powerlinePalette(theme, brandBlue(mode)).provider
45864
+ bg: powerlinePalette(theme, brandBlue(mode)).provider,
45865
+ priority: 60
45389
45866
  };
45390
45867
  }
45391
45868
  function effortIcon(effort) {
@@ -45405,7 +45882,8 @@ function modelSegment(model, effort = DEFAULT_EFFORT, theme) {
45405
45882
  const word = effectiveEffort(effort);
45406
45883
  return {
45407
45884
  text: `\uD83E\uDD16 ${clipToWidth(model, 24)} ${effortIcon(word)} ${word}`,
45408
- bg: effortFill(resolvePalette(theme), word)
45885
+ bg: effortFill(resolvePalette(theme), word),
45886
+ priority: 70
45409
45887
  };
45410
45888
  }
45411
45889
  function fmtNum(n) {
@@ -45426,6 +45904,8 @@ function contextSegment(used, window, theme) {
45426
45904
  return {
45427
45905
  text: `\uD83E\uDDE0 ${fmtNum(used)}/${fmtNum(window)}(${percent.toFixed(1)}%)`,
45428
45906
  bg,
45907
+ degrade: `\uD83E\uDDE0 ${fmtNum(used)}`,
45908
+ priority: 90,
45429
45909
  roll: {
45430
45910
  value: percent,
45431
45911
  decimals: 1,
@@ -45441,6 +45921,7 @@ function contextSegment(used, window, theme) {
45441
45921
  return {
45442
45922
  text: `\uD83E\uDDE0 ${fmtNum(used)}`,
45443
45923
  bg: p.contextOk,
45924
+ priority: 90,
45444
45925
  roll: {
45445
45926
  value: used,
45446
45927
  decimals: 0,
@@ -45455,7 +45936,8 @@ function messagesSegment(n, theme) {
45455
45936
  return null;
45456
45937
  return {
45457
45938
  text: `\uD83D\uDCAC ${n} msgs`,
45458
- bg: resolvePalette(theme).messages
45939
+ bg: resolvePalette(theme).messages,
45940
+ priority: 80
45459
45941
  };
45460
45942
  }
45461
45943
  function toolSegment(n, theme) {
@@ -45463,7 +45945,8 @@ function toolSegment(n, theme) {
45463
45945
  return null;
45464
45946
  return {
45465
45947
  text: `\uD83D\uDD27 ${n} tools`,
45466
- bg: resolvePalette(theme).tools
45948
+ bg: resolvePalette(theme).tools,
45949
+ priority: 50
45467
45950
  };
45468
45951
  }
45469
45952
  function speedSegment(tps, theme) {
@@ -45486,6 +45969,7 @@ function elapsedSegment(seconds, theme) {
45486
45969
  return {
45487
45970
  text: `\u23F1 ${Math.round(seconds)}s`,
45488
45971
  bg: theme?.hue.neutral[400] ?? "#616161",
45972
+ priority: 30,
45489
45973
  roll: {
45490
45974
  value: seconds,
45491
45975
  decimals: 0,
@@ -45500,7 +45984,8 @@ function cacheSegment(rate, theme) {
45500
45984
  return null;
45501
45985
  return {
45502
45986
  text: `\u26A1 CH${rate.toFixed(1)}%`,
45503
- bg: resolvePalette(theme).cache
45987
+ bg: resolvePalette(theme).cache,
45988
+ priority: 40
45504
45989
  };
45505
45990
  }
45506
45991
  function rollingWidth(value, decimals = 0) {
@@ -45553,6 +46038,7 @@ function RollingSegmentText(props) {
45553
46038
  };
45554
46039
  return (() => {
45555
46040
  var _el$ = createElement("text");
46041
+ setProp(_el$, "wrapMode", "none");
45556
46042
  insert(_el$, label);
45557
46043
  effect((_$p) => setProp(_el$, "style", {
45558
46044
  bg: props.seg.bg,
@@ -45561,7 +46047,71 @@ function RollingSegmentText(props) {
45561
46047
  return _el$;
45562
46048
  })();
45563
46049
  }
46050
+ function fitPowerlineSegments(segments, available, right) {
46051
+ const limit = Math.max(0, Math.floor(available));
46052
+ const measure = (segment) => stringWidth(segment.text) + 2;
46053
+ const stripWidth = (list) => list.reduce((n, segment) => n + measure(segment), 0) + list.length;
46054
+ let kept = [...segments];
46055
+ const topPriority = () => Math.max(...kept.map((segment) => segment.priority ?? 0));
46056
+ const shedOne = (allowed) => {
46057
+ let victim = -1;
46058
+ for (let i = 0;i < kept.length; i++) {
46059
+ const segment = kept[i];
46060
+ if (!allowed(segment))
46061
+ continue;
46062
+ if (victim < 0 || (segment.priority ?? 0) <= (kept[victim].priority ?? 0))
46063
+ victim = i;
46064
+ }
46065
+ if (victim < 0)
46066
+ return false;
46067
+ kept = kept.filter((_, i) => i !== victim);
46068
+ return true;
46069
+ };
46070
+ while (kept.length > 1 && stripWidth(kept) > limit) {
46071
+ const top = topPriority();
46072
+ if (!shedOne((segment) => segment.degrade === undefined && (segment.priority ?? 0) < top))
46073
+ break;
46074
+ }
46075
+ if (stripWidth(kept) > limit) {
46076
+ for (let i = 0;i < kept.length; i++) {
46077
+ const candidate = kept[i];
46078
+ if (candidate.degrade === undefined || candidate.degrade === candidate.text)
46079
+ continue;
46080
+ const degraded = {
46081
+ ...candidate,
46082
+ text: candidate.degrade,
46083
+ roll: undefined
46084
+ };
46085
+ if (measure(degraded) >= measure(candidate))
46086
+ continue;
46087
+ kept = [...kept.slice(0, i), degraded, ...kept.slice(i + 1)];
46088
+ if (stripWidth(kept) <= limit)
46089
+ break;
46090
+ }
46091
+ }
46092
+ while (kept.length > 1 && stripWidth(kept) > limit) {
46093
+ const top = topPriority();
46094
+ if (!shedOne((segment) => (segment.priority ?? 0) < top))
46095
+ break;
46096
+ }
46097
+ if (kept.length === 1 && stripWidth(kept) > limit) {
46098
+ const room = Math.max(0, limit - 3);
46099
+ const only = kept[0];
46100
+ kept = [{
46101
+ ...only,
46102
+ text: clipToWidth(only.text, room),
46103
+ roll: undefined
46104
+ }];
46105
+ }
46106
+ const rightText = right !== undefined && right !== "" && stripWidth(kept) + stringWidth(right) + 1 <= limit ? right : undefined;
46107
+ return {
46108
+ segments: kept,
46109
+ right: rightText
46110
+ };
46111
+ }
45564
46112
  function PowerlineFooter(props) {
46113
+ const dimensions = useTerminalSize();
46114
+ const fitted = createMemo(() => fitPowerlineSegments(props.left, dimensions().width - 1, props.right));
45565
46115
  return (() => {
45566
46116
  var _el$2 = createElement("box");
45567
46117
  setProp(_el$2, "style", {
@@ -45571,10 +46121,10 @@ function PowerlineFooter(props) {
45571
46121
  });
45572
46122
  insert(_el$2, createComponent2(For, {
45573
46123
  get each() {
45574
- return props.left;
46124
+ return fitted().segments;
45575
46125
  },
45576
46126
  children: (seg, i) => {
45577
- const next = () => props.left[i() + 1];
46127
+ const next = () => fitted().segments[i() + 1];
45578
46128
  return [createComponent2(Show, {
45579
46129
  get when() {
45580
46130
  return seg.roll;
@@ -45582,6 +46132,7 @@ function PowerlineFooter(props) {
45582
46132
  get fallback() {
45583
46133
  return (() => {
45584
46134
  var _el$5 = createElement("text");
46135
+ setProp(_el$5, "wrapMode", "none");
45585
46136
  insert(_el$5, () => ` ${seg.text} `);
45586
46137
  effect((_$p) => setProp(_el$5, "style", {
45587
46138
  bg: seg.bg,
@@ -45603,6 +46154,7 @@ function PowerlineFooter(props) {
45603
46154
  return (() => {
45604
46155
  var _el$6 = createElement("text");
45605
46156
  insertNode(_el$6, createTextNode(`\uE0B0`));
46157
+ setProp(_el$6, "wrapMode", "none");
45606
46158
  effect((_$p) => setProp(_el$6, "style", {
45607
46159
  fg: seg.bg
45608
46160
  }, _$p));
@@ -45612,6 +46164,7 @@ function PowerlineFooter(props) {
45612
46164
  children: (n) => (() => {
45613
46165
  var _el$8 = createElement("text");
45614
46166
  insertNode(_el$8, createTextNode(`\uE0B0`));
46167
+ setProp(_el$8, "wrapMode", "none");
45615
46168
  effect((_$p) => setProp(_el$8, "style", {
45616
46169
  fg: seg.bg,
45617
46170
  bg: n().bg
@@ -45623,7 +46176,7 @@ function PowerlineFooter(props) {
45623
46176
  }), null);
45624
46177
  insert(_el$2, createComponent2(Show, {
45625
46178
  get when() {
45626
- return props.right;
46179
+ return fitted().right;
45627
46180
  },
45628
46181
  get children() {
45629
46182
  return [(() => {
@@ -45634,7 +46187,8 @@ function PowerlineFooter(props) {
45634
46187
  return _el$3;
45635
46188
  })(), (() => {
45636
46189
  var _el$4 = createElement("text");
45637
- insert(_el$4, () => props.right);
46190
+ setProp(_el$4, "wrapMode", "none");
46191
+ insert(_el$4, () => fitted().right);
45638
46192
  effect((_$p) => setProp(_el$4, "style", {
45639
46193
  fg: props.theme?.text.base ?? "#e6e6e6"
45640
46194
  }, _$p));
@@ -45676,6 +46230,8 @@ var init_powerline = __esm(() => {
45676
46230
  init_motion();
45677
46231
  init_identity();
45678
46232
  init_tool_summarize();
46233
+ init_string_width();
46234
+ init_terminal_size();
45679
46235
  POWERLINE_COLORS = {
45680
46236
  brand: "#4D6BFE",
45681
46237
  provider: "#6A1B9A",
@@ -46222,7 +46778,7 @@ function createFrameLatch(ms = ACTIVITY_FRAME_DEFER_MS) {
46222
46778
  };
46223
46779
  }
46224
46780
  function WidgetsDock(props) {
46225
- const dimensions = useTerminalDimensions();
46781
+ const dimensions = useTerminalSize();
46226
46782
  const theme = useThemeOptional();
46227
46783
  const fgFor = (tone) => tone === "running" ? theme?.text.feedback.warning.base ?? "#e0af68" : tone === "failed" ? theme?.text.feedback.error.base ?? "#f7768e" : tone === "ok" ? theme?.text.feedback.success.base ?? "#9ece6a" : theme?.text.muted ?? "#9aa5ce";
46228
46784
  const bg = () => theme?.background.base ?? "#000000";
@@ -46425,6 +46981,7 @@ var init_widgets_dock = __esm(() => {
46425
46981
  init_index_bun();
46426
46982
  init_server();
46427
46983
  init_index_bun();
46984
+ init_terminal_size();
46428
46985
  init_tool_summarize();
46429
46986
  init_todo();
46430
46987
  init_string_width();
@@ -46555,7 +47112,7 @@ function UserMessageFade(props) {
46555
47112
  function Transcript(props) {
46556
47113
  const renderer = useRenderer();
46557
47114
  const theme = useThemeOptional();
46558
- const dimensions = useTerminalDimensions();
47115
+ const dimensions = useTerminalSize();
46559
47116
  const frame = () => transcriptFrame({
46560
47117
  focused: props.focused?.() ?? false,
46561
47118
  terminalRows: dimensions().height,
@@ -46789,6 +47346,7 @@ var init_transcript = __esm(() => {
46789
47346
  init_index_bun();
46790
47347
  init_server();
46791
47348
  init_index_bun();
47349
+ init_terminal_size();
46792
47350
  init_seam_rows();
46793
47351
  init_theme3();
46794
47352
  init_motion();
@@ -46871,7 +47429,7 @@ function lastRequestLines(rows, request, width) {
46871
47429
  return out;
46872
47430
  }
46873
47431
  function LastRequestDock(props) {
46874
- const dimensions = useTerminalDimensions();
47432
+ const dimensions = useTerminalSize();
46875
47433
  const theme = useThemeOptional();
46876
47434
  const fgFor = (tone) => tone === "running" ? theme?.text.feedback.warning.base ?? "#e0af68" : theme?.text.muted ?? "#9aa5ce";
46877
47435
  const contentWidth = () => Math.max(16, dimensions().width - 1);
@@ -46914,7 +47472,7 @@ var init_lastrequest_dock = __esm(() => {
46914
47472
  init_index_bun();
46915
47473
  init_index_bun();
46916
47474
  init_server();
46917
- init_index_bun();
47475
+ init_terminal_size();
46918
47476
  init_tool_summarize();
46919
47477
  init_string_width();
46920
47478
  init_theme3();
@@ -46963,7 +47521,7 @@ function noticeAnimating(notice, now = Date.now()) {
46963
47521
  return elapsed >= notice.ttlMs - SKIN_NOTICE_FADE_MS && elapsed < notice.ttlMs;
46964
47522
  }
46965
47523
  function NoticesDock() {
46966
- const dimensions = useTerminalDimensions();
47524
+ const dimensions = useTerminalSize();
46967
47525
  const theme = useThemeOptional();
46968
47526
  const [tick, setTick] = createSignal(0);
46969
47527
  onAnimationTick(() => motionAnimationRunning() && notices().some((notice) => noticeAnimating(notice)) ? motionFrameRate() : undefined, () => setTick((t) => t + 1));
@@ -47042,6 +47600,7 @@ var init_notices_dock = __esm(() => {
47042
47600
  init_index_bun();
47043
47601
  init_server();
47044
47602
  init_index_bun();
47603
+ init_terminal_size();
47045
47604
  init_tool_summarize();
47046
47605
  init_theme3();
47047
47606
  init_motion();
@@ -47115,7 +47674,7 @@ function transcriptHintsText(shown = true, locale = hintsLocale()) {
47115
47674
  return `\u2328 ${body}`;
47116
47675
  }
47117
47676
  function HintsLine(props) {
47118
- const dimensions = useTerminalDimensions();
47677
+ const dimensions = useTerminalSize();
47119
47678
  const theme = useThemeOptional();
47120
47679
  const row = () => clipToWidth(props.pane?.() === "transcript" ? transcriptHintsText(hintsShown()) : hintsText(props.busy, hintsShown(), subagentMarkerViews().some((v) => v.status === "running")), Math.max(8, dimensions().width - 2));
47121
47680
  return createComponent2(Show, {
@@ -47146,7 +47705,7 @@ var init_hints_line = __esm(() => {
47146
47705
  init_index_bun();
47147
47706
  init_index_bun();
47148
47707
  init_server();
47149
- init_index_bun();
47708
+ init_terminal_size();
47150
47709
  init_tool_summarize();
47151
47710
  init_theme3();
47152
47711
  init_subagent_markers();
@@ -48680,6 +49239,9 @@ function persistHints(seam) {
48680
49239
  console.error("[commands] hints persist failed:", error);
48681
49240
  }
48682
49241
  }
49242
+ function seamFailureReason(error) {
49243
+ return String(error instanceof Error ? error.message : error).slice(0, 150);
49244
+ }
48683
49245
  function presetNextRow(rows, currentId) {
48684
49246
  if (rows.length <= 1)
48685
49247
  return;
@@ -48798,8 +49360,12 @@ function coreCommands() {
48798
49360
  },
48799
49361
  {
48800
49362
  name: "/model",
48801
- description: "switch model (bare opens the picker)",
49363
+ description: "switch model (bare opens the picker, then the effort picker)",
48802
49364
  async run(ctx, argText) {
49365
+ const pendingSelectionError = ctx.seam.lastSelectionError?.();
49366
+ if (pendingSelectionError) {
49367
+ ctx.say(`model note: the last staged switch failed \u2014 ${pendingSelectionError}`);
49368
+ }
48803
49369
  const arg = argText.trim();
48804
49370
  if (arg) {
48805
49371
  const [providerID, modelID] = arg.split("/");
@@ -48807,7 +49373,12 @@ function coreCommands() {
48807
49373
  ctx.say(`usage: /model or /model provider/model (got "${arg}")`);
48808
49374
  return;
48809
49375
  }
48810
- await ctx.seam.selectModel(providerID, modelID);
49376
+ try {
49377
+ await ctx.seam.selectModel(providerID, modelID);
49378
+ } catch (error) {
49379
+ ctx.say(`model switch failed \u2014 ${seamFailureReason(error)}`);
49380
+ return;
49381
+ }
48811
49382
  ctx.say(`model \u2192 ${providerID}/${modelID}`);
48812
49383
  ctx.refreshFooter?.();
48813
49384
  return;
@@ -48826,8 +49397,65 @@ function coreCommands() {
48826
49397
  if (!picked)
48827
49398
  return;
48828
49399
  const [providerID, modelID] = picked.split("/");
48829
- await ctx.seam.selectModel(providerID, modelID);
49400
+ const thinking = ctx.seam.thinking;
49401
+ let ladder = [];
49402
+ try {
49403
+ ladder = await thinking?.effortsFor?.(providerID, modelID) ?? [];
49404
+ } catch {
49405
+ ladder = [];
49406
+ }
49407
+ if (ladder.length === 0) {
49408
+ const keptEffort = current?.providerID === providerID ? await thinking?.currentEffort() : undefined;
49409
+ try {
49410
+ await ctx.seam.selectModel(providerID, modelID);
49411
+ } catch (error) {
49412
+ ctx.say(`model switch failed \u2014 ${seamFailureReason(error)}`);
49413
+ return;
49414
+ }
49415
+ ctx.say(`model \u2192 ${picked} (no think levels)`);
49416
+ if (keptEffort !== undefined) {
49417
+ try {
49418
+ await thinking?.selectEffort(keptEffort);
49419
+ } catch (error) {
49420
+ ctx.say(`thinking switch failed \u2014 ${seamFailureReason(error)}`);
49421
+ ctx.refreshFooter?.();
49422
+ return;
49423
+ }
49424
+ ctx.say(`thinking \u2192 ${keptEffort} (next turn)`);
49425
+ }
49426
+ ctx.refreshFooter?.();
49427
+ return;
49428
+ }
49429
+ const effortNow = await thinking?.currentEffort();
49430
+ const effortPicked = await ctx.pickOne(`Select reasoning effort \u2014 ${picked}`, [
49431
+ { title: "(model default)", value: MODEL_DEFAULT_EFFORT_PICK },
49432
+ ...ladder.map((effort) => ({
49433
+ title: effort.name,
49434
+ value: effort.id,
49435
+ description: effort.id === effortNow ? "current" : effort.description
49436
+ }))
49437
+ ]);
49438
+ if (!effortPicked) {
49439
+ ctx.say("model unchanged");
49440
+ return;
49441
+ }
49442
+ const effort = effortPicked === MODEL_DEFAULT_EFFORT_PICK ? undefined : effortPicked;
49443
+ ctx.invalidateFooter?.();
49444
+ try {
49445
+ await ctx.seam.selectModel(providerID, modelID);
49446
+ } catch (error) {
49447
+ ctx.say(`model switch failed \u2014 ${seamFailureReason(error)}`);
49448
+ return;
49449
+ }
48830
49450
  ctx.say(`model \u2192 ${picked}`);
49451
+ try {
49452
+ await thinking?.selectEffort(effort);
49453
+ } catch (error) {
49454
+ ctx.say(`thinking switch failed \u2014 ${seamFailureReason(error)}`);
49455
+ ctx.refreshFooter?.();
49456
+ return;
49457
+ }
49458
+ ctx.say(`thinking \u2192 ${effortPicked === MODEL_DEFAULT_EFFORT_PICK ? "model default" : effortPicked} (next turn)`);
48831
49459
  ctx.refreshFooter?.();
48832
49460
  }
48833
49461
  },
@@ -49032,7 +49660,12 @@ function coreCommands() {
49032
49660
  if (!picked || picked === current)
49033
49661
  return;
49034
49662
  ctx.invalidateFooter?.();
49035
- await thinking.selectEffort(picked);
49663
+ try {
49664
+ await thinking.selectEffort(picked);
49665
+ } catch (error) {
49666
+ ctx.say(`thinking switch failed \u2014 ${seamFailureReason(error)}`);
49667
+ return;
49668
+ }
49036
49669
  ctx.say(`thinking \u2192 ${picked} (next turn)`);
49037
49670
  ctx.refreshFooter?.();
49038
49671
  }
@@ -49238,6 +49871,7 @@ function dispatchLine(commands, line) {
49238
49871
  function unknownCommandRow(name) {
49239
49872
  return `unknown command: ${name} (try /help)`;
49240
49873
  }
49874
+ var MODEL_DEFAULT_EFFORT_PICK = "__model_default__";
49241
49875
  var init_commands = __esm(() => {
49242
49876
  init_hotkeys();
49243
49877
  init_login();
@@ -53275,7 +53909,10 @@ function BtwPanel(props) {
53275
53909
  get fallback() {
53276
53910
  return (() => {
53277
53911
  var _el$0 = createElement("text");
53278
- insert(_el$0, () => run().answer);
53912
+ insert(_el$0, (() => {
53913
+ var _c$2 = memo2(() => run().answer === "");
53914
+ return () => _c$2() ? "(empty answer)" : run().answer;
53915
+ })());
53279
53916
  return _el$0;
53280
53917
  })();
53281
53918
  },
@@ -53722,16 +54359,17 @@ class RemoteSessionSeam {
53722
54359
  }
53723
54360
  async sessionInfo() {
53724
54361
  const base = this.#session.sessionInfo();
53725
- if (base.sessionId === undefined)
54362
+ const sessionId = base.sessionId ?? this.#session.stagedSessionId?.();
54363
+ if (sessionId === undefined)
53726
54364
  return;
53727
54365
  let messageCount = 0;
53728
54366
  try {
53729
- const rows = await this.#session.storedTranscript(base.sessionId);
54367
+ const rows = await this.#session.storedTranscript(sessionId);
53730
54368
  messageCount = rows.filter((row) => row.kind === "user" || row.kind === "assistant").length;
53731
54369
  } catch {}
53732
54370
  return {
53733
54371
  ...base,
53734
- sessionId: base.sessionId,
54372
+ sessionId,
53735
54373
  model: base.model ?? null,
53736
54374
  messageCount,
53737
54375
  contextTokens: base.contextTokens,
@@ -53799,10 +54437,11 @@ class RemoteSessionSeam {
53799
54437
  selectModel(providerID, modelID) {
53800
54438
  return this.#session.selectModel({ provider: providerID, model: modelID }).then(() => {
53801
54439
  return;
53802
- }).catch((error) => {
53803
- console.error("[session-seam-adapter] selectModel failed:", error);
53804
54440
  });
53805
54441
  }
54442
+ lastSelectionError() {
54443
+ return this.#session.lastSelectionError();
54444
+ }
53806
54445
  thinking = {
53807
54446
  efforts: async () => {
53808
54447
  try {
@@ -53824,6 +54463,7 @@ class RemoteSessionSeam {
53824
54463
  return [];
53825
54464
  }
53826
54465
  },
54466
+ effortsFor: (providerID, modelID) => this.#session.modelEfforts(providerID, modelID),
53827
54467
  currentEffort: async () => {
53828
54468
  const selection = await this.#session.currentModelSelection();
53829
54469
  return selection?.reasoningEffort;
@@ -53839,8 +54479,6 @@ class RemoteSessionSeam {
53839
54479
  });
53840
54480
  }).then(() => {
53841
54481
  return;
53842
- }).catch((error) => {
53843
- console.error("[session-seam-adapter] selectEffort failed:", error);
53844
54482
  });
53845
54483
  }
53846
54484
  };
@@ -54593,7 +55231,11 @@ async function bootClientV2(options = {}) {
54593
55231
  shared.bootCallOrder.push("ensureHost");
54594
55232
  const host = await lifecycle.ensureHost({ profile, idleExitSec });
54595
55233
  shared.bootCallOrder.push("connect");
54596
- const connection = new transport.ClientConnection({ authority: host.authority, cookieHeader: host.cookieHeader });
55234
+ const connection = new transport.ClientConnection({
55235
+ authority: host.authority,
55236
+ cookieHeader: host.cookieHeader,
55237
+ diagnostics: () => host.diagnostics()
55238
+ });
54597
55239
  shared.bootCallOrder.push("createSession");
54598
55240
  const session = new rhs.RemoteHostSession({
54599
55241
  connection,