@aiwayds/dsh-opentui 0.9.5 → 0.9.6

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,24 @@ 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.6] - 2026-11-11
9
+
10
+ ### Added
11
+
12
+ - **Test tiers** — `test:unit|ft|ui|e2e|all` with a geometry×scene UI matrix and a real-client e2e flow suite (fake model).
13
+
14
+ ### Changed
15
+
16
+ - **Session restore remains opt-in** (`--resume-last` / `autoResume: "last"`); startup defaults to a fresh session.
17
+
18
+ ### Fixed
19
+
20
+ - **Footer no longer wraps on narrow terminals** — segments are dropped by priority and the context segment degrades instead of truncating mid-number.
21
+ - **Tool dock lines are clipped inside the activity frame.**
22
+ - **Message count is restored after `--resume-last`.**
23
+ - **Single shared terminal-size listener** — no more MaxListeners warnings.
24
+ - **Connection hardening** — stale host locks are detected by an HTTP probe and replaced (never killing foreign processes); readiness waits for HTTP + `$events` instead of a bound TCP port; first-connect retries are capped at 3 with the host stderr tail surfaced.
25
+
8
26
  ## [0.9.5] - 2026-11-11
9
27
 
10
28
  ### Added
package/README.md CHANGED
@@ -210,7 +210,7 @@ PATH; otherwise the scripts self-skip (exit 0) so CI runs green.
210
210
 
211
211
  ## Status
212
212
 
213
- v0.9.5: published as `@aiwayds/dsh-opentui` — client-only distribution
213
+ v0.9.6: published as `@aiwayds/dsh-opentui` — client-only distribution
214
214
  (npm bin → client chain; the in-process plugin mode was retired). New
215
215
  default theme dsh-blue (dark/light, auto-selected from terminal background,
216
216
  `/theme` to pin) with focus visuals, framed composer/messages/code blocks,
@@ -228,4 +228,10 @@ launch, a compact footer context percent, and a fix for transcript loss on
228
228
  `/resume`. 0.9.5 adds `/flush` for a paused delivery queue, closes the
229
229
  settings permission-preset and skill-catalog gaps, and makes session restore
230
230
  opt-in (`--resume-last` or `autoResume: "last"`) so a plain launch starts
231
- fresh. Roadmap: platform + Kit polish.
231
+ fresh. 0.9.6 adds tiered tests (`test:unit|ft|ui|e2e|all` with a geometry×
232
+ scene UI matrix and a real-client e2e flow suite), hardens first-connect
233
+ (stale host locks are probed over HTTP and replaced, readiness waits for
234
+ HTTP + `$events`, retries capped at 3 with the host stderr tail surfaced),
235
+ and fixes footer wrapping on narrow terminals, tool-dock clipping, the
236
+ message count after `--resume-last`, and duplicate terminal-size listeners.
237
+ Roadmap: platform + Kit polish.
@@ -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,12 @@ 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";
6066
6280
  async function askBtw(options) {
6067
6281
  const timeoutMs = options.timeoutMs ?? 120000;
6068
6282
  let sessionId = options.previousSessionId ?? "";
6069
6283
  if (!sessionId) {
6070
- const requested = randomUUID();
6284
+ const requested = randomUUID2();
6071
6285
  const value = await options.rpc("session/create", { request: { cwd: options.cwd, sessionId: requested } });
6072
6286
  sessionId = typeof value.sessionId === "string" ? value.sessionId : requested;
6073
6287
  if (options.stagedModel) {
@@ -6141,7 +6355,7 @@ ${options.snapshot.join(`
6141
6355
  ` : "";
6142
6356
  options.rpc("session/prompt", {
6143
6357
  request: {
6144
- requestId: randomUUID(),
6358
+ requestId: randomUUID2(),
6145
6359
  sessionId,
6146
6360
  mode: "queue",
6147
6361
  content: [{ type: "text", text: `${snap}Side question (answer in one or two sentences, do not use tools): ${options.question}` }]
@@ -6404,7 +6618,7 @@ var init_subagent_policy = __esm(() => {
6404
6618
  });
6405
6619
 
6406
6620
  // src/client/remote-subagents.ts
6407
- import { randomUUID as randomUUID2 } from "crypto";
6621
+ import { randomUUID as randomUUID3 } from "crypto";
6408
6622
 
6409
6623
  class RemoteSubagentPanel {
6410
6624
  #options;
@@ -6557,7 +6771,7 @@ class RemoteSubagentPanel {
6557
6771
  try {
6558
6772
  await this.#options.rpc("subagents/prompt", {
6559
6773
  request: {
6560
- requestId: randomUUID2(),
6774
+ requestId: randomUUID3(),
6561
6775
  parentSessionId: parent,
6562
6776
  childSessionId: id,
6563
6777
  mode: "continuable",
@@ -6582,7 +6796,7 @@ class RemoteSubagentPanel {
6582
6796
  try {
6583
6797
  await this.#options.rpc("subagents/prompt", {
6584
6798
  request: {
6585
- requestId: randomUUID2(),
6799
+ requestId: randomUUID3(),
6586
6800
  parentSessionId: parent,
6587
6801
  childSessionId: id,
6588
6802
  mode: "continuable",
@@ -6980,10 +7194,10 @@ __export(exports_remote_host_session, {
6980
7194
  RemoteHostSession: () => RemoteHostSession,
6981
7195
  openRemoteStream: () => openRemoteStream
6982
7196
  });
6983
- import { randomUUID as randomUUID3 } from "crypto";
7197
+ import { randomUUID as randomUUID4 } from "crypto";
6984
7198
  import { existsSync as existsSync7, mkdirSync as mkdirSync4, readFileSync as readFileSync7, renameSync as renameSync5, rmSync as rmSync4, writeFileSync as writeFileSync6 } from "fs";
6985
7199
  import { join as joinPath } from "path";
6986
- import WS2 from "ws";
7200
+ import WS3 from "ws";
6987
7201
  function trace(message) {
6988
7202
  if (!process.env.DSH_OPENTUI_DEBUG)
6989
7203
  return;
@@ -7082,7 +7296,7 @@ class RemoteHostSession {
7082
7296
  this.#socketFactory = options.socketFactory ?? ((path) => this.#openMuxSocket(path));
7083
7297
  }
7084
7298
  #openMuxSocket(path) {
7085
- return new WS2(`${this.#baseUrl}${path}`, { headers: { cookie: this.#cookieHeader } });
7299
+ return new WS3(`${this.#baseUrl}${path}`, { headers: { cookie: this.#cookieHeader } });
7086
7300
  }
7087
7301
  async start() {
7088
7302
  if (this.#disposed)
@@ -7141,6 +7355,9 @@ class RemoteHostSession {
7141
7355
  currentSessionId() {
7142
7356
  return this.#sessionId;
7143
7357
  }
7358
+ stagedSessionId() {
7359
+ return this.#resumeId;
7360
+ }
7144
7361
  onJournalRecord(listener) {
7145
7362
  this.#journalListeners.push(listener);
7146
7363
  return () => {
@@ -7162,7 +7379,7 @@ class RemoteHostSession {
7162
7379
  this.#contextMeter.notePending(userText);
7163
7380
  await this.start();
7164
7381
  const sessionId = await this.#ensureSession();
7165
- const requestId = randomUUID3();
7382
+ const requestId = randomUUID4();
7166
7383
  const attachmentParts = this.#pendingUploads.map(imagePromptPart);
7167
7384
  this.#pendingUploads = [];
7168
7385
  await this.#rpc("session/prompt", {
@@ -7191,7 +7408,7 @@ class RemoteHostSession {
7191
7408
  return;
7192
7409
  this.#rpc("session/prompt", {
7193
7410
  request: {
7194
- requestId: randomUUID3(),
7411
+ requestId: randomUUID4(),
7195
7412
  sessionId,
7196
7413
  mode: "steer",
7197
7414
  content: [{ type: "text", text: userText }]
@@ -8046,7 +8263,7 @@ class RemoteHostSession {
8046
8263
  await this.#attachFollow(false);
8047
8264
  return this.#sessionId;
8048
8265
  }
8049
- const requestedId = this.#resumeId ?? randomUUID3();
8266
+ const requestedId = this.#resumeId ?? randomUUID4();
8050
8267
  this.#resumeId = undefined;
8051
8268
  const request = { cwd: this.#cwd, sessionId: requestedId };
8052
8269
  if (this.#presetId !== undefined)
@@ -11087,6 +11304,49 @@ var init_index_bun = __esm(() => {
11087
11304
  });
11088
11305
  });
11089
11306
 
11307
+ // ../tui-base/src/routes/session/terminal-size.ts
11308
+ function entryFor(renderer) {
11309
+ let entry = registry2.get(renderer);
11310
+ if (!entry) {
11311
+ const [size, setSize] = createSignal({ width: renderer.width, height: renderer.height });
11312
+ const created = {
11313
+ size,
11314
+ setSize,
11315
+ onResize: (width, height) => setSize({ width, height }),
11316
+ refs: 0,
11317
+ attached: false
11318
+ };
11319
+ registry2.set(renderer, created);
11320
+ entry = created;
11321
+ }
11322
+ return entry;
11323
+ }
11324
+ function useTerminalSize() {
11325
+ const renderer = useRenderer();
11326
+ const entry = entryFor(renderer);
11327
+ onMount(() => {
11328
+ entry.refs++;
11329
+ if (!entry.attached) {
11330
+ renderer.on("resize", entry.onResize);
11331
+ entry.attached = true;
11332
+ }
11333
+ });
11334
+ onCleanup(() => {
11335
+ entry.refs = Math.max(0, entry.refs - 1);
11336
+ if (entry.refs === 0 && entry.attached) {
11337
+ renderer.off("resize", entry.onResize);
11338
+ entry.attached = false;
11339
+ }
11340
+ });
11341
+ return entry.size;
11342
+ }
11343
+ var registry2;
11344
+ var init_terminal_size = __esm(() => {
11345
+ init_server();
11346
+ init_index_bun();
11347
+ registry2 = new WeakMap;
11348
+ });
11349
+
11090
11350
  // ../tui-base/src/routes/session/composer-state.ts
11091
11351
  class ComposerHistory {
11092
11352
  entries = [];
@@ -31670,7 +31930,7 @@ var init_hash = __esm(() => {
31670
31930
  // ../tui-base/src/vendor/util/src/flock.ts
31671
31931
  import path2 from "path";
31672
31932
  import os from "os";
31673
- import { randomBytes, randomUUID as randomUUID4 } from "crypto";
31933
+ import { randomBytes, randomUUID as randomUUID5 } from "crypto";
31674
31934
  import { mkdir, readFile as readFile2, rm, stat, utimes, writeFile } from "fs/promises";
31675
31935
  var Flock;
31676
31936
  var init_flock = __esm(() => {
@@ -31760,7 +32020,7 @@ var init_flock = __esm(() => {
31760
32020
  return now - dir.mtimeMs > staleMs;
31761
32021
  }
31762
32022
  async function tryAcquireLockDir(lockDir, opts) {
31763
- const token = randomUUID4?.() ?? randomBytes(16).toString("hex");
32023
+ const token = randomUUID5?.() ?? randomBytes(16).toString("hex");
31764
32024
  const metaPath = path2.join(lockDir, "meta.json");
31765
32025
  const heartbeatPath = path2.join(lockDir, "heartbeat");
31766
32026
  try {
@@ -39213,7 +39473,7 @@ import { measureEditText, RenderableEvents as RenderableEvents2 } from "@opentui
39213
39473
  function SessionComposer(props) {
39214
39474
  const FOOTER_HEIGHT = props.footerHint === false ? 0 : 1;
39215
39475
  const renderer = useRenderer();
39216
- const dimensions = useTerminalDimensions();
39476
+ const dimensions = useTerminalSize();
39217
39477
  const theme = useThemeOptional();
39218
39478
  let configCursorStyle;
39219
39479
  try {
@@ -39560,6 +39820,7 @@ var init_session_composer = __esm(() => {
39560
39820
  init_index_bun();
39561
39821
  init_server();
39562
39822
  init_index_bun();
39823
+ init_terminal_size();
39563
39824
  init_composer_keybinds();
39564
39825
  init_theme3();
39565
39826
  init_keymap();
@@ -39627,7 +39888,7 @@ function composerContextLabel(input) {
39627
39888
  return truncateLeft(branch ? `${dir} \xB7 ${branch}` : dir, input.maxColumns);
39628
39889
  }
39629
39890
  function ComposerContext(props) {
39630
- const dimensions = useTerminalDimensions();
39891
+ const dimensions = useTerminalSize();
39631
39892
  const theme = useThemeOptional();
39632
39893
  const [branch, setBranch] = createSignal("");
39633
39894
  let seq = 0;
@@ -39685,7 +39946,7 @@ var init_composer_context = __esm(() => {
39685
39946
  init_index_bun();
39686
39947
  init_index_bun();
39687
39948
  init_server();
39688
- init_index_bun();
39949
+ init_terminal_size();
39689
39950
  init_theme3();
39690
39951
  init_path_format();
39691
39952
  init_string_width();
@@ -45371,7 +45632,8 @@ function brandSegment(theme, presetLabel, mode = "dark") {
45371
45632
  const label = presetLabel ? `dsh(${presetLabel})` : "dsh";
45372
45633
  return {
45373
45634
  text: label,
45374
- bg: brandBlue(mode)
45635
+ bg: brandBlue(mode),
45636
+ priority: 100
45375
45637
  };
45376
45638
  }
45377
45639
  function providerSegment(provider, theme, mode = "dark") {
@@ -45381,11 +45643,13 @@ function providerSegment(provider, theme, mode = "dark") {
45381
45643
  if (!theme)
45382
45644
  return {
45383
45645
  text: label,
45384
- bg: POWERLINE_COLORS.provider
45646
+ bg: POWERLINE_COLORS.provider,
45647
+ priority: 60
45385
45648
  };
45386
45649
  return {
45387
45650
  text: label,
45388
- bg: powerlinePalette(theme, brandBlue(mode)).provider
45651
+ bg: powerlinePalette(theme, brandBlue(mode)).provider,
45652
+ priority: 60
45389
45653
  };
45390
45654
  }
45391
45655
  function effortIcon(effort) {
@@ -45405,7 +45669,8 @@ function modelSegment(model, effort = DEFAULT_EFFORT, theme) {
45405
45669
  const word = effectiveEffort(effort);
45406
45670
  return {
45407
45671
  text: `\uD83E\uDD16 ${clipToWidth(model, 24)} ${effortIcon(word)} ${word}`,
45408
- bg: effortFill(resolvePalette(theme), word)
45672
+ bg: effortFill(resolvePalette(theme), word),
45673
+ priority: 70
45409
45674
  };
45410
45675
  }
45411
45676
  function fmtNum(n) {
@@ -45426,6 +45691,8 @@ function contextSegment(used, window, theme) {
45426
45691
  return {
45427
45692
  text: `\uD83E\uDDE0 ${fmtNum(used)}/${fmtNum(window)}(${percent.toFixed(1)}%)`,
45428
45693
  bg,
45694
+ degrade: `\uD83E\uDDE0 ${fmtNum(used)}`,
45695
+ priority: 90,
45429
45696
  roll: {
45430
45697
  value: percent,
45431
45698
  decimals: 1,
@@ -45441,6 +45708,7 @@ function contextSegment(used, window, theme) {
45441
45708
  return {
45442
45709
  text: `\uD83E\uDDE0 ${fmtNum(used)}`,
45443
45710
  bg: p.contextOk,
45711
+ priority: 90,
45444
45712
  roll: {
45445
45713
  value: used,
45446
45714
  decimals: 0,
@@ -45455,7 +45723,8 @@ function messagesSegment(n, theme) {
45455
45723
  return null;
45456
45724
  return {
45457
45725
  text: `\uD83D\uDCAC ${n} msgs`,
45458
- bg: resolvePalette(theme).messages
45726
+ bg: resolvePalette(theme).messages,
45727
+ priority: 80
45459
45728
  };
45460
45729
  }
45461
45730
  function toolSegment(n, theme) {
@@ -45463,7 +45732,8 @@ function toolSegment(n, theme) {
45463
45732
  return null;
45464
45733
  return {
45465
45734
  text: `\uD83D\uDD27 ${n} tools`,
45466
- bg: resolvePalette(theme).tools
45735
+ bg: resolvePalette(theme).tools,
45736
+ priority: 50
45467
45737
  };
45468
45738
  }
45469
45739
  function speedSegment(tps, theme) {
@@ -45486,6 +45756,7 @@ function elapsedSegment(seconds, theme) {
45486
45756
  return {
45487
45757
  text: `\u23F1 ${Math.round(seconds)}s`,
45488
45758
  bg: theme?.hue.neutral[400] ?? "#616161",
45759
+ priority: 30,
45489
45760
  roll: {
45490
45761
  value: seconds,
45491
45762
  decimals: 0,
@@ -45500,7 +45771,8 @@ function cacheSegment(rate, theme) {
45500
45771
  return null;
45501
45772
  return {
45502
45773
  text: `\u26A1 CH${rate.toFixed(1)}%`,
45503
- bg: resolvePalette(theme).cache
45774
+ bg: resolvePalette(theme).cache,
45775
+ priority: 40
45504
45776
  };
45505
45777
  }
45506
45778
  function rollingWidth(value, decimals = 0) {
@@ -45553,6 +45825,7 @@ function RollingSegmentText(props) {
45553
45825
  };
45554
45826
  return (() => {
45555
45827
  var _el$ = createElement("text");
45828
+ setProp(_el$, "wrapMode", "none");
45556
45829
  insert(_el$, label);
45557
45830
  effect((_$p) => setProp(_el$, "style", {
45558
45831
  bg: props.seg.bg,
@@ -45561,7 +45834,71 @@ function RollingSegmentText(props) {
45561
45834
  return _el$;
45562
45835
  })();
45563
45836
  }
45837
+ function fitPowerlineSegments(segments, available, right) {
45838
+ const limit = Math.max(0, Math.floor(available));
45839
+ const measure = (segment) => stringWidth(segment.text) + 2;
45840
+ const stripWidth = (list) => list.reduce((n, segment) => n + measure(segment), 0) + list.length;
45841
+ let kept = [...segments];
45842
+ const topPriority = () => Math.max(...kept.map((segment) => segment.priority ?? 0));
45843
+ const shedOne = (allowed) => {
45844
+ let victim = -1;
45845
+ for (let i = 0;i < kept.length; i++) {
45846
+ const segment = kept[i];
45847
+ if (!allowed(segment))
45848
+ continue;
45849
+ if (victim < 0 || (segment.priority ?? 0) <= (kept[victim].priority ?? 0))
45850
+ victim = i;
45851
+ }
45852
+ if (victim < 0)
45853
+ return false;
45854
+ kept = kept.filter((_, i) => i !== victim);
45855
+ return true;
45856
+ };
45857
+ while (kept.length > 1 && stripWidth(kept) > limit) {
45858
+ const top = topPriority();
45859
+ if (!shedOne((segment) => segment.degrade === undefined && (segment.priority ?? 0) < top))
45860
+ break;
45861
+ }
45862
+ if (stripWidth(kept) > limit) {
45863
+ for (let i = 0;i < kept.length; i++) {
45864
+ const candidate = kept[i];
45865
+ if (candidate.degrade === undefined || candidate.degrade === candidate.text)
45866
+ continue;
45867
+ const degraded = {
45868
+ ...candidate,
45869
+ text: candidate.degrade,
45870
+ roll: undefined
45871
+ };
45872
+ if (measure(degraded) >= measure(candidate))
45873
+ continue;
45874
+ kept = [...kept.slice(0, i), degraded, ...kept.slice(i + 1)];
45875
+ if (stripWidth(kept) <= limit)
45876
+ break;
45877
+ }
45878
+ }
45879
+ while (kept.length > 1 && stripWidth(kept) > limit) {
45880
+ const top = topPriority();
45881
+ if (!shedOne((segment) => (segment.priority ?? 0) < top))
45882
+ break;
45883
+ }
45884
+ if (kept.length === 1 && stripWidth(kept) > limit) {
45885
+ const room = Math.max(0, limit - 3);
45886
+ const only = kept[0];
45887
+ kept = [{
45888
+ ...only,
45889
+ text: clipToWidth(only.text, room),
45890
+ roll: undefined
45891
+ }];
45892
+ }
45893
+ const rightText = right !== undefined && right !== "" && stripWidth(kept) + stringWidth(right) + 1 <= limit ? right : undefined;
45894
+ return {
45895
+ segments: kept,
45896
+ right: rightText
45897
+ };
45898
+ }
45564
45899
  function PowerlineFooter(props) {
45900
+ const dimensions = useTerminalSize();
45901
+ const fitted = createMemo(() => fitPowerlineSegments(props.left, dimensions().width - 1, props.right));
45565
45902
  return (() => {
45566
45903
  var _el$2 = createElement("box");
45567
45904
  setProp(_el$2, "style", {
@@ -45571,10 +45908,10 @@ function PowerlineFooter(props) {
45571
45908
  });
45572
45909
  insert(_el$2, createComponent2(For, {
45573
45910
  get each() {
45574
- return props.left;
45911
+ return fitted().segments;
45575
45912
  },
45576
45913
  children: (seg, i) => {
45577
- const next = () => props.left[i() + 1];
45914
+ const next = () => fitted().segments[i() + 1];
45578
45915
  return [createComponent2(Show, {
45579
45916
  get when() {
45580
45917
  return seg.roll;
@@ -45582,6 +45919,7 @@ function PowerlineFooter(props) {
45582
45919
  get fallback() {
45583
45920
  return (() => {
45584
45921
  var _el$5 = createElement("text");
45922
+ setProp(_el$5, "wrapMode", "none");
45585
45923
  insert(_el$5, () => ` ${seg.text} `);
45586
45924
  effect((_$p) => setProp(_el$5, "style", {
45587
45925
  bg: seg.bg,
@@ -45603,6 +45941,7 @@ function PowerlineFooter(props) {
45603
45941
  return (() => {
45604
45942
  var _el$6 = createElement("text");
45605
45943
  insertNode(_el$6, createTextNode(`\uE0B0`));
45944
+ setProp(_el$6, "wrapMode", "none");
45606
45945
  effect((_$p) => setProp(_el$6, "style", {
45607
45946
  fg: seg.bg
45608
45947
  }, _$p));
@@ -45612,6 +45951,7 @@ function PowerlineFooter(props) {
45612
45951
  children: (n) => (() => {
45613
45952
  var _el$8 = createElement("text");
45614
45953
  insertNode(_el$8, createTextNode(`\uE0B0`));
45954
+ setProp(_el$8, "wrapMode", "none");
45615
45955
  effect((_$p) => setProp(_el$8, "style", {
45616
45956
  fg: seg.bg,
45617
45957
  bg: n().bg
@@ -45623,7 +45963,7 @@ function PowerlineFooter(props) {
45623
45963
  }), null);
45624
45964
  insert(_el$2, createComponent2(Show, {
45625
45965
  get when() {
45626
- return props.right;
45966
+ return fitted().right;
45627
45967
  },
45628
45968
  get children() {
45629
45969
  return [(() => {
@@ -45634,7 +45974,8 @@ function PowerlineFooter(props) {
45634
45974
  return _el$3;
45635
45975
  })(), (() => {
45636
45976
  var _el$4 = createElement("text");
45637
- insert(_el$4, () => props.right);
45977
+ setProp(_el$4, "wrapMode", "none");
45978
+ insert(_el$4, () => fitted().right);
45638
45979
  effect((_$p) => setProp(_el$4, "style", {
45639
45980
  fg: props.theme?.text.base ?? "#e6e6e6"
45640
45981
  }, _$p));
@@ -45676,6 +46017,8 @@ var init_powerline = __esm(() => {
45676
46017
  init_motion();
45677
46018
  init_identity();
45678
46019
  init_tool_summarize();
46020
+ init_string_width();
46021
+ init_terminal_size();
45679
46022
  POWERLINE_COLORS = {
45680
46023
  brand: "#4D6BFE",
45681
46024
  provider: "#6A1B9A",
@@ -46222,7 +46565,7 @@ function createFrameLatch(ms = ACTIVITY_FRAME_DEFER_MS) {
46222
46565
  };
46223
46566
  }
46224
46567
  function WidgetsDock(props) {
46225
- const dimensions = useTerminalDimensions();
46568
+ const dimensions = useTerminalSize();
46226
46569
  const theme = useThemeOptional();
46227
46570
  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
46571
  const bg = () => theme?.background.base ?? "#000000";
@@ -46425,6 +46768,7 @@ var init_widgets_dock = __esm(() => {
46425
46768
  init_index_bun();
46426
46769
  init_server();
46427
46770
  init_index_bun();
46771
+ init_terminal_size();
46428
46772
  init_tool_summarize();
46429
46773
  init_todo();
46430
46774
  init_string_width();
@@ -46555,7 +46899,7 @@ function UserMessageFade(props) {
46555
46899
  function Transcript(props) {
46556
46900
  const renderer = useRenderer();
46557
46901
  const theme = useThemeOptional();
46558
- const dimensions = useTerminalDimensions();
46902
+ const dimensions = useTerminalSize();
46559
46903
  const frame = () => transcriptFrame({
46560
46904
  focused: props.focused?.() ?? false,
46561
46905
  terminalRows: dimensions().height,
@@ -46789,6 +47133,7 @@ var init_transcript = __esm(() => {
46789
47133
  init_index_bun();
46790
47134
  init_server();
46791
47135
  init_index_bun();
47136
+ init_terminal_size();
46792
47137
  init_seam_rows();
46793
47138
  init_theme3();
46794
47139
  init_motion();
@@ -46871,7 +47216,7 @@ function lastRequestLines(rows, request, width) {
46871
47216
  return out;
46872
47217
  }
46873
47218
  function LastRequestDock(props) {
46874
- const dimensions = useTerminalDimensions();
47219
+ const dimensions = useTerminalSize();
46875
47220
  const theme = useThemeOptional();
46876
47221
  const fgFor = (tone) => tone === "running" ? theme?.text.feedback.warning.base ?? "#e0af68" : theme?.text.muted ?? "#9aa5ce";
46877
47222
  const contentWidth = () => Math.max(16, dimensions().width - 1);
@@ -46914,7 +47259,7 @@ var init_lastrequest_dock = __esm(() => {
46914
47259
  init_index_bun();
46915
47260
  init_index_bun();
46916
47261
  init_server();
46917
- init_index_bun();
47262
+ init_terminal_size();
46918
47263
  init_tool_summarize();
46919
47264
  init_string_width();
46920
47265
  init_theme3();
@@ -46963,7 +47308,7 @@ function noticeAnimating(notice, now = Date.now()) {
46963
47308
  return elapsed >= notice.ttlMs - SKIN_NOTICE_FADE_MS && elapsed < notice.ttlMs;
46964
47309
  }
46965
47310
  function NoticesDock() {
46966
- const dimensions = useTerminalDimensions();
47311
+ const dimensions = useTerminalSize();
46967
47312
  const theme = useThemeOptional();
46968
47313
  const [tick, setTick] = createSignal(0);
46969
47314
  onAnimationTick(() => motionAnimationRunning() && notices().some((notice) => noticeAnimating(notice)) ? motionFrameRate() : undefined, () => setTick((t) => t + 1));
@@ -47042,6 +47387,7 @@ var init_notices_dock = __esm(() => {
47042
47387
  init_index_bun();
47043
47388
  init_server();
47044
47389
  init_index_bun();
47390
+ init_terminal_size();
47045
47391
  init_tool_summarize();
47046
47392
  init_theme3();
47047
47393
  init_motion();
@@ -47115,7 +47461,7 @@ function transcriptHintsText(shown = true, locale = hintsLocale()) {
47115
47461
  return `\u2328 ${body}`;
47116
47462
  }
47117
47463
  function HintsLine(props) {
47118
- const dimensions = useTerminalDimensions();
47464
+ const dimensions = useTerminalSize();
47119
47465
  const theme = useThemeOptional();
47120
47466
  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
47467
  return createComponent2(Show, {
@@ -47146,7 +47492,7 @@ var init_hints_line = __esm(() => {
47146
47492
  init_index_bun();
47147
47493
  init_index_bun();
47148
47494
  init_server();
47149
- init_index_bun();
47495
+ init_terminal_size();
47150
47496
  init_tool_summarize();
47151
47497
  init_theme3();
47152
47498
  init_subagent_markers();
@@ -53722,16 +54068,17 @@ class RemoteSessionSeam {
53722
54068
  }
53723
54069
  async sessionInfo() {
53724
54070
  const base = this.#session.sessionInfo();
53725
- if (base.sessionId === undefined)
54071
+ const sessionId = base.sessionId ?? this.#session.stagedSessionId?.();
54072
+ if (sessionId === undefined)
53726
54073
  return;
53727
54074
  let messageCount = 0;
53728
54075
  try {
53729
- const rows = await this.#session.storedTranscript(base.sessionId);
54076
+ const rows = await this.#session.storedTranscript(sessionId);
53730
54077
  messageCount = rows.filter((row) => row.kind === "user" || row.kind === "assistant").length;
53731
54078
  } catch {}
53732
54079
  return {
53733
54080
  ...base,
53734
- sessionId: base.sessionId,
54081
+ sessionId,
53735
54082
  model: base.model ?? null,
53736
54083
  messageCount,
53737
54084
  contextTokens: base.contextTokens,
@@ -54593,7 +54940,11 @@ async function bootClientV2(options = {}) {
54593
54940
  shared.bootCallOrder.push("ensureHost");
54594
54941
  const host = await lifecycle.ensureHost({ profile, idleExitSec });
54595
54942
  shared.bootCallOrder.push("connect");
54596
- const connection = new transport.ClientConnection({ authority: host.authority, cookieHeader: host.cookieHeader });
54943
+ const connection = new transport.ClientConnection({
54944
+ authority: host.authority,
54945
+ cookieHeader: host.cookieHeader,
54946
+ diagnostics: () => host.diagnostics()
54947
+ });
54597
54948
  shared.bootCallOrder.push("createSession");
54598
54949
  const session = new rhs.RemoteHostSession({
54599
54950
  connection,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aiwayds/dsh-opentui",
3
- "version": "0.9.5",
3
+ "version": "0.9.6",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "bin": {