@aiwayds/dsh-opentui 0.23.3 → 0.24.0

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.
@@ -687,6 +687,19 @@ var init_safe_kill = __esm(() => {
687
687
  import { createHash, createHmac } from "crypto";
688
688
  import { readFileSync as readFileSync2, statSync } from "fs";
689
689
  import { join as join2 } from "path";
690
+ function resolveRetryWindow(option) {
691
+ if (option !== undefined && Number.isFinite(option) && option > 0)
692
+ return option;
693
+ const env = Number(process.env[RETRY_WINDOW_ENV]);
694
+ if (Number.isFinite(env) && env > 0)
695
+ return env;
696
+ return DEFAULT_RETRY_WINDOW_MS;
697
+ }
698
+ function resolveRetryInterval(option) {
699
+ if (option !== undefined && Number.isFinite(option) && option > 0)
700
+ return option;
701
+ return DEFAULT_RETRY_INTERVAL_MS;
702
+ }
690
703
  function ownerCookieName(authority) {
691
704
  return "dsh-auth-" + base64url(createHash("sha256").update(authority).digest());
692
705
  }
@@ -695,7 +708,7 @@ function mintOwnerCookie(options) {
695
708
  if (typeof authority !== "string" || authority.length === 0 || /[\r\n/]/.test(authority)) {
696
709
  throw new OwnerCookieError("authority must be a non-empty host:port without scheme or path separators");
697
710
  }
698
- const secret = readGrantSecret(options.home);
711
+ const secret = readGrantSecret(options.home, resolveRetryWindow(options.timeoutMs), resolveRetryInterval(options.retryIntervalMs));
699
712
  const issuedAt = Date.now();
700
713
  const maxAgeMs = options.maxAgeMs ?? DEFAULT_MAX_AGE_MS;
701
714
  const expiresAt = issuedAt + Math.min(maxAgeMs, DEFAULT_MAX_AGE_MS);
@@ -703,9 +716,9 @@ function mintOwnerCookie(options) {
703
716
  const signature = base64url(createHmac("sha256", secret).update(body).digest());
704
717
  return `${ownerCookieName(authority)}=v1.${body}.${signature}`;
705
718
  }
706
- function readGrantSecret(home) {
719
+ function readGrantSecret(home, timeoutMs, retryIntervalMs) {
707
720
  const path = join2(home, ".credentials.yaml");
708
- const deadline = Date.now() + RETRY_WINDOW_MS;
721
+ const deadline = Date.now() + timeoutMs;
709
722
  let sawFile = false;
710
723
  while (true) {
711
724
  let file = "";
@@ -725,11 +738,11 @@ function readGrantSecret(home) {
725
738
  }
726
739
  if (Date.now() >= deadline) {
727
740
  if (!sawFile) {
728
- throw new CredentialsFileMissingError(`no credentials file at ${path} within ${RETRY_WINDOW_MS}ms (host first boot still pending?)`);
741
+ throw new CredentialsFileMissingError(`no credentials file at ${path} within ${timeoutMs}ms (host first boot still pending?)`);
729
742
  }
730
- throw new CredentialsGrantMissingError(`credentials record "${RECORD_KEY}" absent in ${path} within ${RETRY_WINDOW_MS}ms (host first boot still pending?)`);
743
+ throw new CredentialsGrantMissingError(`credentials record "${RECORD_KEY}" absent in ${path} within ${timeoutMs}ms (host first boot still pending?)`);
731
744
  }
732
- sleepSync(RETRY_INTERVAL_MS);
745
+ sleepSync(retryIntervalMs);
733
746
  }
734
747
  }
735
748
  function assertOwnerOnly(path) {
@@ -898,7 +911,7 @@ function sleepSync(ms) {
898
911
  while (Date.now() < until) {}
899
912
  }
900
913
  }
901
- var RECORD_KEY = "client-connection/browser-session", DEFAULT_MAX_AGE_MS, RETRY_INTERVAL_MS = 100, RETRY_WINDOW_MS = 2000, SECRET_PATTERN, OwnerCookieError, CredentialsFileMissingError, CredentialsGrantMissingError, CredentialsGrantInvalidError, CredentialsFileInsecureError, CredentialsParseError;
914
+ var RECORD_KEY = "client-connection/browser-session", DEFAULT_MAX_AGE_MS, DEFAULT_RETRY_INTERVAL_MS = 100, DEFAULT_RETRY_WINDOW_MS = 30000, RETRY_WINDOW_ENV = "DSH_OPENTUI_COOKIE_MINT_TIMEOUT_MS", SECRET_PATTERN, OwnerCookieError, CredentialsFileMissingError, CredentialsGrantMissingError, CredentialsGrantInvalidError, CredentialsFileInsecureError, CredentialsParseError;
902
915
  var init_cookie_mint = __esm(() => {
903
916
  DEFAULT_MAX_AGE_MS = 30 * 86400000;
904
917
  SECRET_PATTERN = /^[A-Za-z0-9_-]{43}$/;
@@ -41579,6 +41592,134 @@ var init_interactivity = __esm(() => {
41579
41592
  Context4 = createContext(() => true);
41580
41593
  });
41581
41594
 
41595
+ // ../tui-base/src/context/input-ownership.tsx
41596
+ function InputOwnershipProvider(props) {
41597
+ const page = {
41598
+ id: Symbol("page"),
41599
+ kind: "page"
41600
+ };
41601
+ const [stack, setStack] = createSignal([page]);
41602
+ const top = () => stack().at(-1) ?? page;
41603
+ const value = {
41604
+ top,
41605
+ pageFrame: () => page,
41606
+ push(kind) {
41607
+ const frame = {
41608
+ id: Symbol(kind),
41609
+ kind
41610
+ };
41611
+ setStack((items) => [...items, frame]);
41612
+ return frame;
41613
+ },
41614
+ pop(frame) {
41615
+ if (!frame || frame === page)
41616
+ return;
41617
+ setStack((items) => items.some((item) => item.id === frame.id) ? items.filter((item) => item.id !== frame.id) : items);
41618
+ },
41619
+ owns(frame) {
41620
+ return frame !== undefined && top().id === frame.id;
41621
+ }
41622
+ };
41623
+ return createComponent2(Context5.Provider, {
41624
+ value,
41625
+ get children() {
41626
+ return props.children;
41627
+ }
41628
+ });
41629
+ }
41630
+ function useInputOwnership() {
41631
+ const value = useContext(Context5);
41632
+ if (!value)
41633
+ throw new Error("InputOwnership.Provider is missing");
41634
+ return value;
41635
+ }
41636
+ function useInputOwnershipOptional() {
41637
+ return useContext(Context5);
41638
+ }
41639
+ function useIsPageOwner() {
41640
+ const ownership = useInputOwnershipOptional();
41641
+ return () => ownership === undefined || ownership.owns(ownership.pageFrame());
41642
+ }
41643
+ var Context5;
41644
+ var init_input_ownership = __esm(() => {
41645
+ init_index_bun();
41646
+ init_server();
41647
+ Context5 = createContext(undefined);
41648
+ });
41649
+
41650
+ // ../tui-base/src/context/focus-router.tsx
41651
+ function tierOfFrame(frame) {
41652
+ if (!frame)
41653
+ return;
41654
+ switch (frame.kind) {
41655
+ case "dialog":
41656
+ return "modal";
41657
+ case "panel":
41658
+ case "dock":
41659
+ return "overlay";
41660
+ case "page":
41661
+ return "main";
41662
+ }
41663
+ }
41664
+ function resolveCapture(top, tier, frame) {
41665
+ if (!top)
41666
+ return false;
41667
+ if (tier === "main" || tier === "global")
41668
+ return top.kind === "page";
41669
+ const tierMatches = tierOfFrame(top) === tier;
41670
+ if (!tierMatches)
41671
+ return false;
41672
+ return frame === undefined || top.id === frame.id;
41673
+ }
41674
+ function createFocusRouter(ownership) {
41675
+ const top = ownership.top;
41676
+ return {
41677
+ top,
41678
+ topTier: () => tierOfFrame(top()),
41679
+ allows(tier, frame) {
41680
+ return resolveCapture(top(), tier, frame);
41681
+ },
41682
+ ownership
41683
+ };
41684
+ }
41685
+ function useFocusRouterOptional() {
41686
+ return useContext(Context6);
41687
+ }
41688
+ function useIsPageOwner2() {
41689
+ const router = useFocusRouterOptional();
41690
+ if (router)
41691
+ return () => router.allows("main");
41692
+ const ownership = useInputOwnershipOptional();
41693
+ return () => ownership === undefined || ownership.owns(ownership.pageFrame());
41694
+ }
41695
+ function Scope2(props) {
41696
+ const router = createFocusRouter(useInputOwnership());
41697
+ return createComponent2(Context6.Provider, {
41698
+ value: router,
41699
+ get children() {
41700
+ return props.children;
41701
+ }
41702
+ });
41703
+ }
41704
+ function FocusRouterProvider(props) {
41705
+ return createComponent2(InputOwnershipProvider, {
41706
+ get children() {
41707
+ return createComponent2(Scope2, {
41708
+ get children() {
41709
+ return props.children;
41710
+ }
41711
+ });
41712
+ }
41713
+ });
41714
+ }
41715
+ var Context6;
41716
+ var init_focus_router = __esm(() => {
41717
+ init_index_bun();
41718
+ init_server();
41719
+ init_input_ownership();
41720
+ Context6 = createContext(undefined);
41721
+ });
41722
+
41582
41723
  // ../tui-base/src/context/keymap.tsx
41583
41724
  import { InputRenderable as InputRenderable4, TextareaRenderable as TextareaRenderable3 } from "@opentui/core";
41584
41725
  function Provider(props) {
@@ -41634,7 +41775,7 @@ function Provider(props) {
41634
41775
  return createComponent2(KeymapProvider, {
41635
41776
  keymap,
41636
41777
  get children() {
41637
- return createComponent2(Context5.Provider, {
41778
+ return createComponent2(Context7.Provider, {
41638
41779
  value: {
41639
41780
  keymap,
41640
41781
  config,
@@ -41672,6 +41813,7 @@ function use2() {
41672
41813
  function createLayer(input) {
41673
41814
  const value = useValue();
41674
41815
  const enabled = useInteractivity();
41816
+ const focus = useFocusRouterOptional();
41675
41817
  const stable = new Map;
41676
41818
  useBindings(() => {
41677
41819
  const layer = input();
@@ -41679,12 +41821,20 @@ function createLayer(input) {
41679
41821
  commands,
41680
41822
  bindings,
41681
41823
  mode,
41824
+ capture,
41825
+ captureFrame,
41682
41826
  ...options
41683
41827
  } = layer;
41684
41828
  const grouped = groupCommands(commands);
41829
+ const resolvedEnabled = focus && capture !== undefined ? () => {
41830
+ const base = typeof options.enabled === "function" ? options.enabled() : options.enabled === undefined ? true : options.enabled;
41831
+ if (!base)
41832
+ return false;
41833
+ return focus.allows(capture, captureFrame?.());
41834
+ } : options.enabled;
41685
41835
  return {
41686
41836
  ...options,
41687
- enabled: enabled() ? options.enabled : false,
41837
+ enabled: enabled() ? resolvedEnabled : false,
41688
41838
  ...mode === "global" ? {} : {
41689
41839
  mode: mode ?? MODE.base
41690
41840
  },
@@ -41908,13 +42058,13 @@ function useState() {
41908
42058
  };
41909
42059
  }
41910
42060
  function useValue() {
41911
- const value = useContext(Context5);
42061
+ const value = useContext(Context7);
41912
42062
  if (!value)
41913
42063
  throw new Error("Keymap.Provider is missing");
41914
42064
  return value;
41915
42065
  }
41916
42066
  function useOptional() {
41917
- return useContext(Context5) ? use2() : undefined;
42067
+ return useContext(Context7) ? use2() : undefined;
41918
42068
  }
41919
42069
  function createMode(keymap) {
41920
42070
  const [stack, setStack] = createSignal([]);
@@ -41971,7 +42121,7 @@ function formatOptions(config) {
41971
42121
  }
41972
42122
  };
41973
42123
  }
41974
- var MODE, Context5, Keymap2;
42124
+ var MODE, Context7, Keymap2;
41975
42125
  var init_keymap = __esm(() => {
41976
42126
  init_index_bun();
41977
42127
  init_src2();
@@ -41984,11 +42134,12 @@ var init_keymap = __esm(() => {
41984
42134
  init_config();
41985
42135
  init_keybind();
41986
42136
  init_interactivity();
42137
+ init_focus_router();
41987
42138
  MODE = {
41988
42139
  key: "opencode.mode",
41989
42140
  base: "base"
41990
42141
  };
41991
- Context5 = createContext();
42142
+ Context7 = createContext();
41992
42143
  Keymap2 = {
41993
42144
  Provider,
41994
42145
  use: use2,
@@ -43577,55 +43728,6 @@ var require_fuzzysort = __commonJS(function(exports, module) {
43577
43728
  });
43578
43729
  });
43579
43730
 
43580
- // ../tui-base/src/context/input-ownership.tsx
43581
- function InputOwnershipProvider(props) {
43582
- const page = {
43583
- id: Symbol("page"),
43584
- kind: "page"
43585
- };
43586
- const [stack, setStack] = createSignal([page]);
43587
- const top = () => stack().at(-1) ?? page;
43588
- const value = {
43589
- top,
43590
- pageFrame: () => page,
43591
- push(kind) {
43592
- const frame = {
43593
- id: Symbol(kind),
43594
- kind
43595
- };
43596
- setStack((items) => [...items, frame]);
43597
- return frame;
43598
- },
43599
- pop(frame) {
43600
- if (!frame || frame === page)
43601
- return;
43602
- setStack((items) => items.some((item) => item.id === frame.id) ? items.filter((item) => item.id !== frame.id) : items);
43603
- },
43604
- owns(frame) {
43605
- return frame !== undefined && top().id === frame.id;
43606
- }
43607
- };
43608
- return createComponent2(Context6.Provider, {
43609
- value,
43610
- get children() {
43611
- return props.children;
43612
- }
43613
- });
43614
- }
43615
- function useInputOwnershipOptional() {
43616
- return useContext(Context6);
43617
- }
43618
- function useIsPageOwner() {
43619
- const ownership = useInputOwnershipOptional();
43620
- return () => ownership === undefined || ownership.owns(ownership.pageFrame());
43621
- }
43622
- var Context6;
43623
- var init_input_ownership = __esm(() => {
43624
- init_index_bun();
43625
- init_server();
43626
- Context6 = createContext(undefined);
43627
- });
43628
-
43629
43731
  // ../tui-base/src/ui/border.ts
43630
43732
  var EmptyBorder, SplitBorder;
43631
43733
  var init_border = __esm(() => {
@@ -44275,6 +44377,8 @@ function init2() {
44275
44377
  }
44276
44378
  Keymap2.createLayer(() => ({
44277
44379
  mode: "modal",
44380
+ capture: "modal",
44381
+ captureFrame: () => store.stack.at(-1)?.frame,
44278
44382
  enabled: store.stack.length > 0 && (ownership === undefined || ownership.owns(store.stack.at(-1)?.frame)),
44279
44383
  commands: [{
44280
44384
  bind: "escape",
@@ -47557,12 +47661,6 @@ function subagentHardStopGlyph(view) {
47557
47661
  return "\u23FB!";
47558
47662
  return view.hardStopRound !== undefined ? "\u23FB" : "";
47559
47663
  }
47560
- function foldSubagentMarkerViews(views) {
47561
- setSubagentViews(views);
47562
- }
47563
- function registerSubagentSteer(fn) {
47564
- steerImpl = fn;
47565
- }
47566
47664
  function steerSubagent(id, text) {
47567
47665
  return steerImpl?.(id, text);
47568
47666
  }
@@ -52180,6 +52278,7 @@ function TranscriptScrollKeys(props) {
52180
52278
  };
52181
52279
  Keymap2.createLayer(() => ({
52182
52280
  mode: "global",
52281
+ capture: "main",
52183
52282
  enabled: props.enabled(),
52184
52283
  commands: [{
52185
52284
  id: "session.page.up",
@@ -52208,6 +52307,7 @@ function TranscriptScrollKeys(props) {
52208
52307
  scroll.scrollTo(Infinity);
52209
52308
  };
52210
52309
  Keymap2.createLayer(() => ({
52310
+ capture: "main",
52211
52311
  enabled: () => props.enabled() && renderer.currentFocusedEditor === null,
52212
52312
  commands: [{
52213
52313
  id: "session.first",
@@ -52312,6 +52412,7 @@ function PaneFocusKeys(props) {
52312
52412
  Keymap2.createLayer(() => ({
52313
52413
  mode: "global",
52314
52414
  priority: 1,
52415
+ capture: "main",
52315
52416
  enabled: paneToggleEnabled({
52316
52417
  pane: props.pane(),
52317
52418
  keysEnabled: props.keysEnabled(),
@@ -52332,6 +52433,7 @@ function PaneFocusKeys(props) {
52332
52433
  Keymap2.createLayer(() => ({
52333
52434
  mode: "global",
52334
52435
  priority: 1,
52436
+ capture: "main",
52335
52437
  enabled: transcriptKeysEnabled({
52336
52438
  pane: props.pane(),
52337
52439
  keysEnabled: props.keysEnabled()
@@ -52748,7 +52850,7 @@ function DockProvider(props) {
52748
52850
  }
52749
52851
  setQueue([]);
52750
52852
  });
52751
- return createComponent2(Context7.Provider, {
52853
+ return createComponent2(Context8.Provider, {
52752
52854
  value: api,
52753
52855
  get children() {
52754
52856
  return props.children;
@@ -52756,7 +52858,7 @@ function DockProvider(props) {
52756
52858
  });
52757
52859
  }
52758
52860
  function useDock() {
52759
- const value = useContext(Context7);
52861
+ const value = useContext(Context8);
52760
52862
  if (!value)
52761
52863
  throw new Error("Dock.Provider is missing");
52762
52864
  return value;
@@ -52887,7 +52989,7 @@ function DockSeat(props) {
52887
52989
  return _el$;
52888
52990
  })();
52889
52991
  }
52890
- var DOCK_MAX_ROWS_RATIO = 0.6, Context7, ordinal2 = 0;
52992
+ var DOCK_MAX_ROWS_RATIO = 0.6, Context8, ordinal2 = 0;
52891
52993
  var init_dock_host = __esm(() => {
52892
52994
  init_index_bun();
52893
52995
  init_index_bun();
@@ -52902,7 +53004,7 @@ var init_dock_host = __esm(() => {
52902
53004
  init_input_ownership();
52903
53005
  init_theme3();
52904
53006
  init_terminal_size();
52905
- Context7 = createContext(undefined);
53007
+ Context8 = createContext(undefined);
52906
53008
  });
52907
53009
 
52908
53010
  // ../tui-base/src/routes/session/ask-panel.tsx
@@ -54054,6 +54156,7 @@ function TurnCancelKeys(props) {
54054
54156
  onCleanup(() => cancel.dispose());
54055
54157
  Keymap2.createLayer(() => ({
54056
54158
  mode: "global",
54159
+ capture: "main",
54057
54160
  enabled: props.enabled(),
54058
54161
  commands: [{
54059
54162
  bind: "escape",
@@ -55466,10 +55569,6 @@ function coreCommands() {
55466
55569
  name: "/agents",
55467
55570
  description: t("command.agents.description"),
55468
55571
  run(ctx, argText) {
55469
- if (!ctx.seam.agents) {
55470
- ctx.say(t("command.agents.unavailable"));
55471
- return;
55472
- }
55473
55572
  if (!ctx.openAgents) {
55474
55573
  ctx.say(t("command.agents.panelNotMounted"));
55475
55574
  return;
@@ -62222,6 +62321,7 @@ function AgentsPanel(props) {
62222
62321
  const ownTop = layers().at(-1)?.handle;
62223
62322
  return {
62224
62323
  mode: "global",
62324
+ capture: "overlay",
62225
62325
  enabled: open() && ownTop?.ownsInput() === true,
62226
62326
  priority: 2,
62227
62327
  commands: [
@@ -64029,7 +64129,7 @@ var init_subagents_viewer = __esm(() => {
64029
64129
  import { TextAttributes as TextAttributes12 } from "@opentui/core";
64030
64130
  function resolveVersion() {
64031
64131
  try {
64032
- return "0.23.3";
64132
+ return "0.24.0";
64033
64133
  } catch {
64034
64134
  return "dev";
64035
64135
  }
@@ -65782,6 +65882,7 @@ function createTuiPanelKeymapHost(keymap) {
65782
65882
  return Keymap2.createLayer(() => {
65783
65883
  const layer = input();
65784
65884
  return {
65885
+ capture: "overlay",
65785
65886
  ...layer.mode === undefined ? {} : {
65786
65887
  mode: layer.mode
65787
65888
  },
@@ -65880,440 +65981,15 @@ var init_jsx_dev_runtime = __esm(() => {
65880
65981
  init_jsx_runtime();
65881
65982
  });
65882
65983
 
65883
- // src/client/session-seam-adapter.ts
65884
- var exports_session_seam_adapter = {};
65885
- __export(exports_session_seam_adapter, {
65886
- NOTICE_SOURCE_KINDS: () => NOTICE_SOURCE_KINDS,
65887
- RemoteSessionSeam: () => RemoteSessionSeam,
65888
- projectJournalRecord: () => projectJournalRecord
65889
- });
65890
-
65891
- class RemoteSessionSeam {
65892
- #session;
65893
- #listeners = [];
65894
- #turnInFlight = false;
65895
- #unjournal;
65896
- #pluginsRevision = createSignal(0);
65897
- #unplugins;
65898
- #pluginsPushListeners = [];
65899
- constructor(session) {
65900
- this.#session = session;
65901
- registerSubagentSteer((id, text) => this.#session.steerChild(id, text));
65902
- this.#unplugins = session.onPluginsChanged?.(() => {
65903
- this.#pluginsRevision[1]((n) => n + 1);
65904
- for (const listener of this.#pluginsPushListeners) {
65905
- try {
65906
- listener();
65907
- } catch {}
65908
- }
65909
- }) ?? undefined;
65910
- }
65911
- status() {
65912
- const s = this.#session.status;
65913
- return { connection: s.connection, turn: s.turn, sessionAttached: s.sessionAttached };
65914
- }
65915
- async listSessions(limit) {
65916
- const rows = await this.#session.listSessions(limit);
65917
- return rows.map((row) => ({
65918
- id: row.id,
65919
- title: row.title,
65920
- ...row.updatedAt !== undefined ? { updatedAt: row.updatedAt } : {},
65921
- ...row.cwd !== undefined ? { cwd: row.cwd } : {},
65922
- ...row.sizeBytes !== undefined ? { sizeBytes: row.sizeBytes } : {},
65923
- ...row.blank !== undefined ? { blank: row.blank } : {}
65924
- }));
65925
- }
65926
- async searchSessions(query) {
65927
- return this.#session.searchSessions(query);
65928
- }
65929
- async sessionJournal(sessionId) {
65930
- return this.#session.sessionJournal(sessionId);
65931
- }
65932
- async forkSession(sessionId, seqEnd) {
65933
- return this.#session.forkSession(sessionId, seqEnd);
65934
- }
65935
- async storedTranscript(id, skip) {
65936
- const rows = await this.#session.storedTranscript(id, skip);
65937
- return rows.map((row) => {
65938
- if (row.kind === "ask") {
65939
- return { kind: row.kind, text: "", final: true, entries: row.entries };
65940
- }
65941
- if (row.kind === "tool") {
65942
- return { kind: "tool", text: row.name, final: true, args: row.args, output: row.brief, ok: row.ok };
65943
- }
65944
- return {
65945
- kind: row.kind,
65946
- text: row.text,
65947
- final: row.kind === "assistant" ? row.final ?? true : true
65948
- };
65949
- });
65950
- }
65951
- currentSessionId() {
65952
- return this.#session.currentSessionId();
65953
- }
65954
- stagedSessionId() {
65955
- return this.#session.stagedSessionId();
65956
- }
65957
- cacheHitRate(mode) {
65958
- return this.#session.cacheHitRate(mode);
65959
- }
65960
- contextTokens() {
65961
- return this.#session.contextTokens();
65962
- }
65963
- contextWindow() {
65964
- return this.#session.contextWindow() ?? null;
65965
- }
65966
- configLoad() {
65967
- return this.#session.configLoad();
65968
- }
65969
- configSave(patch) {
65970
- return this.#session.configSave(patch);
65971
- }
65972
- configRaw() {
65973
- return this.#session.configRaw();
65974
- }
65975
- workspaceConfig() {
65976
- return this.#session.workspaceConfig();
65977
- }
65978
- async sessionInfo() {
65979
- const base = this.#session.sessionInfo();
65980
- const sessionId = base.sessionId ?? this.#session.stagedSessionId?.();
65981
- if (sessionId === undefined)
65982
- return;
65983
- let messageCount = 0;
65984
- let turnCount = 0;
65985
- try {
65986
- const rows = await this.#session.storedTranscript(sessionId);
65987
- messageCount = rows.filter((row) => row.kind === "user" || row.kind === "assistant").length;
65988
- turnCount = rows.filter((row) => row.kind === "user").length;
65989
- } catch {}
65990
- const msgCount = base.sessionId === undefined ? undefined : base.msgCount;
65991
- return {
65992
- ...base,
65993
- sessionId,
65994
- model: base.model ?? null,
65995
- messageCount,
65996
- turnCount,
65997
- msgCount,
65998
- contextTokens: base.contextTokens,
65999
- contextWindow: base.contextWindow ?? null
66000
- };
66001
- }
66002
- resumeSession(id) {
66003
- return this.#session.resumeSession(id);
66004
- }
66005
- repairScanBroken() {
66006
- return this.#session.repairScanBroken();
66007
- }
66008
- repairSessionLog(path) {
66009
- return this.#session.repairSessionLog(path);
66010
- }
66011
- newSession() {
66012
- this.#session.newSession();
66013
- }
66014
- async renameSession(title) {
66015
- return this.#session.renameSession(title);
66016
- }
66017
- async turn(userText, cb) {
66018
- this.#turnInFlight = true;
66019
- try {
66020
- await this.#session.turn(userText, {
66021
- onThinkingDelta: (text) => cb.onThinkingDelta(text),
66022
- onContentDelta: (text) => cb.onContentDelta(text),
66023
- onTurnEnd: () => {},
66024
- onApprove: async (name, args) => await cb.onApprove(name, args) === "allowed-once",
66025
- onToolStart: (start) => cb.onToolStart?.(start),
66026
- onToolRun: (run) => cb.onToolRun?.(run),
66027
- onError: (message) => cb.onError(message)
66028
- });
66029
- } finally {
66030
- this.#turnInFlight = false;
66031
- }
66032
- }
66033
- steer(text) {
66034
- this.#session.steer(text);
66035
- }
66036
- interrupt() {
66037
- this.#session.abort();
66038
- }
66039
- registerAskProvider(onAsk) {
66040
- this.#session.registerAskProvider(async (questions) => onAsk(questions));
66041
- }
66042
- async listProviders() {
66043
- return this.#session.listProviders();
66044
- }
66045
- async modelCatalog(force) {
66046
- const catalog = await this.#session.modelCatalog(force ?? false);
66047
- const rows = [];
66048
- for (const group of Array.isArray(catalog.groups) ? catalog.groups : []) {
66049
- const providerID = String(group?.id ?? "");
66050
- if (!providerID)
66051
- continue;
66052
- for (const model of Array.isArray(group.models) ? group.models : []) {
66053
- const modelID = String(model?.id ?? "");
66054
- if (modelID)
66055
- rows.push({ providerID, modelID });
66056
- }
66057
- }
66058
- return rows;
66059
- }
66060
- async currentModelSelection() {
66061
- const selection = await this.#session.currentModelSelection();
66062
- if (!selection)
66063
- return;
66064
- return { providerID: selection.provider, modelID: selection.model };
66065
- }
66066
- selectModel(providerID, modelID) {
66067
- return this.#session.selectModel({ provider: providerID, model: modelID }).then(() => {
66068
- return;
66069
- });
66070
- }
66071
- lastSelectionError() {
66072
- return this.#session.lastSelectionError();
66073
- }
66074
- thinking = {
66075
- efforts: async () => {
66076
- try {
66077
- const selection = await this.#session.currentModelSelection();
66078
- if (!selection)
66079
- return [];
66080
- const catalog = await this.#session.modelCatalog(false);
66081
- const group = Array.isArray(catalog.groups) ? catalog.groups.find((g) => String(g?.id ?? "") === selection.provider) : undefined;
66082
- const model = Array.isArray(group?.models) ? group.models.find((m) => String(m?.id ?? "") === selection.model) : undefined;
66083
- const efforts = model?.reasoning?.efforts;
66084
- if (!Array.isArray(efforts) || efforts.length === 0)
66085
- return [];
66086
- return efforts.map((e) => ({
66087
- id: String(typeof e === "object" && e !== null ? e?.id ?? "" : e ?? ""),
66088
- name: String(typeof e === "object" && e !== null ? e?.name ?? e?.id ?? "" : e ?? ""),
66089
- ...typeof e === "object" && e !== null && typeof e?.description === "string" && e.description ? { description: e.description } : {}
66090
- })).filter((e) => e.id);
66091
- } catch {
66092
- return [];
66093
- }
66094
- },
66095
- effortsFor: (providerID, modelID) => this.#session.modelEfforts(providerID, modelID),
66096
- currentEffort: async () => {
66097
- const selection = await this.#session.currentModelSelection();
66098
- return selection?.reasoningEffort;
66099
- },
66100
- selectEffort: (effort) => {
66101
- return this.#session.currentModelSelection().then((selection) => {
66102
- if (!selection)
66103
- return;
66104
- return this.#session.selectModel({
66105
- provider: selection.provider,
66106
- model: selection.model,
66107
- ...effort ? { reasoningEffort: effort } : {}
66108
- });
66109
- }).then(() => {
66110
- return;
66111
- });
66112
- }
66113
- };
66114
- usageSummary() {
66115
- return this.#session.usageSummary();
66116
- }
66117
- btwAsk(question, snapshot, onDelta) {
66118
- return this.#session.btwAsk(question, snapshot, onDelta);
66119
- }
66120
- plugins() {
66121
- this.#pluginsRevision[0]();
66122
- return this.#session.listPlugins();
66123
- }
66124
- onPluginsChanged(listener) {
66125
- this.#pluginsPushListeners.push(listener);
66126
- return () => {
66127
- const index = this.#pluginsPushListeners.indexOf(listener);
66128
- if (index >= 0)
66129
- this.#pluginsPushListeners.splice(index, 1);
66130
- };
66131
- }
66132
- pluginBundles() {
66133
- this.#pluginsRevision[0]();
66134
- return this.#session.listBundles();
66135
- }
66136
- setPluginBundleEnabled(name, enabled) {
66137
- return this.#session.setBundleEnabled(name, enabled);
66138
- }
66139
- removePluginBundle(name) {
66140
- return this.#session.removeBundle(name);
66141
- }
66142
- inspectPluginSpec(spec) {
66143
- return this.#session.inspectBundle(spec);
66144
- }
66145
- installPluginSpec(spec) {
66146
- return this.#session.installBundle(spec);
66147
- }
66148
- async refreshSkills() {
66149
- return this.#session.refreshSkills();
66150
- }
66151
- onSkillsChanged(listener) {
66152
- return this.#session.onSkillsChanged(listener);
66153
- }
66154
- preset = {
66155
- list: () => this.#session.listPresets(),
66156
- currentId: async () => this.#session.resolveCurrentPresetId(),
66157
- select: async (presetId) => {
66158
- try {
66159
- this.#session.switchPreset(presetId);
66160
- return true;
66161
- } catch (error) {
66162
- console.error("[session-seam-adapter] preset switch failed:", error);
66163
- return false;
66164
- }
66165
- }
66166
- };
66167
- agents = {
66168
- list: () => this.#session.listAgents(),
66169
- dir: () => this.#session.agentsDir(),
66170
- set: (name, field, value) => {
66171
- const result = this.#session.agentSet(name, field, value);
66172
- return { target: result.target, ...result.error !== undefined ? { error: result.error } : {} };
66173
- },
66174
- body: (name) => this.#session.agentBody(name),
66175
- modelEfforts: (providerID, modelID) => this.#session.modelEfforts(providerID, modelID),
66176
- officialCaps: () => this.#session.agentOfficialCaps()
66177
- };
66178
- settings = {
66179
- describe: async () => {
66180
- const doc = await this.#session.settingsDocument();
66181
- return {
66182
- writable: doc.writable,
66183
- hasDocument: doc.hasDocument,
66184
- namespaces: doc.namespaces.map(asSeamSettingsRow)
66185
- };
66186
- },
66187
- mutate: async (ns, ops, revision) => {
66188
- try {
66189
- await this.#session.settingsMutate(ns, ops, revision);
66190
- return { ok: true };
66191
- } catch (error) {
66192
- return {
66193
- ok: false,
66194
- conflict: error?.code === "settings/conflict",
66195
- error: error instanceof Error ? error.message : String(error)
66196
- };
66197
- }
66198
- },
66199
- onChanged: (listener) => this.#session.onSettingsUpdated(listener),
66200
- identity: () => ({
66201
- profile: this.#session.profileName(),
66202
- dshHome: this.#session.homeDir()
66203
- }),
66204
- permissionCatalog: () => this.#session.permissionCatalog()
66205
- };
66206
- login = {
66207
- credentialStatus: (ref) => this.#session.credentialStatus(ref),
66208
- login: (ref, apiKey) => this.#session.login(ref, apiKey),
66209
- logout: (ref) => this.#session.logout(ref),
66210
- routes: async () => {
66211
- const rows = await this.#session.settingsSeam.describe();
66212
- const ns = Array.isArray(rows) ? rows.find((row) => row?.ns === "llm-pi-ai") : undefined;
66213
- const providers = ns?.value?.providers ?? {};
66214
- return Object.entries(providers).map(([id, profile]) => {
66215
- const p = typeof profile === "object" && profile !== null ? profile : {};
66216
- const apiKeyEnv = p.apiKeyEnv;
66217
- const displayName = p.displayName;
66218
- return {
66219
- id,
66220
- ...typeof apiKeyEnv === "string" && apiKeyEnv !== "" ? { apiKeyEnv } : {},
66221
- ...typeof displayName === "string" && displayName !== "" ? { displayName } : {},
66222
- ...typeof p.api === "string" || typeof p.baseURL === "string" || Array.isArray(p.models) ? { declared: true } : {}
66223
- };
66224
- });
66225
- },
66226
- registerRoute: async (providerId, profile) => {
66227
- try {
66228
- const rows = await this.#session.settingsSeam.describe();
66229
- const ns = Array.isArray(rows) ? rows.find((row) => row?.ns === "llm-pi-ai") : undefined;
66230
- const ops = profile ? [{ op: "set", path: ["providers", providerId], value: profile }] : [{ op: "unset", path: ["providers", providerId] }];
66231
- await this.#session.settingsSeam.mutate("llm-pi-ai", ops, ns?.revision);
66232
- return true;
66233
- } catch (error) {
66234
- console.error("[session-seam-adapter] login route registration failed:", error);
66235
- return false;
66236
- }
66237
- }
66238
- };
66239
- #projectSubagentViews(views) {
66240
- return views.map((v) => ({
66241
- id: v.id,
66242
- label: v.label,
66243
- ...v.model ? { model: v.model } : {},
66244
- status: v.status,
66245
- rounds: v.rounds,
66246
- ...v.startedAt !== undefined ? v.status === "running" ? { startedAt: v.startedAt } : { elapsedSec: Number(((Date.now() - v.startedAt) / 1000).toFixed(1)) } : {},
66247
- ...v.status !== "running" && v.endedAt !== undefined ? { endedAt: v.endedAt } : {},
66248
- ...v.injectedRound !== undefined ? { injectedRound: v.injectedRound } : {},
66249
- ...v.hardStopRound !== undefined ? { hardStopRound: v.hardStopRound } : {},
66250
- ...v.spinStopRound !== undefined ? { spinStopRound: v.spinStopRound } : {},
66251
- ...v.lastLine !== undefined ? { lastLine: v.lastLine } : {}
66252
- }));
66253
- }
66254
- subagentViews() {
66255
- return this.#projectSubagentViews(this.#session.subagentViews());
66256
- }
66257
- onSubagentViews(listener) {
66258
- foldSubagentMarkerViews(this.subagentViews());
66259
- return this.#session.onSubagentViews((views) => {
66260
- const projected = this.#projectSubagentViews(views);
66261
- foldSubagentMarkerViews(projected);
66262
- listener(projected);
66263
- });
66264
- }
66265
- steerChild(id, text) {
66266
- return this.#session.steerChild(id, text);
66267
- }
66268
- subagentTranscript(id) {
66269
- return this.#session.childTranscript(id);
66270
- }
66271
- async interruptChild(id) {
66272
- await this.#session.interruptChild(id);
66273
- }
66274
- onSessionEvent(listener) {
66275
- this.#listeners.push(listener);
66276
- this.#ensureJournalFeed();
66277
- return () => {
66278
- const index = this.#listeners.indexOf(listener);
66279
- if (index >= 0)
66280
- this.#listeners.splice(index, 1);
66281
- };
66282
- }
66283
- async dispose() {
66284
- this.#unjournal?.();
66285
- this.#unjournal = undefined;
66286
- this.#unplugins?.();
66287
- this.#unplugins = undefined;
66288
- this.#listeners.length = 0;
66289
- this.#pluginsPushListeners.length = 0;
66290
- await this.#session.dispose();
66291
- }
66292
- #ensureJournalFeed() {
66293
- if (this.#unjournal !== undefined)
66294
- return;
66295
- const hook = this.#session;
66296
- if (typeof hook.onJournalRecord !== "function")
66297
- return;
66298
- this.#unjournal = hook.onJournalRecord((entry) => {
66299
- if (this.#turnInFlight)
66300
- return;
66301
- for (const event of projectJournalRecord(entry, this.#session.currentSessionId() ?? "")) {
66302
- this.#emit(event);
66303
- }
66304
- });
66305
- }
66306
- #emit(event) {
66307
- for (const listener of this.#listeners) {
66308
- try {
66309
- listener(event);
66310
- } catch {}
66311
- }
66312
- }
65984
+ // src/client/journal-projection.ts
65985
+ function assistantTextValue(data) {
65986
+ if (typeof data.text === "string")
65987
+ return data.text.trim();
65988
+ return blocksText(data.content ?? data.parts);
66313
65989
  }
66314
65990
  function projectJournalRecord(entry, sessionId) {
66315
65991
  if (entry.type === "user/message") {
66316
- const text = blocksText3(entry.data.content);
65992
+ const text = blocksText(entry.data.content);
66317
65993
  if (!text)
66318
65994
  return [];
66319
65995
  const id = typeof entry.data.messageID === "string" ? entry.data.messageID : `journal-${entry.seq}`;
@@ -66347,42 +66023,377 @@ function projectJournalRecord(entry, sessionId) {
66347
66023
  }
66348
66024
  return [];
66349
66025
  }
66350
- function blocksText3(content) {
66351
- const blocks = Array.isArray(content) ? content : [];
66352
- let text = "";
66353
- for (const block of blocks) {
66354
- if (typeof block === "object" && block !== null && block.type === "text") {
66355
- const value = block.text;
66356
- if (typeof value === "string")
66357
- text += (text === "" ? "" : `
66358
- `) + value;
66026
+ var NOTICE_SOURCE_KINDS;
66027
+ var init_journal_projection = __esm(() => {
66028
+ init_remote_follow();
66029
+ NOTICE_SOURCE_KINDS = new Set(["subagent-settled", "agent-message", "team-message", "webhook"]);
66030
+ });
66031
+
66032
+ // src/client/local-config-faces.ts
66033
+ import { existsSync as existsSync12, mkdirSync as mkdirSync7, readFileSync as readFileSync13, renameSync as renameSync9, rmSync as rmSync5, writeFileSync as writeFileSync9 } from "fs";
66034
+ import { dirname as dirname7, join as join15 } from "path";
66035
+ function asRecord5(value) {
66036
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
66037
+ }
66038
+ function parseScalar(raw) {
66039
+ const v = raw.trim();
66040
+ if (v === "true")
66041
+ return true;
66042
+ if (v === "false")
66043
+ return false;
66044
+ if (v === "null" || v === "~")
66045
+ return null;
66046
+ if (/^-?\d+$/.test(v))
66047
+ return Number(v);
66048
+ if (/^-?\d+\.\d+$/.test(v))
66049
+ return Number(v);
66050
+ return v.replace(/^["']|["']$/g, "");
66051
+ }
66052
+ function nsEntrySpan(lines, ns) {
66053
+ const start = lines.findIndex((line) => new RegExp(`^- id:\\s*${ns}\\s*$`).test(line));
66054
+ if (start < 0)
66055
+ return;
66056
+ let end = lines.length;
66057
+ for (let i = start + 1;i < lines.length; i++) {
66058
+ if (/^- /.test(lines[i]) || /^-insert:/.test(lines[i]) || /^-\s+insert:/.test(lines[i])) {
66059
+ end = i;
66060
+ break;
66359
66061
  }
66360
66062
  }
66361
- return text.trim();
66063
+ return [start, end];
66362
66064
  }
66363
- function assistantTextValue(data) {
66364
- if (typeof data.text === "string")
66365
- return data.text.trim();
66366
- return blocksText3(data.content ?? data.parts);
66065
+ function readNsValue(lines, ns) {
66066
+ const span = nsEntrySpan(lines, ns);
66067
+ const out = {};
66068
+ const fields = NS_VALUE_FIELDS[ns];
66069
+ if (span === undefined)
66070
+ return out;
66071
+ let inConfig = false;
66072
+ for (let i = span[0] + 1;i < span[1]; i++) {
66073
+ const line = lines[i];
66074
+ if (/^\s{2}config:\s*$/.test(line)) {
66075
+ inConfig = true;
66076
+ continue;
66077
+ }
66078
+ if (inConfig && /^\s{2}\S/.test(line))
66079
+ break;
66080
+ if (!inConfig)
66081
+ continue;
66082
+ const m = /^\s{4}([A-Za-z_][A-Za-z0-9_]*)\s*:\s*(.*)$/.exec(line);
66083
+ if (m && fields.includes(m[1]))
66084
+ out[m[1]] = parseScalar(m[2]);
66085
+ }
66086
+ return out;
66367
66087
  }
66368
- function asSeamSettingsRow(row) {
66369
- return {
66370
- ns: row.ns,
66371
- ...row.revision !== undefined ? { revision: row.revision } : {},
66372
- ...row.value !== undefined ? { value: row.value } : {},
66373
- ...row.base !== undefined ? { base: row.base } : {},
66374
- ...row.autoGenerate !== undefined ? { autoGenerate: row.autoGenerate } : {},
66375
- ...row.schema !== undefined ? { schema: row.schema } : {},
66376
- ...row.user !== undefined ? { user: row.user } : {},
66377
- ...row.secrets !== undefined ? { secrets: row.secrets.map((secret) => ({ path: [...secret.path], set: secret.set })) } : {}
66378
- };
66088
+ function writeNsField(lines, ns, key, raw) {
66089
+ const fields = NS_VALUE_FIELDS[ns];
66090
+ if (!fields.includes(key))
66091
+ return false;
66092
+ const yaml = /^(true|false|null|~|-?\d+(?:\.\d+)?)$/.test(raw.trim()) || /^["']/.test(raw.trim()) ? raw.trim() : JSON.stringify(raw);
66093
+ const span = nsEntrySpan(lines, ns);
66094
+ if (span === undefined) {
66095
+ lines.push("", `- id: ${ns}`, ` name: '${NS_PACKAGE[ns]}'`, " config:", ` ${key}: ${yaml}`);
66096
+ return true;
66097
+ }
66098
+ let configLine = -1;
66099
+ for (let i = span[0] + 1;i < span[1]; i++) {
66100
+ if (/^\s{2}config:\s*$/.test(lines[i])) {
66101
+ configLine = i;
66102
+ break;
66103
+ }
66104
+ }
66105
+ if (configLine < 0) {
66106
+ lines.splice(span[0] + 1, 0, " config:", ` ${key}: ${yaml}`);
66107
+ return true;
66108
+ }
66109
+ for (let i = configLine + 1;i < span[1]; i++) {
66110
+ const m = /^(\s{4})([A-Za-z_][A-Za-z0-9_]*)\s*:\s*(.*)$/.exec(lines[i]);
66111
+ if (!m)
66112
+ continue;
66113
+ if (/^\s{2}\S/.test(lines[i]))
66114
+ break;
66115
+ if (m[2] === key) {
66116
+ lines[i] = ` ${key}: ${yaml}`;
66117
+ return true;
66118
+ }
66119
+ }
66120
+ lines.splice(configLine + 1, 0, ` ${key}: ${yaml}`);
66121
+ return true;
66379
66122
  }
66380
- var NOTICE_SOURCE_KINDS;
66381
- var init_session_seam_adapter = __esm(() => {
66382
- init_remote_follow();
66383
- init_subagent_markers();
66384
- init_server();
66385
- NOTICE_SOURCE_KINDS = new Set(["subagent-settled", "agent-message", "team-message", "webhook"]);
66123
+ function atomicWrite2(path, text) {
66124
+ mkdirSync7(dirname7(path), { recursive: true });
66125
+ const tmp = `${path}.${process.pid}.s5.tmp`;
66126
+ try {
66127
+ writeFileSync9(tmp, text);
66128
+ renameSync9(tmp, path);
66129
+ } catch (err) {
66130
+ try {
66131
+ rmSync5(tmp, { force: true });
66132
+ } catch {}
66133
+ throw err;
66134
+ }
66135
+ }
66136
+
66137
+ class LocalSettingsStore {
66138
+ #patchPath;
66139
+ constructor(home, profile) {
66140
+ this.#patchPath = join15(home, "profiles", profile, "cordis.patch.yml");
66141
+ }
66142
+ describe() {
66143
+ let lines = [];
66144
+ try {
66145
+ lines = readFileSync13(this.#patchPath, "utf8").split(`
66146
+ `);
66147
+ } catch {}
66148
+ const namespaces = SETTINGS_NAMESPACES.map((ns) => {
66149
+ const patchValue = readNsValue(lines, ns);
66150
+ const value = {};
66151
+ for (const field of NS_VALUE_FIELDS[ns]) {
66152
+ const v = patchValue[field] ?? NS_DEFAULTS[ns][field];
66153
+ if (v !== undefined)
66154
+ value[field] = v;
66155
+ }
66156
+ const schema = {};
66157
+ for (const field of NS_VALUE_FIELDS[ns])
66158
+ schema[field] = { type: typeof value[field] };
66159
+ if (ns === "permission") {
66160
+ const presets = value.presets;
66161
+ if (presets && typeof presets === "object") {
66162
+ schema.defaultPreset = { type: "string", enum: Object.keys(presets) };
66163
+ }
66164
+ }
66165
+ return { ns, revision: 1, value, base: { ...value }, schema, secrets: [] };
66166
+ });
66167
+ const hidden = new Set([...SETTINGS_NAMESPACES, "dsh-tui"]);
66168
+ const seen = new Set(SETTINGS_NAMESPACES);
66169
+ const others = [];
66170
+ for (const line of lines) {
66171
+ const m = /^- id:\s*([A-Za-z0-9_.\-@/]+)\s*$/.exec(line);
66172
+ if (!m)
66173
+ continue;
66174
+ const ns = m[1];
66175
+ if (hidden.has(ns) || seen.has(ns))
66176
+ continue;
66177
+ seen.add(ns);
66178
+ others.push({ ns, revision: 1 });
66179
+ }
66180
+ others.sort((a, b) => a.ns === "agent-default-model" ? -1 : b.ns === "agent-default-model" ? 1 : 0);
66181
+ namespaces.push(...others);
66182
+ return { writable: true, hasDocument: existsSync12(this.#patchPath), namespaces };
66183
+ }
66184
+ mutate(ns, ops, _revision) {
66185
+ if (!SETTINGS_NAMESPACES.includes(ns)) {
66186
+ return { ok: false, conflict: false, error: `settings.mutate: namespace '${ns}' is not whitelisted` };
66187
+ }
66188
+ const allow = NS_VALUE_FIELDS[ns];
66189
+ for (const op of ops) {
66190
+ if (!Array.isArray(op.path) || op.path.length !== 1 || !allow.includes(op.path[0])) {
66191
+ return { ok: false, conflict: false, error: `settings.mutate: path not whitelisted for '${ns}'` };
66192
+ }
66193
+ }
66194
+ let text = "";
66195
+ try {
66196
+ text = readFileSync13(this.#patchPath, "utf8");
66197
+ } catch {}
66198
+ const lines = text.length > 0 ? text.split(`
66199
+ `) : [];
66200
+ for (const op of ops) {
66201
+ const key = op.path[0];
66202
+ if (op.op === "unset") {
66203
+ const fallback = NS_DEFAULTS[ns][key];
66204
+ if (fallback !== undefined)
66205
+ writeNsField(lines, ns, key, String(fallback));
66206
+ continue;
66207
+ }
66208
+ const value = op.value;
66209
+ if (typeof value === "object" && value !== null) {
66210
+ return { ok: false, conflict: false, error: "settings.mutate: nested value not whitelisted" };
66211
+ }
66212
+ writeNsField(lines, ns, key, String(value));
66213
+ }
66214
+ try {
66215
+ atomicWrite2(this.#patchPath, lines.join(`
66216
+ `).replace(/\n*$/, `
66217
+ `));
66218
+ } catch (err) {
66219
+ return { ok: false, conflict: false, error: err instanceof Error ? err.message : String(err) };
66220
+ }
66221
+ return { ok: true };
66222
+ }
66223
+ }
66224
+
66225
+ class LocalConfigStore {
66226
+ #configPath;
66227
+ #overlayPath;
66228
+ #overlayCache;
66229
+ constructor(home, profile, workspaceDir) {
66230
+ this.#configPath = join15(home, "profiles", profile, "config.json");
66231
+ this.#overlayPath = workspaceConfigPath(workspaceDir);
66232
+ this.#overlayCache = loadWorkspaceConfigState(workspaceDir);
66233
+ }
66234
+ #readProfile() {
66235
+ try {
66236
+ return asRecord5(JSON.parse(readFileSync13(this.#configPath, "utf8")));
66237
+ } catch {
66238
+ return {};
66239
+ }
66240
+ }
66241
+ configRaw() {
66242
+ return this.#readProfile();
66243
+ }
66244
+ configLoad() {
66245
+ const base = this.#readProfile();
66246
+ const merged = mergeConfig({ theme: typeof base.theme === "string" ? base.theme : undefined }, this.#overlayCache, process.env);
66247
+ const out = {};
66248
+ for (const key of CONFIG_KEYS)
66249
+ if (base[key] !== undefined)
66250
+ out[key] = base[key];
66251
+ if (merged.theme !== undefined)
66252
+ out.theme = merged.theme;
66253
+ if (merged.themeMode !== undefined)
66254
+ out.themeMode = merged.themeMode;
66255
+ if (merged.model !== undefined)
66256
+ out.model = merged.model;
66257
+ return out;
66258
+ }
66259
+ workspaceConfig() {
66260
+ return { ...this.#overlayCache };
66261
+ }
66262
+ configSave(patch) {
66263
+ const current = this.#readProfile();
66264
+ const next = {};
66265
+ for (const [key, value] of Object.entries(patch)) {
66266
+ if (CONFIG_KEY_SET.has(key))
66267
+ next[key] = value;
66268
+ }
66269
+ if (Object.keys(next).length === 0)
66270
+ return this.configLoad();
66271
+ const merged = { ...current, ...next };
66272
+ atomicWrite2(this.#configPath, JSON.stringify(merged, null, 2) + `
66273
+ `);
66274
+ return this.configLoad();
66275
+ }
66276
+ }
66277
+ function loadWorkspaceConfigState(workspaceDir) {
66278
+ try {
66279
+ const raw = JSON.parse(readFileSync13(join15(workspaceDir, ".dsh", "config.yml"), "utf8"));
66280
+ return asRecord5(raw);
66281
+ } catch {
66282
+ try {
66283
+ const text = readFileSync13(join15(workspaceDir, ".dsh", "config.yml"), "utf8");
66284
+ const out = {};
66285
+ const m = /^\s*theme:\s*(.+)$/m.exec(text);
66286
+ if (m)
66287
+ out.theme = parseScalar(m[1]);
66288
+ return out;
66289
+ } catch {
66290
+ return {};
66291
+ }
66292
+ }
66293
+ }
66294
+
66295
+ class LocalAgentsFace {
66296
+ #home;
66297
+ #workspaceDir;
66298
+ #settings;
66299
+ #modelCatalog;
66300
+ constructor(options) {
66301
+ this.#home = options.home;
66302
+ this.#workspaceDir = options.workspaceDir;
66303
+ this.#settings = options.settings;
66304
+ this.#modelCatalog = options.modelCatalog;
66305
+ }
66306
+ #rows() {
66307
+ return listComposedAgents(this.#home, this.#workspaceDir);
66308
+ }
66309
+ list() {
66310
+ return this.#rows().map((row) => ({
66311
+ name: row.name,
66312
+ ...row.displayName ? { displayName: row.displayName } : {},
66313
+ ...row.description ? { description: row.description } : {},
66314
+ ...row.model ? { model: row.model } : {},
66315
+ ...row.thinking ? { thinking: row.thinking } : {},
66316
+ deep: row.deep,
66317
+ ...row.maxRounds !== undefined ? { maxRounds: row.maxRounds } : {},
66318
+ ...row.background !== undefined ? { background: row.background } : {},
66319
+ file: row.file,
66320
+ ...row.pin ? { pin: row.pin } : {},
66321
+ ...row.broken ? { broken: row.broken } : {}
66322
+ }));
66323
+ }
66324
+ dir() {
66325
+ return join15(this.#home, "agents");
66326
+ }
66327
+ body(name) {
66328
+ return this.#rows().find((row) => row.name === name && row.broken === undefined)?.body ?? "";
66329
+ }
66330
+ set(name, field, value) {
66331
+ if (field === "deep" || field === "maxRounds" || field === "background") {
66332
+ const error = setAgentField(name, field, value, this.#home);
66333
+ return { target: { kind: "frontmatter" }, ...error ? { error } : {} };
66334
+ }
66335
+ const row = this.#rows().find((agent) => agent.name === name && agent.broken === undefined);
66336
+ if (row === undefined)
66337
+ return { target: { kind: "frontmatter" }, error: `agent "${name}" not found` };
66338
+ const result = commitAgentModelEdit(this.#home, this.#workspaceDir, row.file, name, { [field]: value });
66339
+ return { target: result.target, ...result.error ? { error: result.error } : {} };
66340
+ }
66341
+ async modelEfforts(providerID, modelID) {
66342
+ const catalog = await this.#modelCatalog();
66343
+ const model = catalog.groups.find((g) => g.id === providerID)?.models.find((m) => m.id === modelID);
66344
+ return model?.reasoning?.efforts ?? [];
66345
+ }
66346
+ async officialCaps() {
66347
+ const doc = this.#settings.describe();
66348
+ const row = doc.namespaces.find((n) => n.ns === "subagent");
66349
+ const value = asRecord5(row?.value);
66350
+ const caps = {};
66351
+ if (typeof value.maxActiveSubagents === "number" && Number.isFinite(value.maxActiveSubagents))
66352
+ caps.maxActiveSubagents = value.maxActiveSubagents;
66353
+ if (typeof value.maxDepth === "number" && Number.isFinite(value.maxDepth))
66354
+ caps.maxDepth = value.maxDepth;
66355
+ return caps;
66356
+ }
66357
+ }
66358
+ var SETTINGS_NAMESPACES, NS_VALUE_FIELDS, NS_PACKAGE, NS_DEFAULTS, CONFIG_KEYS, CONFIG_KEY_SET;
66359
+ var init_local_config_faces = __esm(() => {
66360
+ init_remote_agent_profiles();
66361
+ init_remote_local_fs();
66362
+ init_workspace_config();
66363
+ SETTINGS_NAMESPACES = ["subagent", "permission", "session-log-deepseek"];
66364
+ NS_VALUE_FIELDS = {
66365
+ subagent: ["maxActiveSubagents", "maxDepth"],
66366
+ permission: ["defaultPreset", "presets"],
66367
+ "session-log-deepseek": ["enabled"]
66368
+ };
66369
+ NS_PACKAGE = {
66370
+ subagent: "@deepseek-ai/dsh-subagent",
66371
+ permission: "@deepseek-ai/dsh-permission-presets",
66372
+ "session-log-deepseek": "@deepseek-ai/dsh-session-log-deepseek"
66373
+ };
66374
+ NS_DEFAULTS = {
66375
+ subagent: { maxActiveSubagents: 1, maxDepth: 1 },
66376
+ permission: { defaultPreset: "workspace-write" },
66377
+ "session-log-deepseek": { enabled: true }
66378
+ };
66379
+ CONFIG_KEYS = [
66380
+ "lang",
66381
+ "motion",
66382
+ "theme",
66383
+ "themeMode",
66384
+ "skin",
66385
+ "cacheHitMode",
66386
+ "footerHints",
66387
+ "hintsLocale",
66388
+ "autoResume",
66389
+ "autoResumeDays",
66390
+ "maxRoundsGrace",
66391
+ "activity_panel_height",
66392
+ "stepsDisplay",
66393
+ "stepsCollapse",
66394
+ "stepsFolded"
66395
+ ];
66396
+ CONFIG_KEY_SET = new Set(CONFIG_KEYS);
66386
66397
  });
66387
66398
 
66388
66399
  // src/client/bridge-session-seam.ts
@@ -66395,7 +66406,7 @@ function optionalStringField(row, key) {
66395
66406
  return typeof value === "string" && value !== "" ? value : undefined;
66396
66407
  }
66397
66408
  function parseAskRequest(value) {
66398
- const row = asRecord5(value);
66409
+ const row = asRecord6(value);
66399
66410
  const eventId = optionalStringField(row, "eventId");
66400
66411
  const sessionId = optionalStringField(row, "sessionId");
66401
66412
  const kind = row.kind;
@@ -66418,14 +66429,14 @@ function parseAskRequest(value) {
66418
66429
  if (Array.isArray(row.questions)) {
66419
66430
  const questions = [];
66420
66431
  for (const raw of row.questions) {
66421
- const q = asRecord5(raw);
66432
+ const q = asRecord6(raw);
66422
66433
  const id = optionalStringField(q, "id");
66423
66434
  const prompt = optionalStringField(q, "prompt");
66424
66435
  if (id === undefined || prompt === undefined || !Array.isArray(q.options))
66425
66436
  continue;
66426
66437
  const options = [];
66427
66438
  for (const rawOpt of q.options) {
66428
- const opt = asRecord5(rawOpt);
66439
+ const opt = asRecord6(rawOpt);
66429
66440
  const label = optionalStringField(opt, "label");
66430
66441
  if (label === undefined)
66431
66442
  continue;
@@ -66495,7 +66506,7 @@ function answersFor(request, picks) {
66495
66506
  function unavailableResponse(request) {
66496
66507
  return request.kind === "questions" ? { eventId: request.eventId, kind: "questions", verdict: "unavailable", answers: answersFor(request, []) } : { eventId: request.eventId, kind: "approval", verdict: "unavailable" };
66497
66508
  }
66498
- function asRecord5(value) {
66509
+ function asRecord6(value) {
66499
66510
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
66500
66511
  }
66501
66512
  function unsupported(capability) {
@@ -66505,14 +66516,14 @@ function projectBridgeSessionList(items, limit = 12) {
66505
66516
  const rows = Array.isArray(items) ? items : [];
66506
66517
  const out = [];
66507
66518
  for (const item of rows) {
66508
- const row = asRecord5(item);
66519
+ const row = asRecord6(item);
66509
66520
  if (row.origin === "subagent")
66510
66521
  continue;
66511
66522
  const id = typeof row.sessionId === "string" ? row.sessionId : "";
66512
66523
  if (!id)
66513
66524
  continue;
66514
66525
  const updatedAt = typeof row.updatedAt === "number" ? String(row.updatedAt) : "";
66515
- const values = asRecord5(asRecord5(row.projections).values);
66526
+ const values = asRecord6(asRecord6(row.projections).values);
66516
66527
  const title = typeof values.title === "string" ? values.title : "";
66517
66528
  out.push({
66518
66529
  id,
@@ -66530,7 +66541,7 @@ function bridgeReplayRowsToSeamTranscript(rows, skip = 0) {
66530
66541
  type: row.type,
66531
66542
  seq: row.seq,
66532
66543
  time: 0,
66533
- data: asRecord5(row.payload)
66544
+ data: asRecord6(row.payload)
66534
66545
  }));
66535
66546
  const durable = journalToTranscriptRows(entries, skip);
66536
66547
  return durable.map((row) => {
@@ -66544,8 +66555,8 @@ function bridgeReplayRowsToSeamTranscript(rows, skip = 0) {
66544
66555
  });
66545
66556
  }
66546
66557
  function seamReplayEventKey(event) {
66547
- const details = asRecord5(event.details);
66548
- return `${event.type}:${String(details.id ?? details.messageID ?? "")}:${String(asRecord5(details.part).id ?? "")}`;
66558
+ const details = asRecord6(event.details);
66559
+ return `${event.type}:${String(details.id ?? details.messageID ?? "")}:${String(asRecord6(details.part).id ?? "")}`;
66549
66560
  }
66550
66561
  function bridgeReplayRowsToSeamEvents(rows, sessionId) {
66551
66562
  const events = [];
@@ -66559,7 +66570,7 @@ function bridgeReplayRowsToSeamEvents(rows, sessionId) {
66559
66570
  };
66560
66571
  const toolCalls = new Map;
66561
66572
  for (const row of rows) {
66562
- const entry = { type: row.type, seq: row.seq, time: 0, data: asRecord5(row.payload) };
66573
+ const entry = { type: row.type, seq: row.seq, time: 0, data: asRecord6(row.payload) };
66563
66574
  for (const event of projectJournalRecord(entry, sessionId))
66564
66575
  push(event);
66565
66576
  const data = entry.data;
@@ -66573,7 +66584,7 @@ function bridgeReplayRowsToSeamEvents(rows, sessionId) {
66573
66584
  });
66574
66585
  }
66575
66586
  } else if (row.type === "tool/result") {
66576
- const message = asRecord5(data.message);
66587
+ const message = asRecord6(data.message);
66577
66588
  const callId = data.callId !== undefined ? String(data.callId) : message.toolCallId !== undefined ? String(message.toolCallId) : "";
66578
66589
  const call = callId ? toolCalls.get(callId) : undefined;
66579
66590
  if (call !== undefined) {
@@ -66627,7 +66638,7 @@ function bridgeSettleChild(existing, outcome, startedAt, now) {
66627
66638
  }
66628
66639
  function bridgeFoldAgentRecord(children, runSeq, liveStarts, type, data, now, live) {
66629
66640
  if (type === "user/message") {
66630
- const source = asRecord5(data.source);
66641
+ const source = asRecord6(data.source);
66631
66642
  if (source.kind !== BRIDGE_SUBAGENT_SETTLED)
66632
66643
  return false;
66633
66644
  const childId = typeof source.senderSessionId === "string" ? source.senderSessionId : "";
@@ -66722,7 +66733,7 @@ function bridgeSweepSettledChildIds(rows, parentId, locallyRunning) {
66722
66733
  return [];
66723
66734
  const settled = [];
66724
66735
  for (const raw of rows) {
66725
- const row = asRecord5(raw);
66736
+ const row = asRecord6(raw);
66726
66737
  if (row.origin !== "subagent")
66727
66738
  continue;
66728
66739
  if (row.parentSessionId !== parentId)
@@ -66772,16 +66783,16 @@ function bridgeChildJournalMeta(rows) {
66772
66783
  let contextModel;
66773
66784
  let descriptorModel;
66774
66785
  for (const row of rows) {
66775
- const data = asRecord5(row.payload);
66786
+ const data = asRecord6(row.payload);
66776
66787
  if (row.type === "assistant/message") {
66777
66788
  rounds += 1;
66778
- const message = asRecord5(data.message);
66789
+ const message = asRecord6(data.message);
66779
66790
  const tail = bridgeLastContentLine(bridgeBlocksText(message.content ?? data.content));
66780
66791
  if (tail !== undefined)
66781
66792
  lastLine = tail;
66782
66793
  } else if (row.type === "tool/result") {
66783
66794
  if (data.isError !== true) {
66784
- const message = asRecord5(data.message);
66795
+ const message = asRecord6(data.message);
66785
66796
  const tail = bridgeLastContentLine(bridgeBlocksText(message.content ?? data.content));
66786
66797
  if (tail !== undefined)
66787
66798
  lastLine = tail;
@@ -66808,7 +66819,7 @@ function bridgeChildStopReason(rows) {
66808
66819
  const row = rows[i];
66809
66820
  if (row.type !== "user/message")
66810
66821
  continue;
66811
- const source = asRecord5(asRecord5(row.payload).source);
66822
+ const source = asRecord6(asRecord6(row.payload).source);
66812
66823
  if (source.kind !== BRIDGE_SUBAGENT_SETTLED)
66813
66824
  continue;
66814
66825
  const reason = source.stopReason;
@@ -66819,7 +66830,7 @@ function bridgeChildStopReason(rows) {
66819
66830
  const row = rows[i];
66820
66831
  if (row.type !== "turn/end")
66821
66832
  continue;
66822
- const reason = asRecord5(asRecord5(row.payload).reason);
66833
+ const reason = asRecord6(asRecord6(row.payload).reason);
66823
66834
  const kind = reason.kind;
66824
66835
  if (typeof kind === "string" && kind !== "")
66825
66836
  return kind;
@@ -66877,7 +66888,7 @@ function lastJournalTurnTerminal(rows, startOutsideWindow = false) {
66877
66888
  return latest;
66878
66889
  }
66879
66890
  function journalTurnId(row) {
66880
- const payload = asRecord5(row.payload);
66891
+ const payload = asRecord6(row.payload);
66881
66892
  if (typeof payload.turn === "number" && Number.isFinite(payload.turn))
66882
66893
  return payload.turn;
66883
66894
  if (typeof payload.turnId === "string" && payload.turnId !== "")
@@ -66885,7 +66896,7 @@ function journalTurnId(row) {
66885
66896
  return;
66886
66897
  }
66887
66898
  function projectBridgeEvent(frame, sessionId) {
66888
- const payload = asRecord5(frame.payload);
66899
+ const payload = asRecord6(frame.payload);
66889
66900
  const turnId = typeof payload.turnId === "string" ? payload.turnId : "";
66890
66901
  if (frame.type === "turn.start") {
66891
66902
  return [{ type: "session.updated", details: { sessionID: sessionId, turnId, turn: "starting" } }];
@@ -66907,7 +66918,7 @@ function projectBridgeEvent(frame, sessionId) {
66907
66918
  return [];
66908
66919
  }
66909
66920
  function parseUsage(value) {
66910
- const u = asRecord5(value);
66921
+ const u = asRecord6(value);
66911
66922
  const num = (...aliases) => {
66912
66923
  let present = false;
66913
66924
  let best = 0;
@@ -66936,7 +66947,7 @@ function parseUsage(value) {
66936
66947
  return out;
66937
66948
  }
66938
66949
  function journalUsage(payload) {
66939
- const usage = asRecord5(asRecord5(payload).usage);
66950
+ const usage = asRecord6(asRecord6(payload).usage);
66940
66951
  const parsed = parseUsage(usage);
66941
66952
  if (Object.keys(parsed).length === 0)
66942
66953
  return;
@@ -66946,7 +66957,7 @@ function journalUsage(payload) {
66946
66957
  return { ...parsed, total };
66947
66958
  }
66948
66959
  function asDeadCause(value) {
66949
- const r = asRecord5(value);
66960
+ const r = asRecord6(value);
66950
66961
  const stage = r.stage;
66951
66962
  const stages = ["spawn", "handshake", "runtime", "closed"];
66952
66963
  return {
@@ -66962,6 +66973,24 @@ function asDeadCause(value) {
66962
66973
  class BridgeSessionSeam {
66963
66974
  #transport;
66964
66975
  #ctx;
66976
+ #dshHome;
66977
+ #profile;
66978
+ #configStore;
66979
+ #settingsStore;
66980
+ #localAgents;
66981
+ settings = {
66982
+ describe: () => Promise.resolve(this.#settingsStore.describe()),
66983
+ mutate: (ns, ops, revision) => Promise.resolve(this.#settingsStore.mutate(ns, ops, revision)),
66984
+ identity: () => ({ profile: this.#profile, dshHome: this.#dshHome })
66985
+ };
66986
+ agents = {
66987
+ list: () => this.#localAgents.list(),
66988
+ dir: () => this.#localAgents.dir(),
66989
+ set: (name, field, value) => this.#localAgents.set(name, field, value),
66990
+ body: (name) => this.#localAgents.body(name),
66991
+ modelEfforts: (providerID, modelID) => this.#localAgents.modelEfforts(providerID, modelID),
66992
+ officialCaps: () => this.#localAgents.officialCaps()
66993
+ };
66965
66994
  #unsubEvent;
66966
66995
  #listeners = [];
66967
66996
  #onDead;
@@ -66994,6 +67023,9 @@ class BridgeSessionSeam {
66994
67023
  #turnGeneration = 0;
66995
67024
  #inFlightGeneration = 0;
66996
67025
  #degradedOnce = new Set;
67026
+ #capPushListeners = new Map;
67027
+ #capPushStatus = new Map;
67028
+ #capPushDrops = new Map;
66997
67029
  #usage = { turns: 0, prompt: 0, completion: 0, cacheRead: 0, cacheWrite: 0 };
66998
67030
  #decodeWindowStart;
66999
67031
  #lastTurnDecode;
@@ -67014,6 +67046,17 @@ class BridgeSessionSeam {
67014
67046
  constructor(options) {
67015
67047
  this.#transport = options.transport;
67016
67048
  this.#ctx = options.ctx;
67049
+ this.#dshHome = options.dshHome ?? resolveDshHome();
67050
+ this.#profile = options.profile ?? DEFAULT_PROFILE;
67051
+ const workspaceDir = options.workspaceDir ?? process.cwd();
67052
+ this.#settingsStore = new LocalSettingsStore(this.#dshHome, this.#profile);
67053
+ this.#configStore = new LocalConfigStore(this.#dshHome, this.#profile, workspaceDir);
67054
+ this.#localAgents = new LocalAgentsFace({
67055
+ home: this.#dshHome,
67056
+ workspaceDir,
67057
+ settings: this.#settingsStore,
67058
+ modelCatalog: () => this.#transport.request("modelCatalog")
67059
+ });
67017
67060
  this.#onDead = options.onDead;
67018
67061
  this.#onPermissionUnavailable = options.onPermissionUnavailable;
67019
67062
  this.#confirmClock = options.confirmClock ?? {
@@ -67027,7 +67070,7 @@ class BridgeSessionSeam {
67027
67070
  }
67028
67071
  async connect() {
67029
67072
  try {
67030
- const reply = asRecord5(await this.#transport.request("bridge.ping"));
67073
+ const reply = asRecord6(await this.#transport.request("bridge.ping"));
67031
67074
  this.#recordBridgeCapabilities(reply.capabilities);
67032
67075
  this.#connection = "connected";
67033
67076
  } catch (err) {
@@ -67114,7 +67157,7 @@ class BridgeSessionSeam {
67114
67157
  this.#replayDrainPending = true;
67115
67158
  let opened;
67116
67159
  try {
67117
- opened = asRecord5(await this.#transport.request("session.open", { mode: "resume", id: sessionId }));
67160
+ opened = asRecord6(await this.#transport.request("session.open", { mode: "resume", id: sessionId }));
67118
67161
  } catch (err) {
67119
67162
  const code = err instanceof BridgeProtocolError ? err.code : "SESSION_OPEN_FAILED";
67120
67163
  const message = err instanceof Error ? err.message : String(err);
@@ -67124,7 +67167,7 @@ class BridgeSessionSeam {
67124
67167
  this.#bufferedPendingSnapshot = undefined;
67125
67168
  this.#replayDrainPending = false;
67126
67169
  this.#settleSuspendedTurn();
67127
- const errorDetail = err instanceof BridgeProtocolError ? asRecord5(err.detail) : {};
67170
+ const errorDetail = err instanceof BridgeProtocolError ? asRecord6(err.detail) : {};
67128
67171
  const holder = typeof errorDetail.holder === "string" && errorDetail.holder.trim() !== "" ? errorDetail.holder : undefined;
67129
67172
  const result = {
67130
67173
  state: "locked",
@@ -67199,7 +67242,7 @@ class BridgeSessionSeam {
67199
67242
  turnId: dead.turnId,
67200
67243
  seq: terminal.seq,
67201
67244
  terminalType: terminal.type,
67202
- reason: asRecord5(terminal.payload).reason,
67245
+ reason: asRecord6(terminal.payload).reason,
67203
67246
  payload: terminal.payload,
67204
67247
  source: "journal"
67205
67248
  }
@@ -67233,6 +67276,11 @@ class BridgeSessionSeam {
67233
67276
  this.#connection = "connected";
67234
67277
  this.#bridgeLink = "ready";
67235
67278
  this.#recoveryState = "attached";
67279
+ for (const [key, status] of this.#capPushStatus) {
67280
+ if (status.sessionId !== boundId)
67281
+ continue;
67282
+ this.#capPushStatus.set(key, { ...status, state: "attached", lastSeq: 0 });
67283
+ }
67236
67284
  const result = {
67237
67285
  state: "attached",
67238
67286
  sessionId: boundId,
@@ -67252,7 +67300,7 @@ class BridgeSessionSeam {
67252
67300
  const seen = new Set;
67253
67301
  const collected = [];
67254
67302
  for (;; ) {
67255
- const value = asRecord5(await this.#transport.request("journal.replay", { sessionId, from }));
67303
+ const value = asRecord6(await this.#transport.request("journal.replay", { sessionId, from }));
67256
67304
  const rawRows = Array.isArray(value.rows) ? value.rows : [];
67257
67305
  if (typeof value.cursor === "number" && Number.isFinite(value.cursor))
67258
67306
  cursor = value.cursor;
@@ -67265,7 +67313,7 @@ class BridgeSessionSeam {
67265
67313
  let added = 0;
67266
67314
  let pageMax = from - 1;
67267
67315
  for (const raw of rawRows) {
67268
- const row = asRecord5(raw);
67316
+ const row = asRecord6(raw);
67269
67317
  const seq = row.seq;
67270
67318
  if (typeof seq !== "number" || !Number.isFinite(seq) || seq < floor || seen.has(seq))
67271
67319
  continue;
@@ -67314,7 +67362,7 @@ class BridgeSessionSeam {
67314
67362
  };
67315
67363
  const attempt = (remaining) => {
67316
67364
  this.#transport.request("turn.abort", { turnId }).then((result) => {
67317
- if (asRecord5(result).noop === true) {
67365
+ if (asRecord6(result).noop === true) {
67318
67366
  fail(`turn.abort was a noop for turn ${turnId}; turn may still be running`, "TURN_ABORT_NOOP");
67319
67367
  }
67320
67368
  }).catch((err) => {
@@ -67450,7 +67498,7 @@ class BridgeSessionSeam {
67450
67498
  stats.contextTokens = usage.total;
67451
67499
  }
67452
67500
  } else if (row.type === "request/context") {
67453
- const data = asRecord5(row.payload);
67501
+ const data = asRecord6(row.payload);
67454
67502
  const window = data.contextWindow;
67455
67503
  if (typeof window === "number" && Number.isFinite(window) && window > 0) {
67456
67504
  const provider = typeof data.provider === "string" ? data.provider : "";
@@ -67501,6 +67549,49 @@ class BridgeSessionSeam {
67501
67549
  contextWindow: this.#liveContextWindow()
67502
67550
  };
67503
67551
  }
67552
+ onCapPush(sessionId, listener) {
67553
+ let set = this.#capPushListeners.get(sessionId);
67554
+ if (set === undefined) {
67555
+ set = new Set;
67556
+ this.#capPushListeners.set(sessionId, set);
67557
+ }
67558
+ set.add(listener);
67559
+ return () => {
67560
+ const current = this.#capPushListeners.get(sessionId);
67561
+ if (current === undefined)
67562
+ return;
67563
+ current.delete(listener);
67564
+ if (current.size === 0)
67565
+ this.#capPushListeners.delete(sessionId);
67566
+ };
67567
+ }
67568
+ capPushStatus(sessionId) {
67569
+ let seen = false;
67570
+ let state = "attached";
67571
+ let lastSeq = 0;
67572
+ for (const status of this.#capPushStatus.values()) {
67573
+ if (status.sessionId !== sessionId)
67574
+ continue;
67575
+ seen = true;
67576
+ lastSeq = Math.max(lastSeq, status.lastSeq);
67577
+ if (status.state === "disconnected")
67578
+ state = "disconnected";
67579
+ else if (status.state === "degraded" && state === "attached")
67580
+ state = "degraded";
67581
+ }
67582
+ return seen ? { sessionId, state, lastSeq } : undefined;
67583
+ }
67584
+ capPushDropCount(sessionId, methodId) {
67585
+ if (methodId !== undefined) {
67586
+ return this.#capPushDrops.get(`${sessionId}|${methodId}`)?.count ?? 0;
67587
+ }
67588
+ let total = 0;
67589
+ for (const drop of this.#capPushDrops.values()) {
67590
+ if (drop.sessionId === sessionId)
67591
+ total += drop.count;
67592
+ }
67593
+ return total;
67594
+ }
67504
67595
  onSessionEvent(listener) {
67505
67596
  this.#degradeOnce("onSessionEvent", "only turn.* lifecycle/error events project; permission.asked / bridge.shutdown absent");
67506
67597
  this.#listeners.push(listener);
@@ -67523,7 +67614,7 @@ class BridgeSessionSeam {
67523
67614
  this.#interruptInFlight.set(childId, generation);
67524
67615
  let value;
67525
67616
  try {
67526
- value = asRecord5(await this.#transport.request("subagents.interrupt", { parentSessionId, childId }));
67617
+ value = asRecord6(await this.#transport.request("subagents.interrupt", { parentSessionId, childId }));
67527
67618
  } catch (err) {
67528
67619
  if (this.#interruptInFlight.get(childId) === generation)
67529
67620
  this.#interruptInFlight.delete(childId);
@@ -67549,13 +67640,13 @@ class BridgeSessionSeam {
67549
67640
  if (parentSessionId === undefined || parentSessionId === "") {
67550
67641
  throw new BridgeProtocolError("NO_SESSION", "cannot stop children: no session is bound to this bridge connection");
67551
67642
  }
67552
- const value = asRecord5(await this.#transport.request("subagents.stopChildren", { parentSessionId }));
67643
+ const value = asRecord6(await this.#transport.request("subagents.stopChildren", { parentSessionId }));
67553
67644
  const children = value.children;
67554
67645
  if (!Array.isArray(children))
67555
67646
  return [];
67556
67647
  const sessionAtStart = this.#subagentSessionId;
67557
67648
  const rows = children.map((row) => {
67558
- const r = asRecord5(row);
67649
+ const r = asRecord6(row);
67559
67650
  return {
67560
67651
  childId: typeof r.childId === "string" ? r.childId : "",
67561
67652
  disposition: typeof r.disposition === "string" ? r.disposition : "failed"
@@ -67581,10 +67672,10 @@ class BridgeSessionSeam {
67581
67672
  return;
67582
67673
  let stopped = false;
67583
67674
  try {
67584
- const items = asRecord5(await this.#transport.request("session.list", { _request: {} })).items;
67675
+ const items = asRecord6(await this.#transport.request("session.list", { _request: {} })).items;
67585
67676
  if (Array.isArray(items)) {
67586
67677
  stopped = items.some((row) => {
67587
- const item = asRecord5(row);
67678
+ const item = asRecord6(row);
67588
67679
  return item.sessionId === childId && item.running === false;
67589
67680
  });
67590
67681
  }
@@ -67594,7 +67685,7 @@ class BridgeSessionSeam {
67594
67685
  if (stopped) {
67595
67686
  let reason = "aborted";
67596
67687
  try {
67597
- const rows = asRecord5(await this.#transport.request("journal.replay", { sessionId: childId })).rows;
67688
+ const rows = asRecord6(await this.#transport.request("journal.replay", { sessionId: childId })).rows;
67598
67689
  if (Array.isArray(rows)) {
67599
67690
  const clean = rows.filter((row) => row !== null && typeof row === "object" && !Array.isArray(row));
67600
67691
  reason = bridgeChildStopReason(clean) ?? "aborted";
@@ -67653,7 +67744,7 @@ class BridgeSessionSeam {
67653
67744
  } catch {
67654
67745
  return;
67655
67746
  }
67656
- const items = asRecord5(value).items;
67747
+ const items = asRecord6(value).items;
67657
67748
  if (!Array.isArray(items))
67658
67749
  return;
67659
67750
  const locallyRunning = new Set;
@@ -67698,7 +67789,7 @@ class BridgeSessionSeam {
67698
67789
  this.#subagentJournalLoaded.add(key);
67699
67790
  const sessionAtStart = this.#subagentSessionId;
67700
67791
  try {
67701
- const value = asRecord5(await this.#transport.request("journal.replay", { sessionId: childId }));
67792
+ const value = asRecord6(await this.#transport.request("journal.replay", { sessionId: childId }));
67702
67793
  const rows = value.rows;
67703
67794
  if (!Array.isArray(rows))
67704
67795
  return;
@@ -67804,7 +67895,7 @@ class BridgeSessionSeam {
67804
67895
  }
67805
67896
  }
67806
67897
  #foldAgentFrame(frame) {
67807
- const payload = asRecord5(frame.payload);
67898
+ const payload = asRecord6(frame.payload);
67808
67899
  const frameSession = typeof payload.sessionId === "string" ? payload.sessionId : "";
67809
67900
  if (this.#subagentSessionId !== undefined && frameSession !== "" && frameSession !== this.#subagentSessionId)
67810
67901
  return;
@@ -67840,7 +67931,7 @@ class BridgeSessionSeam {
67840
67931
  let changed = false;
67841
67932
  const now = Date.now();
67842
67933
  for (const row of rows) {
67843
- if (this.#foldWithFrozenSettle(row.type, asRecord5(row.payload), now, false))
67934
+ if (this.#foldWithFrozenSettle(row.type, asRecord6(row.payload), now, false))
67844
67935
  changed = true;
67845
67936
  }
67846
67937
  if (rosterReset || changed) {
@@ -67849,16 +67940,16 @@ class BridgeSessionSeam {
67849
67940
  }
67850
67941
  }
67851
67942
  configLoad() {
67852
- this.#degradeOnce("configLoad", "no config frame on the in-process bridge; returning {} (no stored override)");
67853
- return {};
67943
+ return this.#configStore.configLoad();
67854
67944
  }
67855
67945
  configRaw() {
67856
- this.#degradeOnce("configRaw", "no config frame on the in-process bridge; returning {} (no profile layer)");
67857
- return {};
67946
+ return this.#configStore.configRaw();
67858
67947
  }
67859
67948
  workspaceConfig() {
67860
- this.#degradeOnce("workspaceConfig", "no config frame on the in-process bridge; returning {} (no workspace overlay)");
67861
- return {};
67949
+ return this.#configStore.workspaceConfig();
67950
+ }
67951
+ configSave(patch) {
67952
+ return this.#configStore.configSave(patch);
67862
67953
  }
67863
67954
  async permissionCatalog() {
67864
67955
  const answererReady = this.#askProvider !== undefined || this.#inFlightGeneration !== 0 && this.#activeCallbacks !== undefined || this.#askFrameSeen;
@@ -67874,11 +67965,11 @@ class BridgeSessionSeam {
67874
67965
  }
67875
67966
  async listSessions(limit) {
67876
67967
  const value = await this.#transport.request("session.list");
67877
- return projectBridgeSessionList(asRecord5(value).items, limit);
67968
+ return projectBridgeSessionList(asRecord6(value).items, limit);
67878
67969
  }
67879
67970
  async storedTranscript(id, skip = 0) {
67880
67971
  const value = await this.#transport.request("journal.replay", { sessionId: id });
67881
- const rows = Array.isArray(asRecord5(value).rows) ? asRecord5(value).rows : [];
67972
+ const rows = Array.isArray(asRecord6(value).rows) ? asRecord6(value).rows : [];
67882
67973
  this.#foldAgentReplayRows(rows, id);
67883
67974
  this.#sweepSubagents(id);
67884
67975
  return bridgeReplayRowsToSeamTranscript(rows, skip);
@@ -67887,7 +67978,7 @@ class BridgeSessionSeam {
67887
67978
  const selection = await this.#transport.request("model.currentSelection");
67888
67979
  if (selection === undefined || selection === null)
67889
67980
  return;
67890
- const s = asRecord5(selection);
67981
+ const s = asRecord6(selection);
67891
67982
  const providerID = typeof s.provider === "string" ? s.provider : "";
67892
67983
  const modelID = typeof s.model === "string" ? s.model : "";
67893
67984
  if (!providerID || !modelID)
@@ -67924,7 +68015,7 @@ class BridgeSessionSeam {
67924
68015
  this.#pendingOpen = undefined;
67925
68016
  const params = pending.mode === "resume" ? { mode: "resume", id: pending.id, ...this.#sessionAttached ? { replace: true } : {} } : { mode: "new", ...this.#sessionAttached ? { replace: true } : {} };
67926
68017
  try {
67927
- const opened = asRecord5(await this.#transport.request("session.open", params));
68018
+ const opened = asRecord6(await this.#transport.request("session.open", params));
67928
68019
  if (typeof opened.sessionId === "string")
67929
68020
  this.#currentSessionId = opened.sessionId;
67930
68021
  if (this.#lastAppliedSessionId !== this.#currentSessionId) {
@@ -67941,7 +68032,7 @@ class BridgeSessionSeam {
67941
68032
  const done = new Promise((resolve) => {
67942
68033
  this.#turnDone = resolve;
67943
68034
  });
67944
- const sent = asRecord5(await this.#transport.request("session.send", { text: userText }));
68035
+ const sent = asRecord6(await this.#transport.request("session.send", { text: userText }));
67945
68036
  if (typeof sent.turnId === "string") {
67946
68037
  this.#inFlightTurnId = sent.turnId;
67947
68038
  this.#emitEvent({
@@ -68027,10 +68118,35 @@ class BridgeSessionSeam {
68027
68118
  return unsupported("listProviders");
68028
68119
  }
68029
68120
  async modelCatalog(_force) {
68030
- return unsupported("modelCatalog");
68121
+ const raw = await this.#transport.request("modelCatalog");
68122
+ if (raw === undefined || raw === null || !Array.isArray(raw.groups)) {
68123
+ return unsupported("modelCatalog");
68124
+ }
68125
+ const rows = [];
68126
+ for (const group of raw.groups) {
68127
+ const providerID = typeof group?.id === "string" ? group.id : "";
68128
+ if (!providerID)
68129
+ continue;
68130
+ for (const model of Array.isArray(group.models) ? group.models : []) {
68131
+ const modelID = typeof model?.id === "string" ? model.id : "";
68132
+ if (modelID)
68133
+ rows.push({ providerID, modelID });
68134
+ }
68135
+ }
68136
+ return rows;
68031
68137
  }
68032
- selectModel(_providerID, _modelID) {
68033
- return Promise.reject(new BridgeProtocolError("UNSUPPORTED", "selectModel is not backed by the in-process bridge", { capability: "selectModel" }));
68138
+ selectModel(providerID, modelID) {
68139
+ const sessionId = this.#currentSessionId ?? this.stagedSessionId();
68140
+ return this.#transport.request("selectModel", {
68141
+ provider: providerID,
68142
+ model: modelID,
68143
+ ...sessionId !== undefined && sessionId !== "" ? { sessionId } : {}
68144
+ }).then((reply) => {
68145
+ const r = reply;
68146
+ if (r === undefined || r === null || r.selected === undefined) {
68147
+ return unsupported("selectModel");
68148
+ }
68149
+ });
68034
68150
  }
68035
68151
  #approvalParams(request, verdict) {
68036
68152
  const base = { eventId: request.eventId, kind: "approval" };
@@ -68157,7 +68273,7 @@ class BridgeSessionSeam {
68157
68273
  this.#settlePendingAsk(eventId);
68158
68274
  }
68159
68275
  #onAskEvent(frame) {
68160
- const payload = asRecord5(frame.payload);
68276
+ const payload = asRecord6(frame.payload);
68161
68277
  if (frame.type === "ask.request" || frame.type === "ask.pending")
68162
68278
  this.#askFrameSeen = true;
68163
68279
  switch (frame.type) {
@@ -68214,9 +68330,60 @@ class BridgeSessionSeam {
68214
68330
  this.#degradedOnce.add(member);
68215
68331
  this.#degrade(member, reason);
68216
68332
  }
68333
+ #onCapPushEvent(frame) {
68334
+ if (frame.type !== "cap.event" && frame.type !== "cap.end")
68335
+ return false;
68336
+ const payload = asRecord6(frame.payload);
68337
+ const sessionId = optionalStringField(payload, "sessionId");
68338
+ if (sessionId === undefined || sessionId === "")
68339
+ return true;
68340
+ const methodId = optionalStringField(payload, "methodId") ?? "unknown";
68341
+ const key = `${sessionId}|${methodId}`;
68342
+ if (frame.type === "cap.end") {
68343
+ const current = this.#capPushStatus.get(key);
68344
+ this.#capPushStatus.set(key, {
68345
+ sessionId,
68346
+ methodId,
68347
+ state: "degraded",
68348
+ lastSeq: current?.lastSeq ?? 0
68349
+ });
68350
+ const code = optionalStringField(payload, "code");
68351
+ this.#degradeOnce("cap.end", `push stream ${methodId} ended for ${sessionId}${code === undefined ? "" : ` (code=${code})`}`);
68352
+ return true;
68353
+ }
68354
+ const seq = typeof payload.seq === "number" && Number.isInteger(payload.seq) ? payload.seq : 0;
68355
+ const current = this.#capPushStatus.get(key) ?? {
68356
+ sessionId,
68357
+ methodId,
68358
+ state: "attached",
68359
+ lastSeq: 0
68360
+ };
68361
+ if (seq <= current.lastSeq) {
68362
+ const drop = this.#capPushDrops.get(key) ?? { sessionId, methodId, count: 0 };
68363
+ drop.count += 1;
68364
+ this.#capPushDrops.set(key, drop);
68365
+ return true;
68366
+ }
68367
+ const status = { ...current, lastSeq: seq };
68368
+ this.#capPushStatus.set(key, status);
68369
+ const event = {
68370
+ methodId,
68371
+ sessionId,
68372
+ seq,
68373
+ eventType: optionalStringField(payload, "eventType") ?? "event"
68374
+ };
68375
+ for (const listener of [...this.#capPushListeners.get(sessionId) ?? []]) {
68376
+ try {
68377
+ listener(event);
68378
+ } catch {}
68379
+ }
68380
+ return true;
68381
+ }
68217
68382
  #onBridgeEvent(frame) {
68218
68383
  if (this.#onAskEvent(frame))
68219
68384
  return;
68385
+ if (this.#onCapPushEvent(frame))
68386
+ return;
68220
68387
  if (frame.type === "agent.spawn" || frame.type === "agent.settle") {
68221
68388
  this.#foldAgentFrame(frame);
68222
68389
  return;
@@ -68229,6 +68396,9 @@ class BridgeSessionSeam {
68229
68396
  this.#bridgeLink = "dead";
68230
68397
  this.#connection = "disconnected";
68231
68398
  this.#turn = "idle";
68399
+ for (const [key, status] of this.#capPushStatus) {
68400
+ this.#capPushStatus.set(key, { ...status, state: "disconnected" });
68401
+ }
68232
68402
  this.#onDead?.(cause);
68233
68403
  for (const listener of [...this.#listeners]) {
68234
68404
  try {
@@ -68237,7 +68407,7 @@ class BridgeSessionSeam {
68237
68407
  }
68238
68408
  return;
68239
68409
  }
68240
- const payload = asRecord5(frame.payload);
68410
+ const payload = asRecord6(frame.payload);
68241
68411
  if (frame.type === "turn.start") {
68242
68412
  this.#turn = "starting";
68243
68413
  this.#decodeWindowStart = undefined;
@@ -68321,8 +68491,11 @@ class BridgeSessionSeam {
68321
68491
  var BridgeProtocolError, BRIDGE_AGENT_START = "tool-workflow/agent-start", BRIDGE_AGENT_END = "tool-workflow/agent-end", BRIDGE_SUBAGENT_CATALOG = "subagent/catalog", BRIDGE_SUBAGENT_SETTLED = "subagent-settled", BRIDGE_CATALOG_RUN_PREFIX = "catalog:", CONFIRM_POLL_INITIAL_MS = 250, CONFIRM_POLL_MAX_MS = 1000, CONFIRM_TIMEOUT_MS = 45000, fmtTokens = (n) => n >= 1000 ? `${(n / 1000).toFixed(1)}k` : `${n}`;
68322
68492
  var init_bridge_session_seam = __esm(() => {
68323
68493
  init_remote_session_ops();
68324
- init_session_seam_adapter();
68494
+ init_journal_projection();
68325
68495
  init_loop();
68496
+ init_local_config_faces();
68497
+ init_remote_local_fs();
68498
+ init_lifecycle();
68326
68499
  BridgeProtocolError = class BridgeProtocolError extends Error {
68327
68500
  code;
68328
68501
  detail;
@@ -68341,10 +68514,9 @@ function formatBridgeFailFastMessage(diagnosis, repairCommand = BRIDGE_REPAIR_CO
68341
68514
  return [diagnosis, `Fix: ${repairCommand}`, BRIDGE_APPEND_PRESET_NOTICE].join(`
68342
68515
  `);
68343
68516
  }
68344
- var BRIDGE_REPAIR_COMMAND = "dsh-opentui --repair-bridge", BRIDGE_APPEND_PRESET_NOTICE = "inproc bridge mode injects append-system via the bridge section; presets are standard only.", BRIDGE_LEGACY_REMOTE_HINT = "To keep the legacy remote thin client for this launch: DSH_OPENTUI_INPROC=0", BRIDGE_REPAIR_HINT;
68517
+ var BRIDGE_REPAIR_COMMAND = "dsh-opentui --repair-bridge", BRIDGE_APPEND_PRESET_NOTICE = "inproc bridge mode injects append-system via the bridge section; presets are standard only.", BRIDGE_REPAIR_HINT;
68345
68518
  var init_bridge_failfast_text = __esm(() => {
68346
- BRIDGE_REPAIR_HINT = `Run \`${BRIDGE_REPAIR_COMMAND}\` to rebuild the bridge symlink / manifest (it fixes links, not corrupted artifact contents).
68347
- ${BRIDGE_LEGACY_REMOTE_HINT}`;
68519
+ BRIDGE_REPAIR_HINT = `Run \`${BRIDGE_REPAIR_COMMAND}\` to rebuild the bridge manifest (it fixes links, not corrupted artifact contents).`;
68348
68520
  });
68349
68521
 
68350
68522
  // scripts/lib/host-compat.mjs
@@ -68418,22 +68590,13 @@ __export(exports_seam_bootstrap, {
68418
68590
  BRIDGE_REPAIR_HINT: () => BRIDGE_REPAIR_HINT,
68419
68591
  BridgeBootstrapError: () => BridgeBootstrapError,
68420
68592
  createBridgeSessionSeam: () => createBridgeSessionSeam,
68421
- createSessionSeam: () => createSessionSeam,
68422
68593
  formatBridgeBootstrapMessage: () => formatBridgeBootstrapMessage,
68423
68594
  formatDeadNotice: () => formatDeadNotice,
68424
- isInprocMode: () => isInprocMode,
68425
68595
  recoverBridgeSession: () => recoverBridgeSession,
68426
- selectSeamKind: () => selectSeamKind,
68427
68596
  toBridgeBootstrapError: () => toBridgeBootstrapError,
68428
68597
  verifyBridgeFingerprint: () => verifyBridgeFingerprint,
68429
68598
  verifyRecoveryHandshake: () => verifyRecoveryHandshake
68430
68599
  });
68431
- function selectSeamKind(input) {
68432
- return input.inproc ? "bridge" : "remote";
68433
- }
68434
- function isInprocMode(env = process.env) {
68435
- return env.DSH_OPENTUI_INPROC !== "0";
68436
- }
68437
68600
  function formatBridgeBootstrapMessage(options) {
68438
68601
  return formatBridgeFailFastMessage(`dsh-opentui inproc bridge seam failed [${options.code}]: ${options.diagnosis}`, options.repairCommand ?? BRIDGE_REPAIR_COMMAND);
68439
68602
  }
@@ -68450,11 +68613,11 @@ function toBridgeBootstrapError(err, fallbackCode = "BRIDGE_HANDSHAKE_FAILED") {
68450
68613
  const message = err instanceof Error ? err.message : String(err);
68451
68614
  return new BridgeBootstrapError({ code: fallbackCode, diagnosis: `bridge handshake failed: ${message}` });
68452
68615
  }
68453
- function asRecord6(value) {
68616
+ function asRecord7(value) {
68454
68617
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
68455
68618
  }
68456
68619
  function verifyBridgeFingerprint(hello, expectedProtocolVersion = BRIDGE_PROTOCOL_VERSION) {
68457
- const h = asRecord6(hello);
68620
+ const h = asRecord7(hello);
68458
68621
  const protocolVersion = h.protocolVersion;
68459
68622
  if (protocolVersion !== expectedProtocolVersion) {
68460
68623
  throw new BridgeBootstrapError({
@@ -68532,11 +68695,6 @@ async function createBridgeSessionSeam(options) {
68532
68695
  await seam.connect();
68533
68696
  return seam;
68534
68697
  }
68535
- async function createSessionSeam(options) {
68536
- if (options.kind === "remote")
68537
- return options.createRemote();
68538
- return options.createBridge();
68539
- }
68540
68698
  async function recoverBridgeSession(options) {
68541
68699
  await options.transport.recover();
68542
68700
  return options.seam.recoverSession();
@@ -68562,31 +68720,30 @@ var init_seam_bootstrap = __esm(() => {
68562
68720
  });
68563
68721
 
68564
68722
  // ../tui-base/examples/v2-entry.tsx
68565
- import { join as join15 } from "path";
68566
- import { existsSync as existsSync12 } from "fs";
68723
+ import { join as join16 } from "path";
68724
+ import { existsSync as existsSync13 } from "fs";
68567
68725
  function resolveWatchdogScript() {
68568
68726
  const candidates = [
68569
- join15(import.meta.dir, "..", "watchdog.mjs"),
68570
- join15(import.meta.dir, "..", "..", "shell", "dist", "watchdog.mjs"),
68571
- join15(import.meta.dir, "..", "..", "..", "shell", "dist", "watchdog.mjs")
68727
+ join16(import.meta.dir, "..", "watchdog.mjs"),
68728
+ join16(import.meta.dir, "..", "..", "shell", "dist", "watchdog.mjs"),
68729
+ join16(import.meta.dir, "..", "..", "..", "shell", "dist", "watchdog.mjs")
68572
68730
  ];
68573
68731
  for (const candidate of candidates)
68574
- if (existsSync12(candidate))
68732
+ if (existsSync13(candidate))
68575
68733
  return candidate;
68576
68734
  return null;
68577
68735
  }
68578
68736
  async function loadShell() {
68579
- const [shared, lifecycle, clifecycle, transport, rhs, adapter, git, seamBootstrap] = await Promise.all([
68737
+ const [shared, lifecycle, clifecycle, transport, rhs, git, seamBootstrap] = await Promise.all([
68580
68738
  Promise.resolve().then(() => (init_boot_shared(), exports_boot_shared)),
68581
68739
  Promise.resolve().then(() => (init_lifecycle(), exports_lifecycle)),
68582
68740
  Promise.resolve().then(() => (init_client_lifecycle(), exports_client_lifecycle)),
68583
68741
  Promise.resolve().then(() => (init_transport(), exports_transport)),
68584
68742
  Promise.resolve().then(() => (init_remote_host_session(), exports_remote_host_session)),
68585
- Promise.resolve().then(() => (init_session_seam_adapter(), exports_session_seam_adapter)),
68586
68743
  Promise.resolve().then(() => (init_remote_git(), exports_remote_git)),
68587
68744
  Promise.resolve().then(() => (init_seam_bootstrap(), exports_seam_bootstrap))
68588
68745
  ]);
68589
- return { shared, lifecycle, clifecycle, transport, rhs, adapter, git, seamBootstrap };
68746
+ return { shared, lifecycle, clifecycle, transport, rhs, git, seamBootstrap };
68590
68747
  }
68591
68748
  function V2SessionPage(props) {
68592
68749
  return createComponent2(DockProvider, {
@@ -68618,7 +68775,7 @@ function V2SessionPageBody(props) {
68618
68775
  }
68619
68776
  });
68620
68777
  const dialog = useDialog();
68621
- const pageOwns = useIsPageOwner();
68778
+ const pageOwns = useIsPageOwner2();
68622
68779
  const dock = useDock();
68623
68780
  const theme = useTheme();
68624
68781
  const themeService = useThemes();
@@ -69291,7 +69448,7 @@ function appendDiagnostic(line) {
69291
69448
  } catch {}
69292
69449
  }
69293
69450
  async function bootClientV2(options = {}) {
69294
- const { shared, lifecycle, clifecycle, transport, rhs, adapter, git, seamBootstrap } = await loadShell();
69451
+ const { shared, lifecycle, clifecycle, transport, rhs, git, seamBootstrap } = await loadShell();
69295
69452
  const workspace = process.cwd();
69296
69453
  const profile = lifecycle.DEFAULT_PROFILE;
69297
69454
  const idleExitMs = lifecycle.resolveIdleExitMs();
@@ -69340,31 +69497,22 @@ async function bootClientV2(options = {}) {
69340
69497
  }
69341
69498
  }
69342
69499
  const launchArgs = parseLaunchArgs(options.argv ?? process.argv.slice(2));
69343
- const seamKind = seamBootstrap.selectSeamKind({
69344
- inproc: seamBootstrap.isInprocMode()
69345
- });
69346
- const seam = await seamBootstrap.createSessionSeam({
69347
- kind: seamKind,
69348
- createBridge: async () => {
69349
- if (options.bridgeTransport === undefined) {
69350
- throw new seamBootstrap.BridgeBootstrapError({
69351
- code: "BRIDGE_TRANSPORT_MISSING",
69352
- diagnosis: "bridge seam is selected (DSH_OPENTUI_INPROC is not 0) but no bridge transport was injected at the synthetic root"
69353
- });
69354
- }
69355
- return seamBootstrap.createBridgeSessionSeam({
69356
- transport: options.bridgeTransport,
69357
- ctx: options.bridgeCtx ?? { logger: console },
69358
- onDead: (cause) => void showNotice(`${seamBootstrap.formatDeadNotice(cause)} \xB7 ${t("recovery.action.reconnect")}`, undefined, "error"),
69359
- onPermissionUnavailable: (reason) => void showNotice(`${t("notice.permission.unavailable")} \xB7 ${t(`notice.permission.reason.${reason}`)}`, undefined, "error")
69360
- });
69361
- },
69362
- createRemote: () => new adapter.RemoteSessionSeam(session)
69500
+ if (options.bridgeTransport === undefined) {
69501
+ throw new seamBootstrap.BridgeBootstrapError({
69502
+ code: "BRIDGE_TRANSPORT_MISSING",
69503
+ diagnosis: "no bridge transport was injected at the synthetic root"
69504
+ });
69505
+ }
69506
+ const seam = await seamBootstrap.createBridgeSessionSeam({
69507
+ transport: options.bridgeTransport,
69508
+ ctx: options.bridgeCtx ?? { logger: console },
69509
+ onDead: (cause) => void showNotice(`${seamBootstrap.formatDeadNotice(cause)} \xB7 ${t("recovery.action.reconnect")}`, undefined, "error"),
69510
+ onPermissionUnavailable: (reason) => void showNotice(`${t("notice.permission.unavailable")} \xB7 ${t(`notice.permission.reason.${reason}`)}`, undefined, "error")
69363
69511
  });
69364
- const recoverBridge = seamKind === "bridge" && options.bridgeTransport !== undefined ? () => seamBootstrap.recoverBridgeSession({
69512
+ const recoverBridge = () => seamBootstrap.recoverBridgeSession({
69365
69513
  transport: options.bridgeTransport,
69366
69514
  seam
69367
- }) : undefined;
69515
+ });
69368
69516
  registerTurnOverlays(seam, overlays, {
69369
69517
  deadReason: (details) => {
69370
69518
  const cause = details;
@@ -69395,8 +69543,8 @@ async function bootClientV2(options = {}) {
69395
69543
  agentsHome: agentsHomeForSkills
69396
69544
  });
69397
69545
  const skillsManagerRoots = {
69398
- source: join15(agentsHomeForSkills, "skills"),
69399
- curated: join15(host.dshHome, "skills")
69546
+ source: join16(agentsHomeForSkills, "skills"),
69547
+ curated: join16(host.dshHome, "skills")
69400
69548
  };
69401
69549
  const envTheme = process.env[shared.ENV_THEME];
69402
69550
  const workspaceConfig = seam.workspaceConfig?.() ?? {};
@@ -69435,12 +69583,10 @@ async function bootClientV2(options = {}) {
69435
69583
  try {
69436
69584
  await Promise.race([session.dispose(), new Promise((resolve) => setTimeout(resolve, shared.SHUTDOWN_GRACE_MS))]);
69437
69585
  } catch {}
69438
- if (seamKind === "bridge") {
69439
- try {
69440
- await Promise.race([seam.dispose(), new Promise((resolve) => setTimeout(resolve, shared.SHUTDOWN_GRACE_MS))]);
69441
- } catch {}
69442
- options.bridgeTransport?.close?.();
69443
- }
69586
+ try {
69587
+ await Promise.race([seam.dispose(), new Promise((resolve) => setTimeout(resolve, shared.SHUTDOWN_GRACE_MS))]);
69588
+ } catch {}
69589
+ options.bridgeTransport?.close?.();
69444
69590
  if (clientHeartbeat) {
69445
69591
  clientHeartbeat.stop();
69446
69592
  clientHeartbeat.remove();
@@ -69472,7 +69618,7 @@ async function bootClientV2(options = {}) {
69472
69618
  get children() {
69473
69619
  return createComponent2(ClipboardHost, {
69474
69620
  get children() {
69475
- return createComponent2(InputOwnershipProvider, {
69621
+ return createComponent2(FocusRouterProvider, {
69476
69622
  get children() {
69477
69623
  return createComponent2(DialogProvider, {
69478
69624
  get children() {
@@ -69596,7 +69742,7 @@ var init_v2_entry = __esm(() => {
69596
69742
  init_keymap();
69597
69743
  init_theme3();
69598
69744
  init_panel_kit_host();
69599
- init_input_ownership();
69745
+ init_focus_router();
69600
69746
  init_config();
69601
69747
  init_selection();
69602
69748
  init_theme2();
@@ -69611,7 +69757,7 @@ var init_v2_entry = __esm(() => {
69611
69757
  // src/client/bridge-transport.ts
69612
69758
  import { spawn as nodeSpawn2 } from "child_process";
69613
69759
  import { homedir as homedir9 } from "os";
69614
- import { join as join16 } from "path";
69760
+ import { join as join17 } from "path";
69615
69761
  function recoveryCause(err, phase) {
69616
69762
  if (err instanceof BridgeBootstrapError) {
69617
69763
  return {
@@ -69624,7 +69770,7 @@ function recoveryCause(err, phase) {
69624
69770
  };
69625
69771
  }
69626
69772
  if (err instanceof BridgeProtocolError && err.code === "BRIDGE_DEAD") {
69627
- const detail = asRecord7(err.detail);
69773
+ const detail = asRecord8(err.detail);
69628
69774
  return {
69629
69775
  stage: phase,
69630
69776
  code: typeof detail.code === "number" ? detail.code : null,
@@ -69675,7 +69821,7 @@ class StdioBridgeTransport {
69675
69821
  #spawn() {
69676
69822
  if (this.#child !== undefined)
69677
69823
  return this.#child;
69678
- const dshHome = this.#opts.dshHome ?? process.env.DSH_HOME ?? join16(homedir9(), ".dsh");
69824
+ const dshHome = this.#opts.dshHome ?? process.env.DSH_HOME ?? join17(homedir9(), ".dsh");
69679
69825
  const env = {
69680
69826
  ...process.env,
69681
69827
  ...this.#opts.env ?? {},
@@ -69739,7 +69885,7 @@ class StdioBridgeTransport {
69739
69885
  } catch {
69740
69886
  return;
69741
69887
  }
69742
- const rec = asRecord7(frame);
69888
+ const rec = asRecord8(frame);
69743
69889
  if (typeof rec.id === "number") {
69744
69890
  const pending = this.#pending.get(rec.id);
69745
69891
  if (pending === undefined)
@@ -69751,7 +69897,7 @@ class StdioBridgeTransport {
69751
69897
  this.#setState("ready");
69752
69898
  pending.resolve(rec.result);
69753
69899
  } else {
69754
- const error = asRecord7(rec.error);
69900
+ const error = asRecord8(rec.error);
69755
69901
  pending.reject(new BridgeProtocolError(typeof error.code === "string" ? error.code : "BRIDGE_ERROR", typeof error.message === "string" ? error.message : "bridge request failed", error.detail));
69756
69902
  }
69757
69903
  return;
@@ -69883,7 +70029,7 @@ class StdioBridgeTransport {
69883
70029
  } catch {}
69884
70030
  }
69885
70031
  }
69886
- var asRecord7 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
70032
+ var asRecord8 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
69887
70033
  var init_bridge_transport = __esm(() => {
69888
70034
  init_bridge_session_seam();
69889
70035
  init_seam_bootstrap();
@@ -69896,16 +70042,16 @@ init_boot_shared();
69896
70042
  init_lifecycle();
69897
70043
  init_transport();
69898
70044
  init_remote_host_session();
69899
- import { existsSync as existsSync13 } from "fs";
69900
- import { join as join17 } from "path";
70045
+ import { existsSync as existsSync14 } from "fs";
70046
+ import { join as join18 } from "path";
69901
70047
  function resolveWatchdogScript2() {
69902
70048
  const candidates = [
69903
- join17(import.meta.dir, "..", "watchdog.mjs"),
69904
- join17(import.meta.dir, "..", "dist", "watchdog.mjs"),
69905
- join17(import.meta.dir, "..", "scripts", "watchdog.mjs")
70049
+ join18(import.meta.dir, "..", "watchdog.mjs"),
70050
+ join18(import.meta.dir, "..", "dist", "watchdog.mjs"),
70051
+ join18(import.meta.dir, "..", "scripts", "watchdog.mjs")
69906
70052
  ];
69907
70053
  for (const candidate of candidates) {
69908
- if (existsSync13(candidate))
70054
+ if (existsSync14(candidate))
69909
70055
  return candidate;
69910
70056
  }
69911
70057
  return null;
@@ -70050,16 +70196,12 @@ async function main() {
70050
70196
  const v2Specifier = "../../" + "tui-base/examples/v2-entry.tsx";
70051
70197
  const mod = await Promise.resolve().then(() => (init_v2_entry(), {}));
70052
70198
  const argv = process.argv.slice(2);
70053
- let bootOptions = { argv };
70054
- if (process.env.DSH_OPENTUI_INPROC !== "0") {
70055
- const bridgeMod = await Promise.resolve().then(() => (init_bridge_transport(), {}));
70056
- bootOptions = {
70057
- ...bootOptions,
70058
- bridgeTransport: new StdioBridgeTransport,
70059
- bridgeCtx: { logger: console }
70060
- };
70061
- }
70062
- await bootClientV2(bootOptions);
70199
+ const bridgeMod = await Promise.resolve().then(() => (init_bridge_transport(), {}));
70200
+ await bootClientV2({
70201
+ argv,
70202
+ bridgeTransport: new StdioBridgeTransport,
70203
+ bridgeCtx: { logger: console }
70204
+ });
70063
70205
  } catch (error) {
70064
70206
  const message = error instanceof Error ? error.stack ?? error.message : String(error);
70065
70207
  process.stderr.write(`dsh-opentui client boot failed: ${message}
@@ -70080,5 +70222,5 @@ export {
70080
70222
  themeNameFromConfig
70081
70223
  };
70082
70224
 
70083
- //# debugId=4EE49A8A419D300F64756E2164756E21
70225
+ //# debugId=02978B65DF730BBE64756E2164756E21
70084
70226
  //# sourceMappingURL=index.js.map