@aiwayds/dsh-opentui 0.9.4 → 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.
@@ -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;
@@ -7057,6 +7271,8 @@ class RemoteHostSession {
7057
7271
  #tail;
7058
7272
  #pluginsCache = [];
7059
7273
  #skillsCache = [];
7274
+ #skillListeners = [];
7275
+ #skillsRefreshedFor;
7060
7276
  #pushListeners = [];
7061
7277
  #coldBootLabelApplied = false;
7062
7278
  #executionMode = "native";
@@ -7080,7 +7296,7 @@ class RemoteHostSession {
7080
7296
  this.#socketFactory = options.socketFactory ?? ((path) => this.#openMuxSocket(path));
7081
7297
  }
7082
7298
  #openMuxSocket(path) {
7083
- return new WS2(`${this.#baseUrl}${path}`, { headers: { cookie: this.#cookieHeader } });
7299
+ return new WS3(`${this.#baseUrl}${path}`, { headers: { cookie: this.#cookieHeader } });
7084
7300
  }
7085
7301
  async start() {
7086
7302
  if (this.#disposed)
@@ -7139,6 +7355,9 @@ class RemoteHostSession {
7139
7355
  currentSessionId() {
7140
7356
  return this.#sessionId;
7141
7357
  }
7358
+ stagedSessionId() {
7359
+ return this.#resumeId;
7360
+ }
7142
7361
  onJournalRecord(listener) {
7143
7362
  this.#journalListeners.push(listener);
7144
7363
  return () => {
@@ -7160,7 +7379,7 @@ class RemoteHostSession {
7160
7379
  this.#contextMeter.notePending(userText);
7161
7380
  await this.start();
7162
7381
  const sessionId = await this.#ensureSession();
7163
- const requestId = randomUUID3();
7382
+ const requestId = randomUUID4();
7164
7383
  const attachmentParts = this.#pendingUploads.map(imagePromptPart);
7165
7384
  this.#pendingUploads = [];
7166
7385
  await this.#rpc("session/prompt", {
@@ -7171,6 +7390,7 @@ class RemoteHostSession {
7171
7390
  content: [{ type: "text", text: userText }, ...attachmentParts]
7172
7391
  }
7173
7392
  });
7393
+ this.#refreshSkillsOnce(sessionId);
7174
7394
  this.#promptInFlight = false;
7175
7395
  if (this.#interrupted || this.#disposed)
7176
7396
  return;
@@ -7188,7 +7408,7 @@ class RemoteHostSession {
7188
7408
  return;
7189
7409
  this.#rpc("session/prompt", {
7190
7410
  request: {
7191
- requestId: randomUUID3(),
7411
+ requestId: randomUUID4(),
7192
7412
  sessionId,
7193
7413
  mode: "steer",
7194
7414
  content: [{ type: "text", text: userText }]
@@ -7536,6 +7756,19 @@ class RemoteHostSession {
7536
7756
  async settingsDocument() {
7537
7757
  return this.#settingsClient().describeDocument();
7538
7758
  }
7759
+ async permissionCatalog() {
7760
+ try {
7761
+ const value = await this.#rpc("permissionPresets/catalog");
7762
+ const options = asPermissionOptions(value.options);
7763
+ const defaultOptions = asPermissionOptions(value.defaultOptions);
7764
+ const defaultPreset = typeof value.defaultPreset === "string" ? value.defaultPreset : "";
7765
+ if (options.length === 0 && defaultOptions.length === 0 && defaultPreset === "")
7766
+ return;
7767
+ return { options, defaultOptions, defaultPreset };
7768
+ } catch {
7769
+ return;
7770
+ }
7771
+ }
7539
7772
  profileName() {
7540
7773
  return this.#profile;
7541
7774
  }
@@ -7699,7 +7932,29 @@ class RemoteHostSession {
7699
7932
  if (sessionId === undefined)
7700
7933
  return [...this.#skillsCache];
7701
7934
  this.#skillsCache = await this.#opsClient().skillsList(sessionId);
7702
- return [...this.#skillsCache];
7935
+ const snapshot = [...this.#skillsCache];
7936
+ for (const listener of [...this.#skillListeners]) {
7937
+ try {
7938
+ listener(snapshot);
7939
+ } catch (error) {
7940
+ console.error("[remote-host-session] skill listener failed:", error);
7941
+ }
7942
+ }
7943
+ return snapshot;
7944
+ }
7945
+ onSkillsChanged(listener) {
7946
+ this.#skillListeners.push(listener);
7947
+ return () => {
7948
+ this.#skillListeners = this.#skillListeners.filter((entry) => entry !== listener);
7949
+ };
7950
+ }
7951
+ #refreshSkillsOnce(sessionId) {
7952
+ if (this.#skillsRefreshedFor === sessionId)
7953
+ return;
7954
+ this.#skillsRefreshedFor = sessionId;
7955
+ this.refreshSkills().catch((error) => {
7956
+ console.error("[remote-host-session] skill catalog refresh failed:", error);
7957
+ });
7703
7958
  }
7704
7959
  async reloadPlugins() {
7705
7960
  if (this.#disposed)
@@ -8008,7 +8263,7 @@ class RemoteHostSession {
8008
8263
  await this.#attachFollow(false);
8009
8264
  return this.#sessionId;
8010
8265
  }
8011
- const requestedId = this.#resumeId ?? randomUUID3();
8266
+ const requestedId = this.#resumeId ?? randomUUID4();
8012
8267
  this.#resumeId = undefined;
8013
8268
  const request = { cwd: this.#cwd, sessionId: requestedId };
8014
8269
  if (this.#presetId !== undefined)
@@ -8447,6 +8702,22 @@ class RemoteHostSession {
8447
8702
  }
8448
8703
  }
8449
8704
  }
8705
+ function asPermissionOptions(value) {
8706
+ if (!Array.isArray(value))
8707
+ return [];
8708
+ return value.flatMap((entry) => {
8709
+ const row = typeof entry === "object" && entry !== null ? entry : {};
8710
+ if (typeof row.value !== "string" || row.value === "")
8711
+ return [];
8712
+ return [
8713
+ {
8714
+ value: row.value,
8715
+ ...typeof row.name === "string" ? { name: row.name } : {},
8716
+ ...typeof row.description === "string" ? { description: row.description } : {}
8717
+ }
8718
+ ];
8719
+ });
8720
+ }
8450
8721
  var REATTACH_RETRY_MS = 1000, REATTACH_MAX_ATTEMPTS = 30, PRESET_ENGLISH_NAMES;
8451
8722
  var init_remote_host_session = __esm(() => {
8452
8723
  init_loop();
@@ -11033,6 +11304,49 @@ var init_index_bun = __esm(() => {
11033
11304
  });
11034
11305
  });
11035
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
+
11036
11350
  // ../tui-base/src/routes/session/composer-state.ts
11037
11351
  class ComposerHistory {
11038
11352
  entries = [];
@@ -11154,6 +11468,17 @@ class ComposerController {
11154
11468
  this.pendingRows = [];
11155
11469
  this.emitPending();
11156
11470
  }
11471
+ flushQueue() {
11472
+ if (this.queueItems.length === 0)
11473
+ return { kind: "empty", started: 0, remaining: 0 };
11474
+ if (this.busyState)
11475
+ return { kind: "busy", started: 0, remaining: this.queueItems.length };
11476
+ const next = this.queueItems.shift();
11477
+ this.dropQueueRow(next.id);
11478
+ this.setQueuedState("queued");
11479
+ this.startTurn(next.text);
11480
+ return { kind: "flushed", started: 1, remaining: this.queueItems.length };
11481
+ }
11157
11482
  get turn() {
11158
11483
  return this.pendingTurn;
11159
11484
  }
@@ -31605,7 +31930,7 @@ var init_hash = __esm(() => {
31605
31930
  // ../tui-base/src/vendor/util/src/flock.ts
31606
31931
  import path2 from "path";
31607
31932
  import os from "os";
31608
- import { randomBytes, randomUUID as randomUUID4 } from "crypto";
31933
+ import { randomBytes, randomUUID as randomUUID5 } from "crypto";
31609
31934
  import { mkdir, readFile as readFile2, rm, stat, utimes, writeFile } from "fs/promises";
31610
31935
  var Flock;
31611
31936
  var init_flock = __esm(() => {
@@ -31695,7 +32020,7 @@ var init_flock = __esm(() => {
31695
32020
  return now - dir.mtimeMs > staleMs;
31696
32021
  }
31697
32022
  async function tryAcquireLockDir(lockDir, opts) {
31698
- const token = randomUUID4?.() ?? randomBytes(16).toString("hex");
32023
+ const token = randomUUID5?.() ?? randomBytes(16).toString("hex");
31699
32024
  const metaPath = path2.join(lockDir, "meta.json");
31700
32025
  const heartbeatPath = path2.join(lockDir, "heartbeat");
31701
32026
  try {
@@ -39148,7 +39473,7 @@ import { measureEditText, RenderableEvents as RenderableEvents2 } from "@opentui
39148
39473
  function SessionComposer(props) {
39149
39474
  const FOOTER_HEIGHT = props.footerHint === false ? 0 : 1;
39150
39475
  const renderer = useRenderer();
39151
- const dimensions = useTerminalDimensions();
39476
+ const dimensions = useTerminalSize();
39152
39477
  const theme = useThemeOptional();
39153
39478
  let configCursorStyle;
39154
39479
  try {
@@ -39413,7 +39738,8 @@ function SessionComposer(props) {
39413
39738
  value.focus();
39414
39739
  },
39415
39740
  node: () => value.isDestroyed ? undefined : value,
39416
- resetDeliveries: () => controller.resetDeliveries()
39741
+ resetDeliveries: () => controller.resetDeliveries(),
39742
+ flushQueue: () => controller.flushQueue()
39417
39743
  });
39418
39744
  }, _el$2);
39419
39745
  setProp(_el$2, "width", "100%");
@@ -39494,6 +39820,7 @@ var init_session_composer = __esm(() => {
39494
39820
  init_index_bun();
39495
39821
  init_server();
39496
39822
  init_index_bun();
39823
+ init_terminal_size();
39497
39824
  init_composer_keybinds();
39498
39825
  init_theme3();
39499
39826
  init_keymap();
@@ -39561,7 +39888,7 @@ function composerContextLabel(input) {
39561
39888
  return truncateLeft(branch ? `${dir} \xB7 ${branch}` : dir, input.maxColumns);
39562
39889
  }
39563
39890
  function ComposerContext(props) {
39564
- const dimensions = useTerminalDimensions();
39891
+ const dimensions = useTerminalSize();
39565
39892
  const theme = useThemeOptional();
39566
39893
  const [branch, setBranch] = createSignal("");
39567
39894
  let seq = 0;
@@ -39619,7 +39946,7 @@ var init_composer_context = __esm(() => {
39619
39946
  init_index_bun();
39620
39947
  init_index_bun();
39621
39948
  init_server();
39622
- init_index_bun();
39949
+ init_terminal_size();
39623
39950
  init_theme3();
39624
39951
  init_path_format();
39625
39952
  init_string_width();
@@ -42586,6 +42913,7 @@ var SESSIONS_MIN_BYTES = 1024, SESSIONS_DIR_CAP = 32;
42586
42913
  // ../tui-base/src/routes/session/auto-resume.ts
42587
42914
  function parseLaunchArgs(argv) {
42588
42915
  let newRequested = false;
42916
+ let resumeLastRequested = false;
42589
42917
  let sessionId;
42590
42918
  for (let index = 0;index < argv.length; index++) {
42591
42919
  const arg = argv[index];
@@ -42595,6 +42923,10 @@ function parseLaunchArgs(argv) {
42595
42923
  newRequested = true;
42596
42924
  continue;
42597
42925
  }
42926
+ if (arg === "--resume-last") {
42927
+ resumeLastRequested = true;
42928
+ continue;
42929
+ }
42598
42930
  if (arg === "--session") {
42599
42931
  const value = argv[index + 1];
42600
42932
  if (value !== undefined && value !== "" && !value.startsWith("--")) {
@@ -42609,10 +42941,17 @@ function parseLaunchArgs(argv) {
42609
42941
  sessionId = value;
42610
42942
  }
42611
42943
  }
42612
- return { newRequested, ...sessionId !== undefined ? { sessionId } : {} };
42944
+ return { newRequested, resumeLastRequested, ...sessionId !== undefined ? { sessionId } : {} };
42613
42945
  }
42614
42946
  function readAutoResumeMode(config) {
42615
- return config?.autoResume === "off" ? "off" : "last";
42947
+ return config?.autoResume === "last" ? "last" : "off";
42948
+ }
42949
+ function resolveAutoResumeMode(config, launch) {
42950
+ if (launch.newRequested || launch.sessionId !== undefined)
42951
+ return "off";
42952
+ if (launch.resumeLastRequested)
42953
+ return "last";
42954
+ return readAutoResumeMode(config);
42616
42955
  }
42617
42956
  function readAutoResumeDays(config, fallback = DEFAULT_AUTO_RESUME_DAYS) {
42618
42957
  const value = Number(config?.autoResumeDays);
@@ -42685,9 +43024,7 @@ async function withBudget(promise, timeoutMs) {
42685
43024
  }
42686
43025
  async function runAutoResume(input, deps) {
42687
43026
  const warn = deps.warn ?? (() => {});
42688
- if (input.launch.newRequested || input.launch.sessionId !== undefined)
42689
- return;
42690
- const mode = readAutoResumeMode(input.config);
43027
+ const mode = resolveAutoResumeMode(input.config, input.launch);
42691
43028
  if (mode !== "last")
42692
43029
  return;
42693
43030
  const timeoutMs = deps.timeoutMs ?? AUTO_RESUME_TIMEOUT_MS;
@@ -45295,7 +45632,8 @@ function brandSegment(theme, presetLabel, mode = "dark") {
45295
45632
  const label = presetLabel ? `dsh(${presetLabel})` : "dsh";
45296
45633
  return {
45297
45634
  text: label,
45298
- bg: brandBlue(mode)
45635
+ bg: brandBlue(mode),
45636
+ priority: 100
45299
45637
  };
45300
45638
  }
45301
45639
  function providerSegment(provider, theme, mode = "dark") {
@@ -45305,11 +45643,13 @@ function providerSegment(provider, theme, mode = "dark") {
45305
45643
  if (!theme)
45306
45644
  return {
45307
45645
  text: label,
45308
- bg: POWERLINE_COLORS.provider
45646
+ bg: POWERLINE_COLORS.provider,
45647
+ priority: 60
45309
45648
  };
45310
45649
  return {
45311
45650
  text: label,
45312
- bg: powerlinePalette(theme, brandBlue(mode)).provider
45651
+ bg: powerlinePalette(theme, brandBlue(mode)).provider,
45652
+ priority: 60
45313
45653
  };
45314
45654
  }
45315
45655
  function effortIcon(effort) {
@@ -45329,7 +45669,8 @@ function modelSegment(model, effort = DEFAULT_EFFORT, theme) {
45329
45669
  const word = effectiveEffort(effort);
45330
45670
  return {
45331
45671
  text: `\uD83E\uDD16 ${clipToWidth(model, 24)} ${effortIcon(word)} ${word}`,
45332
- bg: effortFill(resolvePalette(theme), word)
45672
+ bg: effortFill(resolvePalette(theme), word),
45673
+ priority: 70
45333
45674
  };
45334
45675
  }
45335
45676
  function fmtNum(n) {
@@ -45350,6 +45691,8 @@ function contextSegment(used, window, theme) {
45350
45691
  return {
45351
45692
  text: `\uD83E\uDDE0 ${fmtNum(used)}/${fmtNum(window)}(${percent.toFixed(1)}%)`,
45352
45693
  bg,
45694
+ degrade: `\uD83E\uDDE0 ${fmtNum(used)}`,
45695
+ priority: 90,
45353
45696
  roll: {
45354
45697
  value: percent,
45355
45698
  decimals: 1,
@@ -45365,6 +45708,7 @@ function contextSegment(used, window, theme) {
45365
45708
  return {
45366
45709
  text: `\uD83E\uDDE0 ${fmtNum(used)}`,
45367
45710
  bg: p.contextOk,
45711
+ priority: 90,
45368
45712
  roll: {
45369
45713
  value: used,
45370
45714
  decimals: 0,
@@ -45379,7 +45723,8 @@ function messagesSegment(n, theme) {
45379
45723
  return null;
45380
45724
  return {
45381
45725
  text: `\uD83D\uDCAC ${n} msgs`,
45382
- bg: resolvePalette(theme).messages
45726
+ bg: resolvePalette(theme).messages,
45727
+ priority: 80
45383
45728
  };
45384
45729
  }
45385
45730
  function toolSegment(n, theme) {
@@ -45387,7 +45732,8 @@ function toolSegment(n, theme) {
45387
45732
  return null;
45388
45733
  return {
45389
45734
  text: `\uD83D\uDD27 ${n} tools`,
45390
- bg: resolvePalette(theme).tools
45735
+ bg: resolvePalette(theme).tools,
45736
+ priority: 50
45391
45737
  };
45392
45738
  }
45393
45739
  function speedSegment(tps, theme) {
@@ -45410,6 +45756,7 @@ function elapsedSegment(seconds, theme) {
45410
45756
  return {
45411
45757
  text: `\u23F1 ${Math.round(seconds)}s`,
45412
45758
  bg: theme?.hue.neutral[400] ?? "#616161",
45759
+ priority: 30,
45413
45760
  roll: {
45414
45761
  value: seconds,
45415
45762
  decimals: 0,
@@ -45424,7 +45771,8 @@ function cacheSegment(rate, theme) {
45424
45771
  return null;
45425
45772
  return {
45426
45773
  text: `\u26A1 CH${rate.toFixed(1)}%`,
45427
- bg: resolvePalette(theme).cache
45774
+ bg: resolvePalette(theme).cache,
45775
+ priority: 40
45428
45776
  };
45429
45777
  }
45430
45778
  function rollingWidth(value, decimals = 0) {
@@ -45477,6 +45825,7 @@ function RollingSegmentText(props) {
45477
45825
  };
45478
45826
  return (() => {
45479
45827
  var _el$ = createElement("text");
45828
+ setProp(_el$, "wrapMode", "none");
45480
45829
  insert(_el$, label);
45481
45830
  effect((_$p) => setProp(_el$, "style", {
45482
45831
  bg: props.seg.bg,
@@ -45485,7 +45834,71 @@ function RollingSegmentText(props) {
45485
45834
  return _el$;
45486
45835
  })();
45487
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
+ }
45488
45899
  function PowerlineFooter(props) {
45900
+ const dimensions = useTerminalSize();
45901
+ const fitted = createMemo(() => fitPowerlineSegments(props.left, dimensions().width - 1, props.right));
45489
45902
  return (() => {
45490
45903
  var _el$2 = createElement("box");
45491
45904
  setProp(_el$2, "style", {
@@ -45495,10 +45908,10 @@ function PowerlineFooter(props) {
45495
45908
  });
45496
45909
  insert(_el$2, createComponent2(For, {
45497
45910
  get each() {
45498
- return props.left;
45911
+ return fitted().segments;
45499
45912
  },
45500
45913
  children: (seg, i) => {
45501
- const next = () => props.left[i() + 1];
45914
+ const next = () => fitted().segments[i() + 1];
45502
45915
  return [createComponent2(Show, {
45503
45916
  get when() {
45504
45917
  return seg.roll;
@@ -45506,6 +45919,7 @@ function PowerlineFooter(props) {
45506
45919
  get fallback() {
45507
45920
  return (() => {
45508
45921
  var _el$5 = createElement("text");
45922
+ setProp(_el$5, "wrapMode", "none");
45509
45923
  insert(_el$5, () => ` ${seg.text} `);
45510
45924
  effect((_$p) => setProp(_el$5, "style", {
45511
45925
  bg: seg.bg,
@@ -45527,6 +45941,7 @@ function PowerlineFooter(props) {
45527
45941
  return (() => {
45528
45942
  var _el$6 = createElement("text");
45529
45943
  insertNode(_el$6, createTextNode(`\uE0B0`));
45944
+ setProp(_el$6, "wrapMode", "none");
45530
45945
  effect((_$p) => setProp(_el$6, "style", {
45531
45946
  fg: seg.bg
45532
45947
  }, _$p));
@@ -45536,6 +45951,7 @@ function PowerlineFooter(props) {
45536
45951
  children: (n) => (() => {
45537
45952
  var _el$8 = createElement("text");
45538
45953
  insertNode(_el$8, createTextNode(`\uE0B0`));
45954
+ setProp(_el$8, "wrapMode", "none");
45539
45955
  effect((_$p) => setProp(_el$8, "style", {
45540
45956
  fg: seg.bg,
45541
45957
  bg: n().bg
@@ -45547,7 +45963,7 @@ function PowerlineFooter(props) {
45547
45963
  }), null);
45548
45964
  insert(_el$2, createComponent2(Show, {
45549
45965
  get when() {
45550
- return props.right;
45966
+ return fitted().right;
45551
45967
  },
45552
45968
  get children() {
45553
45969
  return [(() => {
@@ -45558,7 +45974,8 @@ function PowerlineFooter(props) {
45558
45974
  return _el$3;
45559
45975
  })(), (() => {
45560
45976
  var _el$4 = createElement("text");
45561
- insert(_el$4, () => props.right);
45977
+ setProp(_el$4, "wrapMode", "none");
45978
+ insert(_el$4, () => fitted().right);
45562
45979
  effect((_$p) => setProp(_el$4, "style", {
45563
45980
  fg: props.theme?.text.base ?? "#e6e6e6"
45564
45981
  }, _$p));
@@ -45600,6 +46017,8 @@ var init_powerline = __esm(() => {
45600
46017
  init_motion();
45601
46018
  init_identity();
45602
46019
  init_tool_summarize();
46020
+ init_string_width();
46021
+ init_terminal_size();
45603
46022
  POWERLINE_COLORS = {
45604
46023
  brand: "#4D6BFE",
45605
46024
  provider: "#6A1B9A",
@@ -46146,7 +46565,7 @@ function createFrameLatch(ms = ACTIVITY_FRAME_DEFER_MS) {
46146
46565
  };
46147
46566
  }
46148
46567
  function WidgetsDock(props) {
46149
- const dimensions = useTerminalDimensions();
46568
+ const dimensions = useTerminalSize();
46150
46569
  const theme = useThemeOptional();
46151
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";
46152
46571
  const bg = () => theme?.background.base ?? "#000000";
@@ -46349,6 +46768,7 @@ var init_widgets_dock = __esm(() => {
46349
46768
  init_index_bun();
46350
46769
  init_server();
46351
46770
  init_index_bun();
46771
+ init_terminal_size();
46352
46772
  init_tool_summarize();
46353
46773
  init_todo();
46354
46774
  init_string_width();
@@ -46479,7 +46899,7 @@ function UserMessageFade(props) {
46479
46899
  function Transcript(props) {
46480
46900
  const renderer = useRenderer();
46481
46901
  const theme = useThemeOptional();
46482
- const dimensions = useTerminalDimensions();
46902
+ const dimensions = useTerminalSize();
46483
46903
  const frame = () => transcriptFrame({
46484
46904
  focused: props.focused?.() ?? false,
46485
46905
  terminalRows: dimensions().height,
@@ -46713,6 +47133,7 @@ var init_transcript = __esm(() => {
46713
47133
  init_index_bun();
46714
47134
  init_server();
46715
47135
  init_index_bun();
47136
+ init_terminal_size();
46716
47137
  init_seam_rows();
46717
47138
  init_theme3();
46718
47139
  init_motion();
@@ -46795,7 +47216,7 @@ function lastRequestLines(rows, request, width) {
46795
47216
  return out;
46796
47217
  }
46797
47218
  function LastRequestDock(props) {
46798
- const dimensions = useTerminalDimensions();
47219
+ const dimensions = useTerminalSize();
46799
47220
  const theme = useThemeOptional();
46800
47221
  const fgFor = (tone) => tone === "running" ? theme?.text.feedback.warning.base ?? "#e0af68" : theme?.text.muted ?? "#9aa5ce";
46801
47222
  const contentWidth = () => Math.max(16, dimensions().width - 1);
@@ -46838,7 +47259,7 @@ var init_lastrequest_dock = __esm(() => {
46838
47259
  init_index_bun();
46839
47260
  init_index_bun();
46840
47261
  init_server();
46841
- init_index_bun();
47262
+ init_terminal_size();
46842
47263
  init_tool_summarize();
46843
47264
  init_string_width();
46844
47265
  init_theme3();
@@ -46887,7 +47308,7 @@ function noticeAnimating(notice, now = Date.now()) {
46887
47308
  return elapsed >= notice.ttlMs - SKIN_NOTICE_FADE_MS && elapsed < notice.ttlMs;
46888
47309
  }
46889
47310
  function NoticesDock() {
46890
- const dimensions = useTerminalDimensions();
47311
+ const dimensions = useTerminalSize();
46891
47312
  const theme = useThemeOptional();
46892
47313
  const [tick, setTick] = createSignal(0);
46893
47314
  onAnimationTick(() => motionAnimationRunning() && notices().some((notice) => noticeAnimating(notice)) ? motionFrameRate() : undefined, () => setTick((t) => t + 1));
@@ -46966,6 +47387,7 @@ var init_notices_dock = __esm(() => {
46966
47387
  init_index_bun();
46967
47388
  init_server();
46968
47389
  init_index_bun();
47390
+ init_terminal_size();
46969
47391
  init_tool_summarize();
46970
47392
  init_theme3();
46971
47393
  init_motion();
@@ -47039,7 +47461,7 @@ function transcriptHintsText(shown = true, locale = hintsLocale()) {
47039
47461
  return `\u2328 ${body}`;
47040
47462
  }
47041
47463
  function HintsLine(props) {
47042
- const dimensions = useTerminalDimensions();
47464
+ const dimensions = useTerminalSize();
47043
47465
  const theme = useThemeOptional();
47044
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));
47045
47467
  return createComponent2(Show, {
@@ -47070,7 +47492,7 @@ var init_hints_line = __esm(() => {
47070
47492
  init_index_bun();
47071
47493
  init_index_bun();
47072
47494
  init_server();
47073
- init_index_bun();
47495
+ init_terminal_size();
47074
47496
  init_tool_summarize();
47075
47497
  init_theme3();
47076
47498
  init_subagent_markers();
@@ -48826,6 +49248,26 @@ function coreCommands() {
48826
49248
  ctx.say("transcript cleared");
48827
49249
  }
48828
49250
  },
49251
+ {
49252
+ name: "/flush",
49253
+ description: "deliver the queued prompts now",
49254
+ run(ctx) {
49255
+ if (!ctx.flushQueue) {
49256
+ ctx.say("/flush unavailable in this session");
49257
+ return;
49258
+ }
49259
+ const result = ctx.flushQueue();
49260
+ if (result.kind === "empty") {
49261
+ ctx.say("queue is empty \u2014 nothing to flush");
49262
+ return;
49263
+ }
49264
+ if (result.kind === "busy") {
49265
+ ctx.say(`a turn is running \u2014 ${result.remaining} queued prompt(s) wait for it to finish`);
49266
+ return;
49267
+ }
49268
+ ctx.say(`queue flushed \u2014 ${result.started} prompt(s) sending now, ${result.remaining} still queued`);
49269
+ }
49270
+ },
48829
49271
  {
48830
49272
  name: "/btw",
48831
49273
  description: "side question (bare reopens the last answer)",
@@ -49209,7 +49651,8 @@ function buildSlashDeps(base, hooks) {
49209
49651
  openAgents: hooks.openAgents,
49210
49652
  openSettings: hooks.openSettings,
49211
49653
  refreshFooter: hooks.refreshFooter,
49212
- invalidateFooter: hooks.invalidateFooter
49654
+ invalidateFooter: hooks.invalidateFooter,
49655
+ flushQueue: hooks.flushQueue
49213
49656
  };
49214
49657
  }
49215
49658
  function carrySlashHooks(deps) {
@@ -49232,7 +49675,8 @@ var init_slash_deps = __esm(() => {
49232
49675
  "openAgents",
49233
49676
  "openSettings",
49234
49677
  "refreshFooter",
49235
- "invalidateFooter"
49678
+ "invalidateFooter",
49679
+ "flushQueue"
49236
49680
  ];
49237
49681
  });
49238
49682
 
@@ -49669,6 +50113,7 @@ class SlashPaletteController {
49669
50113
  }
49670
50114
  }
49671
50115
  function SlashPalette(props) {
50116
+ const commands = () => typeof props.commands === "function" ? props.commands() : props.commands;
49672
50117
  const theme = useThemeOptional();
49673
50118
  const color = {
49674
50119
  base: () => theme?.text.base ?? "#e6e6e6",
@@ -49688,7 +50133,7 @@ function SlashPalette(props) {
49688
50133
  setProp(_el$, "paddingLeft", 2);
49689
50134
  insert(_el$, createComponent2(For, {
49690
50135
  get each() {
49691
- return props.controller.filtered(props.commands);
50136
+ return props.controller.filtered(commands());
49692
50137
  },
49693
50138
  children: (command, index) => {
49694
50139
  const active = () => props.controller.isRowActive(index());
@@ -49729,7 +50174,7 @@ function SlashPalette(props) {
49729
50174
  }), null);
49730
50175
  insert(_el$, createComponent2(Show, {
49731
50176
  get when() {
49732
- return overflowHint(props.controller.matches(props.commands), props.controller.offset());
50177
+ return overflowHint(props.controller.matches(commands()), props.controller.offset());
49733
50178
  },
49734
50179
  children: (hint) => (() => {
49735
50180
  var _el$6 = createElement("box"), _el$7 = createElement("text");
@@ -49759,7 +50204,8 @@ function SlashPalette(props) {
49759
50204
  });
49760
50205
  }
49761
50206
  function createSlashHost(deps) {
49762
- const commands = deps.commands ?? coreCommands();
50207
+ const fallbackCommands = coreCommands();
50208
+ const commands = () => typeof deps.commands === "function" ? deps.commands() : deps.commands ?? fallbackCommands;
49763
50209
  const usage = createCommandUsage(deps.seam);
49764
50210
  const controller = new SlashPaletteController(usage);
49765
50211
  const ctx = {
@@ -49777,33 +50223,35 @@ function createSlashHost(deps) {
49777
50223
  return true;
49778
50224
  }
49779
50225
  return {
49780
- commands,
50226
+ get commands() {
50227
+ return commands();
50228
+ },
49781
50229
  controller,
49782
50230
  usage,
49783
50231
  slashComplete(buffer, cursor) {
49784
- controller.sync(buffer, commands);
49785
- const selected = controller.open ? controller.current(commands)?.name : undefined;
49786
- return completeSlash(buffer, cursor, commands, selected === undefined ? {} : {
50232
+ controller.sync(buffer, commands());
50233
+ const selected = controller.open ? controller.current(commands())?.name : undefined;
50234
+ return completeSlash(buffer, cursor, commands(), selected === undefined ? {} : {
49787
50235
  selected
49788
50236
  });
49789
50237
  },
49790
50238
  slashKeyFilter(event, buffer) {
49791
- controller.sync(buffer, commands);
50239
+ controller.sync(buffer, commands());
49792
50240
  if (!controller.open)
49793
50241
  return false;
49794
50242
  if (event.name === "up" || event.name === "down") {
49795
50243
  event.preventDefault();
49796
- controller.move(event.name === "up" ? -1 : 1, commands);
50244
+ controller.move(event.name === "up" ? -1 : 1, commands());
49797
50245
  return true;
49798
50246
  }
49799
50247
  if (event.name === "pageup" || event.name === "pagedown") {
49800
50248
  event.preventDefault();
49801
- controller.movePage(event.name === "pageup" ? -1 : 1, commands);
50249
+ controller.movePage(event.name === "pageup" ? -1 : 1, commands());
49802
50250
  return true;
49803
50251
  }
49804
50252
  if (event.name === "home" || event.name === "end") {
49805
50253
  event.preventDefault();
49806
- controller.moveEdge(event.name === "home" ? "home" : "end", commands);
50254
+ controller.moveEdge(event.name === "home" ? "home" : "end", commands());
49807
50255
  return true;
49808
50256
  }
49809
50257
  if (event.name === "escape") {
@@ -49814,11 +50262,11 @@ function createSlashHost(deps) {
49814
50262
  return false;
49815
50263
  },
49816
50264
  interceptSubmit(buffer, apply) {
49817
- controller.sync(buffer, commands);
49818
- const highlighted = controller.current(commands);
50265
+ controller.sync(buffer, commands());
50266
+ const highlighted = controller.current(commands());
49819
50267
  controller.close();
49820
50268
  const needle = buffer.trim().toLowerCase();
49821
- const exact = commands.find((command) => command.name.toLowerCase() === needle);
50269
+ const exact = commands().find((command) => command.name.toLowerCase() === needle);
49822
50270
  if (exact)
49823
50271
  return isSkillCommand(exact) ? false : run(exact, "");
49824
50272
  if (highlighted) {
@@ -49828,7 +50276,7 @@ function createSlashHost(deps) {
49828
50276
  apply?.(`${highlighted.name} `);
49829
50277
  return false;
49830
50278
  }
49831
- const dispatch = dispatchLine(commands, buffer);
50279
+ const dispatch = dispatchLine(commands(), buffer);
49832
50280
  if (dispatch.kind === "command") {
49833
50281
  return isSkillCommand(dispatch.command) ? false : run(dispatch.command, dispatch.argText);
49834
50282
  }
@@ -50448,7 +50896,7 @@ function buildLocalItems(input) {
50448
50896
  }];
50449
50897
  return items;
50450
50898
  }
50451
- function buildHostItems(document, writable) {
50899
+ function buildHostItems(document, writable, catalog) {
50452
50900
  return HOST_SETTINGS_WHITELIST.map((spec) => {
50453
50901
  const row = document?.namespaces.find((candidate) => candidate.ns === spec.ns);
50454
50902
  const item = {
@@ -50481,21 +50929,33 @@ function buildHostItems(document, writable) {
50481
50929
  const raw = valueAtPath(row.value, spec.path);
50482
50930
  const base = valueAtPath(row.base, spec.path);
50483
50931
  const declared = schemaDeclaresPath(row.schema, spec.path);
50484
- if (raw === undefined && base === undefined && !declared)
50932
+ const permissionRow = spec.id === "permission.defaultPreset";
50933
+ const hasCatalog = permissionRow && catalog !== undefined;
50934
+ if (raw === undefined && base === undefined && !declared && !hasCatalog)
50485
50935
  return item;
50486
50936
  item.revision = row.revision;
50487
50937
  const effective = raw ?? base;
50488
- item.value = effective === undefined ? UNKNOWN : typeof effective === "boolean" ? effective ? "on" : "off" : String(effective);
50938
+ item.value = effective === undefined ? hasCatalog && catalog.defaultPreset !== "" ? catalog.defaultPreset : UNKNOWN : typeof effective === "boolean" ? effective ? "on" : "off" : String(effective);
50489
50939
  item.note = undefined;
50490
50940
  item.editable = writable;
50491
50941
  if (spec.kind === "enum") {
50492
50942
  const info = readSchemaField(row.schema, spec.path);
50493
50943
  const derived = spec.id === "permission.defaultPreset" ? presetEnumFromSchema(row.schema) : [];
50494
- const options = info.options !== undefined && info.options.length > 0 ? info.options : derived;
50495
- if (options.length > 0)
50944
+ const schemaOptions = info.options !== undefined && info.options.length > 0 ? info.options : derived;
50945
+ const catalogOptions = hasCatalog ? catalog.defaultOptions.map((option) => option.value) : [];
50946
+ const options = catalogOptions.length > 0 ? catalogOptions : schemaOptions;
50947
+ if (options.length > 0) {
50496
50948
  item.options = options;
50497
- else
50498
- item.note = "schema \u672A\u58F0\u660E\u53EF\u9009\u9879";
50949
+ if (hasCatalog) {
50950
+ item.source = "permissionPresets/catalog \xB7 \u5199\u5165 settings.mutate";
50951
+ if (item.value !== UNKNOWN && item.value !== NA && !options.includes(item.value)) {
50952
+ item.note = `\u5F53\u524D\u503C "${item.value}" \u4E0D\u5728 catalog \u9ED8\u8BA4\u9009\u9879\u4E2D`;
50953
+ }
50954
+ }
50955
+ } else {
50956
+ item.editable = false;
50957
+ item.note = hasCatalog ? "catalog \u672A\u58F0\u660E\u53EF\u9009\u9879 \u2014 \u53EA\u8BFB\u5C55\u793A\u751F\u6548\u503C" : "\u65E0 preset catalog\uFF08permissionPresets/catalog \u4E0D\u53EF\u7528\uFF09\u2014 \u53EA\u8BFB\u5C55\u793A\u751F\u6548\u503C";
50958
+ }
50499
50959
  }
50500
50960
  if (spec.kind === "number") {
50501
50961
  const info = readSchemaField(row.schema, spec.path);
@@ -51079,6 +51539,7 @@ function SettingsPanel(props) {
51079
51539
  const [open, setOpen] = useSettingsPanelOpenState();
51080
51540
  const [document, setDocument] = createSignal(undefined);
51081
51541
  const [describeError, setDescribeError] = createSignal(undefined);
51542
+ const [permissionCatalog, setPermissionCatalog] = createSignal(undefined);
51082
51543
  const [merged, setMerged] = createSignal({});
51083
51544
  const [profile, setProfile] = createSignal({});
51084
51545
  const [workspace, setWorkspace] = createSignal({});
@@ -51118,7 +51579,7 @@ function SettingsPanel(props) {
51118
51579
  themeNames: safeThemeNames()
51119
51580
  } : {},
51120
51581
  writable: writable().local
51121
- }), ...buildHostItems(document(), writable().host), ...buildOtherItems(document())]);
51582
+ }), ...buildHostItems(document(), writable().host, permissionCatalog()), ...buildOtherItems(document())]);
51122
51583
  const visible = createMemo(() => filterSettingsItems(items(), filter()));
51123
51584
  const active = createMemo(() => visible()[cursor()]);
51124
51585
  function safeThemeNames() {
@@ -51150,6 +51611,7 @@ function SettingsPanel(props) {
51150
51611
  if (face === undefined) {
51151
51612
  setDocument(undefined);
51152
51613
  setDescribeError(undefined);
51614
+ setPermissionCatalog(undefined);
51153
51615
  return;
51154
51616
  }
51155
51617
  try {
@@ -51158,6 +51620,11 @@ function SettingsPanel(props) {
51158
51620
  } catch (error) {
51159
51621
  setDescribeError(error instanceof Error ? error.message : String(error));
51160
51622
  }
51623
+ try {
51624
+ setPermissionCatalog(await face.permissionCatalog?.());
51625
+ } catch {
51626
+ setPermissionCatalog(undefined);
51627
+ }
51161
51628
  }
51162
51629
  function close() {
51163
51630
  unsettings?.();
@@ -53601,16 +54068,17 @@ class RemoteSessionSeam {
53601
54068
  }
53602
54069
  async sessionInfo() {
53603
54070
  const base = this.#session.sessionInfo();
53604
- if (base.sessionId === undefined)
54071
+ const sessionId = base.sessionId ?? this.#session.stagedSessionId?.();
54072
+ if (sessionId === undefined)
53605
54073
  return;
53606
54074
  let messageCount = 0;
53607
54075
  try {
53608
- const rows = await this.#session.storedTranscript(base.sessionId);
54076
+ const rows = await this.#session.storedTranscript(sessionId);
53609
54077
  messageCount = rows.filter((row) => row.kind === "user" || row.kind === "assistant").length;
53610
54078
  } catch {}
53611
54079
  return {
53612
54080
  ...base,
53613
- sessionId: base.sessionId,
54081
+ sessionId,
53614
54082
  model: base.model ?? null,
53615
54083
  messageCount,
53616
54084
  contextTokens: base.contextTokens,
@@ -53733,6 +54201,12 @@ class RemoteSessionSeam {
53733
54201
  this.#pluginsRevision[0]();
53734
54202
  return this.#session.listPlugins();
53735
54203
  }
54204
+ async refreshSkills() {
54205
+ return this.#session.refreshSkills();
54206
+ }
54207
+ onSkillsChanged(listener) {
54208
+ return this.#session.onSkillsChanged(listener);
54209
+ }
53736
54210
  preset = {
53737
54211
  list: () => this.#session.listPresets(),
53738
54212
  currentId: async () => this.#session.resolveCurrentPresetId(),
@@ -53782,7 +54256,8 @@ class RemoteSessionSeam {
53782
54256
  identity: () => ({
53783
54257
  profile: this.#session.profileName(),
53784
54258
  dshHome: this.#session.homeDir()
53785
- })
54259
+ }),
54260
+ permissionCatalog: () => this.#session.permissionCatalog()
53786
54261
  };
53787
54262
  login = {
53788
54263
  credentialStatus: (ref) => this.#session.credentialStatus(ref),
@@ -53989,6 +54464,12 @@ function V2SessionPage(props) {
53989
54464
  const [now, setNow] = createSignal(new Date);
53990
54465
  const [contextRevision, setContextRevision] = createSignal(0);
53991
54466
  const [presetLabel, setPresetLabel] = createSignal();
54467
+ const [skillRows, setSkillRows] = createSignal(props.skills ?? []);
54468
+ const slashCommands = createMemo(() => withSkillCommands(coreCommands(), skillRows()));
54469
+ onMount(() => {
54470
+ const off = seam.onSkillsChanged?.((rows) => setSkillRows(rows.map((row) => ({ name: row.name, description: row.description, path: "skills/list" }))));
54471
+ onCleanup(() => off?.());
54472
+ });
53992
54473
  const refreshPresetLabel = () => {
53993
54474
  const face = seam.preset;
53994
54475
  if (!face)
@@ -54213,7 +54694,7 @@ function V2SessionPage(props) {
54213
54694
  };
54214
54695
  const slash = createSlashHost(buildSlashDeps({
54215
54696
  seam,
54216
- commands: withSkillCommands(coreCommands(), props.skills ?? []),
54697
+ commands: slashCommands,
54217
54698
  say: sayLine,
54218
54699
  clear: () => {
54219
54700
  projection.hydrate([]);
@@ -54223,6 +54704,7 @@ function V2SessionPage(props) {
54223
54704
  setTools(0);
54224
54705
  refreshFooterData();
54225
54706
  resetSkinLineFades();
54707
+ setSkillRows(props.skills ?? []);
54226
54708
  setContextRevision((n) => n + 1);
54227
54709
  },
54228
54710
  reload: (sessionId) => {
@@ -54235,6 +54717,7 @@ function V2SessionPage(props) {
54235
54717
  seam.currentModelSelection().then(setModel);
54236
54718
  refreshFooterData();
54237
54719
  refreshPresetLabel();
54720
+ setSkillRows(props.skills ?? []);
54238
54721
  setContextRevision((n) => n + 1);
54239
54722
  return settled;
54240
54723
  },
@@ -54251,7 +54734,8 @@ function V2SessionPage(props) {
54251
54734
  invalidateFooter: () => {
54252
54735
  footerRefreshSeq++;
54253
54736
  },
54254
- themes: themeFace
54737
+ themes: themeFace,
54738
+ flushQueue: () => composerRef?.flushQueue() ?? { kind: "empty", started: 0, remaining: 0 }
54255
54739
  }));
54256
54740
  const overlayHost = createComponent2(TurnOverlayHost, {
54257
54741
  controller: overlays,
@@ -54382,7 +54866,7 @@ function V2SessionPage(props) {
54382
54866
  slashSync: (buffer) => slash.controller.sync(buffer, slash.commands),
54383
54867
  interceptSubmit: slash.interceptSubmit,
54384
54868
  slashComplete: (buffer, cursor) => dialog.stack.length > 0 ? undefined : slash.slashComplete(buffer, cursor),
54385
- slashPalette: () => createComponent2(SlashPalette, { controller: slash.controller, commands: slash.commands }),
54869
+ slashPalette: () => createComponent2(SlashPalette, { controller: slash.controller, commands: () => slash.commands }),
54386
54870
  slashHeight: () => slash.controller.rows()
54387
54871
  })
54388
54872
  ];
@@ -54456,7 +54940,11 @@ async function bootClientV2(options = {}) {
54456
54940
  shared.bootCallOrder.push("ensureHost");
54457
54941
  const host = await lifecycle.ensureHost({ profile, idleExitSec });
54458
54942
  shared.bootCallOrder.push("connect");
54459
- 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
+ });
54460
54948
  shared.bootCallOrder.push("createSession");
54461
54949
  const session = new rhs.RemoteHostSession({
54462
54950
  connection,