@aiwayds/dsh-opentui 0.21.1 → 0.23.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.
@@ -3773,7 +3773,7 @@ var init_lib = __esm(() => {
3773
3773
  })(Time || (Time = {}));
3774
3774
  });
3775
3775
 
3776
- // ../../node_modules/.pnpm/@deepseek-ai+cordis@4.1.0/node_modules/@deepseek-ai/cordis/lib/index.js
3776
+ // ../../node_modules/.pnpm/@deepseek-ai+cordis@4.1.0_@deepseek-ai+cordis-plugin-include@1.1.0_@deepseek-ai+cordis-plugin-loader@1.1.0/node_modules/@deepseek-ai/cordis/lib/index.js
3777
3777
  function isConstructor(func) {
3778
3778
  if (!func.prototype)
3779
3779
  return false;
@@ -13751,6 +13751,7 @@ class ComposerController {
13751
13751
  onPendingChange;
13752
13752
  onQueuePaused;
13753
13753
  isTurnAborted;
13754
+ disabled;
13754
13755
  busyState = false;
13755
13756
  pendingTurn;
13756
13757
  queueItems = [];
@@ -13765,6 +13766,7 @@ class ComposerController {
13765
13766
  this.onPendingChange = options.onPendingChange;
13766
13767
  this.onQueuePaused = options.onQueuePaused;
13767
13768
  this.isTurnAborted = options.isTurnAborted;
13769
+ this.disabled = options.disabled;
13768
13770
  this.history = options.history ?? new ComposerHistory;
13769
13771
  }
13770
13772
  get busy() {
@@ -13777,6 +13779,8 @@ class ComposerController {
13777
13779
  return this.queueItems.length;
13778
13780
  }
13779
13781
  submit(text) {
13782
+ if (this.disabled?.())
13783
+ return "ignored";
13780
13784
  const prompt = text.trim();
13781
13785
  if (!prompt)
13782
13786
  return "ignored";
@@ -13789,6 +13793,8 @@ class ComposerController {
13789
13793
  return "sent";
13790
13794
  }
13791
13795
  async submitWhileBusy(text) {
13796
+ if (this.disabled?.())
13797
+ return "ignored";
13792
13798
  const prompt = text.trim();
13793
13799
  if (!prompt)
13794
13800
  return "ignored";
@@ -34177,7 +34183,7 @@ var init_config = __esm(() => {
34177
34183
  description: "Prompt for permission requests or accept them automatically"
34178
34184
  }),
34179
34185
  activity_panel_height: optional2(Literals(["1", "5", "7", "10", "all"])).annotate({
34180
- description: "Activity panel height gear (U4): lines per think and tool block; 'all' grows the blocks freely while the whole frame never exceeds 2/3 of the terminal rows"
34186
+ description: "Think display lines in the activity panel: 1 / 5 / 7 / 10; 'all' is a legacy spelling equal to 10. The tool block is fixed and the panel never exceeds 10 lines"
34181
34187
  })
34182
34188
  })).annotate({
34183
34189
  description: "Session transcript presentation settings"
@@ -42072,6 +42078,7 @@ function SessionComposer(props) {
42072
42078
  onPendingChange: props.onPendingChange,
42073
42079
  onQueuePaused: props.onQueuePaused,
42074
42080
  isTurnAborted: props.isTurnAborted,
42081
+ disabled: props.disabled,
42075
42082
  onBusyChange: (value) => {
42076
42083
  if (disposed)
42077
42084
  return;
@@ -42113,6 +42120,8 @@ function SessionComposer(props) {
42113
42120
  const editor = textarea;
42114
42121
  if (!editor || editor.isDestroyed)
42115
42122
  return;
42123
+ if (props.disabled?.())
42124
+ return;
42116
42125
  if (props.interceptSubmit?.(editor.plainText, (text) => editor.setText(text))) {
42117
42126
  editor.setText("");
42118
42127
  syncHeight();
@@ -42334,7 +42343,7 @@ function SessionComposer(props) {
42334
42343
  footerRows: FOOTER_HEIGHT,
42335
42344
  paletteRows: props.slashHeight?.() ?? 0,
42336
42345
  terminalRows: dimensions().height
42337
- }).height, _v$2 = composerBorderSides(dimensions().height), _v$3 = border().borderStyle, _v$4 = border().borderColor, _v$5 = dimensions().height > COMPOSER_COMPACT_TERMINAL_ROWS ? props.frameTitle?.() || (busy() ? STEER_TITLE : undefined) : undefined, _v$6 = border().borderColor, _v$7 = color.background(), _v$8 = maxLines(), _v$9 = props.placeholder ?? t("composer.placeholder"), _v$0 = color.placeholder(), _v$1 = color.unfocusedText(), _v$10 = color.text(), _v$11 = busy() ? busyColor() : color.text(), _v$12 = cursor();
42346
+ }).height, _v$2 = composerBorderSides(dimensions().height), _v$3 = border().borderStyle, _v$4 = border().borderColor, _v$5 = dimensions().height > COMPOSER_COMPACT_TERMINAL_ROWS ? props.frameTitle?.() || (busy() ? STEER_TITLE : undefined) : undefined, _v$6 = border().borderColor, _v$7 = color.background(), _v$8 = maxLines(), _v$9 = props.disabled?.() ? props.disabledReason?.() ?? props.placeholder ?? t("composer.placeholder") : props.placeholder ?? t("composer.placeholder"), _v$0 = color.placeholder(), _v$1 = !props.disabled?.(), _v$10 = color.unfocusedText(), _v$11 = color.text(), _v$12 = busy() ? busyColor() : color.text(), _v$13 = cursor();
42338
42347
  _v$ !== _p$.e && (_p$.e = setProp(_el$, "height", _v$, _p$.e));
42339
42348
  _v$2 !== _p$.t && (_p$.t = setProp(_el$, "border", _v$2, _p$.t));
42340
42349
  _v$3 !== _p$.a && (_p$.a = setProp(_el$, "borderStyle", _v$3, _p$.a));
@@ -42345,10 +42354,11 @@ function SessionComposer(props) {
42345
42354
  _v$8 !== _p$.h && (_p$.h = setProp(_el$2, "maxHeight", _v$8, _p$.h));
42346
42355
  _v$9 !== _p$.r && (_p$.r = setProp(_el$2, "placeholder", _v$9, _p$.r));
42347
42356
  _v$0 !== _p$.d && (_p$.d = setProp(_el$2, "placeholderColor", _v$0, _p$.d));
42348
- _v$1 !== _p$.l && (_p$.l = setProp(_el$2, "textColor", _v$1, _p$.l));
42349
- _v$10 !== _p$.u && (_p$.u = setProp(_el$2, "focusedTextColor", _v$10, _p$.u));
42350
- _v$11 !== _p$.c && (_p$.c = setProp(_el$2, "cursorColor", _v$11, _p$.c));
42351
- _v$12 !== _p$.w && (_p$.w = setProp(_el$2, "cursorStyle", _v$12, _p$.w));
42357
+ _v$1 !== _p$.l && (_p$.l = setProp(_el$2, "showCursor", _v$1, _p$.l));
42358
+ _v$10 !== _p$.u && (_p$.u = setProp(_el$2, "textColor", _v$10, _p$.u));
42359
+ _v$11 !== _p$.c && (_p$.c = setProp(_el$2, "focusedTextColor", _v$11, _p$.c));
42360
+ _v$12 !== _p$.w && (_p$.w = setProp(_el$2, "cursorColor", _v$12, _p$.w));
42361
+ _v$13 !== _p$.m && (_p$.m = setProp(_el$2, "cursorStyle", _v$13, _p$.m));
42352
42362
  return _p$;
42353
42363
  }, {
42354
42364
  e: undefined,
@@ -42364,7 +42374,8 @@ function SessionComposer(props) {
42364
42374
  l: undefined,
42365
42375
  u: undefined,
42366
42376
  c: undefined,
42367
- w: undefined
42377
+ w: undefined,
42378
+ m: undefined
42368
42379
  });
42369
42380
  return _el$;
42370
42381
  })();
@@ -43609,6 +43620,18 @@ function isRecord4(value) {
43609
43620
  }
43610
43621
 
43611
43622
  // ../tui-base/src/util/error.ts
43623
+ function sessionLockedErrorText(error) {
43624
+ if (!isRecord4(error) || error.code !== "SESSION_LOCKED")
43625
+ return;
43626
+ const detail = isRecord4(error.detail) ? error.detail : undefined;
43627
+ const holderValue = detail?.holder;
43628
+ const holder = typeof holderValue === "string" && holderValue !== "" && holderValue !== "unknown" ? holderValue : undefined;
43629
+ if (holder === undefined)
43630
+ return t("error.sessionLockedNoHolder");
43631
+ const idValue = detail?.sessionId;
43632
+ const id = typeof idValue === "string" && idValue !== "" ? idValue : holder;
43633
+ return t("error.sessionLocked", { id, holder });
43634
+ }
43612
43635
  function errorFormat(error) {
43613
43636
  if (error instanceof Error) {
43614
43637
  return error.stack ?? `${error.name}: ${error.message}`;
@@ -43653,7 +43676,9 @@ function errorMessage(error) {
43653
43676
  return formatted;
43654
43677
  return "unknown error";
43655
43678
  }
43656
- var init_error = () => {};
43679
+ var init_error = __esm(() => {
43680
+ init_i18n();
43681
+ });
43657
43682
 
43658
43683
  // ../tui-base/src/ui/toast.tsx
43659
43684
  import { TextAttributes as TextAttributes2 } from "@opentui/core";
@@ -45694,7 +45719,11 @@ function parseLaunchArgs(argv) {
45694
45719
  sessionId = value;
45695
45720
  }
45696
45721
  }
45697
- return { newRequested, resumeLastRequested, ...sessionId !== undefined ? { sessionId } : {} };
45722
+ return {
45723
+ newRequested,
45724
+ resumeLastRequested,
45725
+ ...sessionId !== undefined ? { sessionId } : {}
45726
+ };
45698
45727
  }
45699
45728
  function readAutoResumeMode(config) {
45700
45729
  return config?.autoResume === "last" ? "last" : "off";
@@ -47937,7 +47966,9 @@ function createSeamRows(seam, sessionID, options) {
47937
47966
  if (event.type === "message.updated" && details.role === "user") {
47938
47967
  const id = typeof details.id === "string" ? details.id : `local-${++liveOrdinal}`;
47939
47968
  const text = typeof details.text === "string" ? details.text : "";
47940
- if (!turnOpen && pendingTurns.length > 0 && typeof details.sessionID === "string") {
47969
+ const journalKey = `user:${id}`;
47970
+ const isWire = typeof details.sessionID === "string";
47971
+ if (!turnOpen && pendingTurns.length > 0 && isWire) {
47941
47972
  const group = pendingTurns[0];
47942
47973
  const local = rows.find((row) => row.key === group.userKey);
47943
47974
  if (!local || local.kind !== "user" || local.text.trim() === text.trim()) {
@@ -47945,12 +47976,12 @@ function createSeamRows(seam, sessionID, options) {
47945
47976
  dropRows(new Set([group.userKey]));
47946
47977
  }
47947
47978
  }
47948
- upsert({
47949
- key: `user:${id}`,
47950
- kind: "user",
47951
- text,
47952
- final: true
47953
- });
47979
+ if (isWire && !rows.some((row) => row.key === journalKey)) {
47980
+ const optimistic = rows.find((row) => row.kind === "user" && row.seq === null && row.text.trim() === text.trim());
47981
+ if (optimistic !== undefined)
47982
+ dropRows(new Set([optimistic.key]));
47983
+ }
47984
+ upsert({ key: journalKey, kind: "user", text, final: true });
47954
47985
  return;
47955
47986
  }
47956
47987
  if (event.type === "message.part.updated") {
@@ -47991,6 +48022,37 @@ function createSeamRows(seam, sessionID, options) {
47991
48022
  });
47992
48023
  return;
47993
48024
  }
48025
+ if (event.type === "bridge.input.acked") {
48026
+ if (typeof details.sessionID === "string" && details.sessionID !== sessionID())
48027
+ return;
48028
+ const text = typeof details.text === "string" ? details.text.trim() : "";
48029
+ setRows(produce((draft) => {
48030
+ for (const row of draft) {
48031
+ if (row.kind === "user" && row.unconfirmed === true && row.key.startsWith("user:local") && row.text.trim() === text) {
48032
+ row.unconfirmed = false;
48033
+ break;
48034
+ }
48035
+ }
48036
+ }));
48037
+ return;
48038
+ }
48039
+ if (event.type === "bridge.turn.interrupted") {
48040
+ if (typeof details.sessionID === "string" && details.sessionID !== sessionID())
48041
+ return;
48042
+ const turnId = typeof details.turnId === "string" ? details.turnId : "";
48043
+ if (turnId === "")
48044
+ return;
48045
+ const reason = typeof details.reason === "string" ? details.reason : "interrupted";
48046
+ upsert({
48047
+ key: `interrupted:local:${turnId}`,
48048
+ kind: "interrupted",
48049
+ text: reason,
48050
+ final: true,
48051
+ seq: null,
48052
+ turnId
48053
+ });
48054
+ return;
48055
+ }
47994
48056
  if (event.type === "session.error") {
47995
48057
  const message = typeof details.message === "string" ? details.message : "unknown error";
47996
48058
  upsert({ key: `error:local-${++liveOrdinal}`, kind: "assistant", text: `error: ${message}`, final: true });
@@ -48004,7 +48066,7 @@ function createSeamRows(seam, sessionID, options) {
48004
48066
  if (!prompt)
48005
48067
  return;
48006
48068
  const userKey = `user:local-${++liveOrdinal}`;
48007
- upsert({ key: userKey, kind: "user", text: prompt, final: true });
48069
+ upsert({ key: userKey, kind: "user", text: prompt, final: true, unconfirmed: true, seq: null });
48008
48070
  const assistantKey = `assistant:live-${++liveOrdinal}`;
48009
48071
  const reasoningKey = `reasoning:live-${liveOrdinal}`;
48010
48072
  const group = { userKey, reasoningKey, assistantKey, userSuperseded: false };
@@ -48014,6 +48076,11 @@ function createSeamRows(seam, sessionID, options) {
48014
48076
  let reasoningStartedAt;
48015
48077
  let turnErrored = false;
48016
48078
  turnOpen = true;
48079
+ const reportError = (message) => {
48080
+ turnErrored = true;
48081
+ upsert({ key: assistantKey, kind: "assistant", text: `error: ${message}`, final: true });
48082
+ options?.onError?.(message);
48083
+ };
48017
48084
  const collapseThinking = () => {
48018
48085
  if (reasoningStartedAt === undefined)
48019
48086
  return;
@@ -48068,11 +48135,12 @@ function createSeamRows(seam, sessionID, options) {
48068
48135
  onToolRun: (run) => {
48069
48136
  const existing = rows.find((row) => row.key === `tool:live:${run.callId ?? run.name}`);
48070
48137
  const startedAt = existing?.kind === "tool" ? existing.startedAt : undefined;
48138
+ const args = run.argsPretty || (existing?.kind === "tool" ? existing.args : undefined) || "";
48071
48139
  upsert({
48072
48140
  key: `tool:live:${run.callId ?? run.name}`,
48073
48141
  kind: "tool",
48074
48142
  name: run.name,
48075
- args: run.argsPretty,
48143
+ args,
48076
48144
  status: run.ok ? "done" : "failed",
48077
48145
  output: run.output,
48078
48146
  ...startedAt !== undefined ? { elapsedSec: Number(((Date.now() - startedAt) / 1000).toFixed(1)) } : {}
@@ -48081,11 +48149,12 @@ function createSeamRows(seam, sessionID, options) {
48081
48149
  options?.onToolRun?.(run);
48082
48150
  },
48083
48151
  onApprove: options?.onApprove ?? approveThrough,
48084
- onError: (message) => {
48085
- turnErrored = true;
48086
- upsert({ key: assistantKey, kind: "assistant", text: `error: ${message}`, final: true });
48087
- options?.onError?.(message);
48088
- }
48152
+ onError: reportError
48153
+ }).catch((error) => {
48154
+ const diagnostic = sessionLockedErrorText(error);
48155
+ if (diagnostic !== undefined)
48156
+ reportError(diagnostic);
48157
+ throw error;
48089
48158
  }).finally(() => {
48090
48159
  turnOpen = false;
48091
48160
  (async () => {
@@ -48149,6 +48218,7 @@ var init_seam_rows = __esm(() => {
48149
48218
  init_server2();
48150
48219
  init_dock_visibility();
48151
48220
  init_motion();
48221
+ init_error();
48152
48222
  });
48153
48223
 
48154
48224
  // ../tui-base/src/routes/session/footer-refresh.ts
@@ -48700,6 +48770,17 @@ function cacheSegment(rate, theme) {
48700
48770
  priority: 40
48701
48771
  };
48702
48772
  }
48773
+ function bridgeStatusSegment(status) {
48774
+ if (status === undefined || status === "ready")
48775
+ return null;
48776
+ const text = status === "dead" ? "\u26A0 dead" : "\u27F3 recovering";
48777
+ const bg = status === "dead" ? "#a82124" : "#b58105";
48778
+ return {
48779
+ text,
48780
+ bg,
48781
+ priority: -2
48782
+ };
48783
+ }
48703
48784
  function rollingWidth(value, decimals = 0) {
48704
48785
  const fixed = Math.abs(value).toFixed(decimals);
48705
48786
  return Math.max(1, (fixed.split(".")[0] ?? "0").length);
@@ -48927,6 +49008,7 @@ function sessionFooterSegments(data) {
48927
49008
  add(toolSegment(data.tools ?? 0, theme));
48928
49009
  add(elapsedSegment(data.elapsedSec ?? null, theme));
48929
49010
  add(speedSegment(data.tps ?? null, theme));
49011
+ add(bridgeStatusSegment(data.bridgeStatus));
48930
49012
  return applyPowerlineGradient(segs, theme);
48931
49013
  }
48932
49014
  var POWERLINE_COLORS, AUTO_FG_DARK = "#1a1a2e", AUTO_FG_LIGHT = "#ffffff", DEFAULT_EFFORT = "high", POWERLINE_MIN_SEGMENT_DISTANCE = 80, POWERLINE_RAMP_FAMILIES, POWERLINE_RAMP_DEEP_LUMINANCE = 0.02, POWERLINE_RAMP_LIGHT_LUMINANCE = 0.55, POWERLINE_RAMP_HUE_STEPS, POWERLINE_RAMP_FALLBACK_HUES, EFFORT_ICONS;
@@ -49007,15 +49089,6 @@ var init_powerline = __esm(() => {
49007
49089
  });
49008
49090
 
49009
49091
  // ../tui-base/src/routes/session/merged-dock.ts
49010
- function activeTodos(todos) {
49011
- const out = [];
49012
- for (let i = 0;i < todos.length; i++) {
49013
- const todo = todos[i];
49014
- if (todo.status === "in_progress")
49015
- out.push({ ...todo, index: i + 1 });
49016
- }
49017
- return out;
49018
- }
49019
49092
  function attributeAgents(todos, agents) {
49020
49093
  let parent = null;
49021
49094
  for (let i = 0;i < todos.length; i++) {
@@ -49145,28 +49218,14 @@ function latestThinkRow(rows) {
49145
49218
  }
49146
49219
  return;
49147
49220
  }
49148
- function thinkLine(row, now, spin) {
49149
- const text = thinkBlockLines(row, spin, 1, now)[0];
49150
- if (text === undefined)
49151
- return;
49152
- return {
49221
+ function thinkLinesFor(row, now, spin, thinkLines) {
49222
+ return thinkBlockLines(row, spin, thinkLines, now).map((text) => ({
49153
49223
  kind: "think",
49154
49224
  segments: [{ text, tone: "running", accent: "think" }],
49155
49225
  italic: true,
49156
49226
  id: `dock:think:${row.key}`,
49157
49227
  fadeOutAt: row.streaming === true ? undefined : skinStopAt(row)
49158
- };
49159
- }
49160
- function todoLine(todo) {
49161
- const glyph = TODO_STATUS_GLYPHS.in_progress;
49162
- return {
49163
- kind: "todo",
49164
- index: todo.index,
49165
- segments: [
49166
- { text: `${glyph} ${todo.index} `, tone: "running" },
49167
- { text: todo.content, tone: "running" }
49168
- ]
49169
- };
49228
+ }));
49170
49229
  }
49171
49230
  function agentLine(agent, position, count, parentIndex, now = Date.now()) {
49172
49231
  const branch = position === count - 1 ? "\u2514\u2500 " : "\u251C\u2500 ";
@@ -49201,31 +49260,29 @@ function mergedWindowInfo(data, options) {
49201
49260
  function buildMergedDock(data, options) {
49202
49261
  const now = options.now ?? Date.now();
49203
49262
  const spin = options.spin ?? (() => 0);
49204
- const active = activeTodos(data.todos);
49205
- const attribution = attributeAgents(data.todos, data.agents);
49206
- const agents = attribution.agents;
49207
- const parent = attribution.parent;
49208
- const hasLowerContent = active.length > 0 || agents.length > 0;
49263
+ const agents = attributeAgents(data.todos, data.agents).agents;
49209
49264
  const thinkRow = latestThinkRow(data.think ?? []);
49210
- const thinkLines = thinkRow === undefined ? [] : [thinkLine(thinkRow, now, spin)].filter((line) => line !== undefined);
49265
+ const thinkAtGear = thinkRow === undefined ? [] : thinkLinesFor(thinkRow, now, spin, options.thinkLines ?? 1);
49266
+ const scene = activityScene(agents.length > 0, thinkAtGear.length > 0);
49211
49267
  const tools = data.tools;
49212
- let toolLines;
49213
- if (hasLowerContent) {
49268
+ let upperLines;
49269
+ let lowerRaw;
49270
+ if (scene === "A") {
49271
+ upperLines = thinkRow === undefined ? [] : thinkLinesFor(thinkRow, now, spin, 1).slice(0, 1);
49214
49272
  const latest = tools.length > 0 ? tools[tools.length - 1] : undefined;
49215
- toolLines = latest ? [coexistenceToolLine(latest, now, spin)] : [];
49273
+ if (latest !== undefined)
49274
+ upperLines.push(coexistenceToolLine(latest, now, spin));
49275
+ const brief = todoBriefLine(data.todos, now, data.todoStartedAt);
49276
+ if (brief !== "")
49277
+ upperLines.push({ kind: "todo", segments: [{ text: brief, tone: "running" }] });
49278
+ lowerRaw = agents.map((agent, i) => agentLine(agent, i, agents.length, undefined, now));
49279
+ } else if (scene === "B") {
49280
+ upperLines = thinkAtGear;
49281
+ lowerRaw = [];
49216
49282
  } else {
49217
- toolLines = tools.slice(-MERGED_DOCK_TOOL_ONLY_MAX).map((tool) => toolOnlyLine(tool, now, spin));
49218
- }
49219
- const upperLines = [...thinkLines, ...toolLines];
49220
- const lowerRaw = [];
49221
- for (const todo of active) {
49222
- lowerRaw.push(todoLine(todo));
49223
- if (parent && parent.index === todo.index) {
49224
- agents.forEach((agent, i) => lowerRaw.push(agentLine(agent, i, agents.length, todo.index, now)));
49225
- }
49226
- }
49227
- if (!parent) {
49228
- agents.forEach((agent, i) => lowerRaw.push(agentLine(agent, i, agents.length, undefined, now)));
49283
+ upperLines = tools.slice(-MERGED_DOCK_TOOL_ONLY_MAX).map((tool) => toolOnlyLine(tool, now, spin));
49284
+ const summary = todosSummaryFromTodos(data.todos);
49285
+ lowerRaw = summary === "" ? [] : [{ kind: "todo", segments: [{ text: summary, tone: "running" }] }];
49229
49286
  }
49230
49287
  const assembled = assembleZones(upperLines, lowerRaw, options.totalLines ?? MERGED_DOCK_TOTAL_LINES, options.cursor);
49231
49288
  return { lines: fitAll(assembled.lines, options.innerWidth), info: assembled.info };
@@ -49351,26 +49408,81 @@ function activityPanelCapSpec(gear, terminalRows) {
49351
49408
  maxLines: dockLineCap(terminalRows)
49352
49409
  };
49353
49410
  }
49354
- if (gear === "all") {
49355
- if (terminalRows === undefined)
49356
- return {
49357
- maxLines: PANEL_UNBOUNDED_LINES
49358
- };
49359
- return {
49360
- maxLines: PANEL_UNBOUNDED_LINES,
49361
- totalMaxLines: Math.max(1, Math.floor(terminalRows * 2 / 3) - 2)
49362
- };
49363
- }
49364
- const cap = Number(gear);
49365
- if (terminalRows === undefined)
49411
+ if (gear === "all")
49366
49412
  return {
49367
- maxLines: cap
49413
+ maxLines: ACTIVITY_PANEL_ALL_LINES
49368
49414
  };
49369
- const halfBudget = Math.floor(Math.max(1, Math.floor(terminalRows * 2 / 3) - 2) / 2);
49370
49415
  return {
49371
- maxLines: Math.min(cap, halfBudget)
49416
+ maxLines: Math.min(Number(gear), MERGED_DOCK_TOTAL_LINES)
49372
49417
  };
49373
49418
  }
49419
+ function dockHeightEase(t) {
49420
+ const k = Math.max(0, Math.min(1, t));
49421
+ return k * k * (3 - 2 * k);
49422
+ }
49423
+ function dockHeightLines(from, to, elapsedMs, durationMs = DOCK_HEIGHT_ANIM_MS) {
49424
+ const a = Math.max(0, Math.floor(from));
49425
+ const b = Math.max(0, Math.floor(to));
49426
+ if (elapsedMs <= 0)
49427
+ return a;
49428
+ if (elapsedMs >= durationMs)
49429
+ return b;
49430
+ return Math.max(0, Math.round(a + (b - a) * dockHeightEase(elapsedMs / durationMs)));
49431
+ }
49432
+ function dockHeightContentLines(target, now = Date.now()) {
49433
+ if (!motionAnimationRunning())
49434
+ return target;
49435
+ const tween = dockHeightTween();
49436
+ if (tween === undefined)
49437
+ return target;
49438
+ return dockHeightLines(tween.from, tween.to, now - tween.startedAt);
49439
+ }
49440
+ function setDockHeightTarget(target, now = Date.now()) {
49441
+ dockFrameNow = now;
49442
+ const to = Math.max(0, Math.min(MERGED_DOCK_TOTAL_LINES, Math.floor(target)));
49443
+ const current = untrack(dockHeightTween);
49444
+ if (current !== undefined) {
49445
+ if (current.to === to)
49446
+ return;
49447
+ const from = Math.min(current.to, dockHeightLines(current.from, current.to, now - current.startedAt));
49448
+ if (from === 0 || to === 0 || !motionAnimationRunning()) {
49449
+ setDockHeightTween(undefined);
49450
+ dockHeightSettled = to;
49451
+ return;
49452
+ }
49453
+ setDockHeightTween({
49454
+ from,
49455
+ to,
49456
+ startedAt: now
49457
+ });
49458
+ } else {
49459
+ if (dockHeightSettled === to)
49460
+ return;
49461
+ if (dockHeightSettled === undefined || dockHeightSettled === 0 || to === 0 || !motionAnimationRunning()) {
49462
+ dockHeightSettled = to;
49463
+ return;
49464
+ }
49465
+ setDockHeightTween({
49466
+ from: dockHeightSettled,
49467
+ to,
49468
+ startedAt: now
49469
+ });
49470
+ }
49471
+ dockHeightSettled = to;
49472
+ }
49473
+ function dockHeightAnimating() {
49474
+ return dockHeightTween() !== undefined;
49475
+ }
49476
+ function tickDockHeight(now = Date.now()) {
49477
+ dockFrameNow = now;
49478
+ const current = untrack(dockHeightTween);
49479
+ if (current !== undefined && now - current.startedAt >= DOCK_HEIGHT_ANIM_MS)
49480
+ setDockHeightTween(undefined);
49481
+ }
49482
+ function resetDockHeight(to) {
49483
+ setDockHeightTween(undefined);
49484
+ dockHeightSettled = to === undefined ? undefined : Math.max(0, Math.min(MERGED_DOCK_TOTAL_LINES, Math.floor(to)));
49485
+ }
49374
49486
  function skinNoticeFadeProgress(elapsedMs, ttlMs) {
49375
49487
  return Math.max(0, Math.min(1, (elapsedMs - (ttlMs - SKIN_NOTICE_FADE_MS)) / SKIN_NOTICE_FADE_MS));
49376
49488
  }
@@ -49440,7 +49552,9 @@ function latestTodos(rows) {
49440
49552
  return parseTodos(todoArray(source) ?? []);
49441
49553
  }
49442
49554
  function todosSummaryLine(rows) {
49443
- const todos = latestTodos(rows);
49555
+ return todosSummaryFromTodos(latestTodos(rows));
49556
+ }
49557
+ function todosSummaryFromTodos(todos) {
49444
49558
  if (todos.length === 0)
49445
49559
  return "";
49446
49560
  const done = todos.filter((todo) => todo.status === "completed").length;
@@ -49453,6 +49567,25 @@ function todosSummaryLine(rows) {
49453
49567
  });
49454
49568
  return active ? `${head} \xB7 ${active.content}` : head;
49455
49569
  }
49570
+ function todoSetStartedAt(todos, now = Date.now()) {
49571
+ const sig = todoSetSignature(todos);
49572
+ const first = todoSetFirstSeen.get(sig);
49573
+ if (first !== undefined)
49574
+ return first;
49575
+ todoSetFirstSeen.set(sig, now);
49576
+ return now;
49577
+ }
49578
+ function todoBriefLine(todos, now = Date.now(), startedAt) {
49579
+ if (todos.length === 0)
49580
+ return "";
49581
+ const done = todos.filter((todo) => todo.status === "completed").length;
49582
+ const anchor = startedAt ?? todoSetStartedAt(todos, now);
49583
+ const secs = Math.max(0, Math.floor((now - anchor) / 1000));
49584
+ return `todo ${done}/${todos.length} ${secs}s`;
49585
+ }
49586
+ function resetTodoBriefClock() {
49587
+ todoSetFirstSeen.clear();
49588
+ }
49456
49589
  function toolMarker(status) {
49457
49590
  return status === "running" ? "\u2699" : status === "failed" ? "\u2718" : "\u2714";
49458
49591
  }
@@ -49489,13 +49622,20 @@ function thinkBlockLines(row, spin, maxLines = DOCK_WIDGET_MAX_LINES, now = Date
49489
49622
  }
49490
49623
  return [];
49491
49624
  }
49625
+ function activityScene(hasRunningSubagent, hasVisibleThink) {
49626
+ if (hasRunningSubagent)
49627
+ return "A";
49628
+ return hasVisibleThink ? "B" : "C";
49629
+ }
49492
49630
  function dockBlocks(rows, options = {}) {
49493
49631
  dockSpin();
49494
49632
  const now = options.now ?? Date.now();
49495
49633
  const decorated = options.decorated ?? motionDecorationsEnabled();
49496
49634
  const maxLines = Math.max(1, Math.floor(options.maxLines ?? DOCK_WIDGET_MAX_LINES));
49635
+ const gearThinkMaxLines = Math.max(1, Math.floor(options.thinkMaxLines ?? maxLines));
49497
49636
  const think = [];
49498
49637
  const toolLines = [];
49638
+ const hasRunningSubagent = rows.some((row) => row.kind === "subagents" && row.children.some((child) => child.status === "running"));
49499
49639
  const reasoning = rows.filter((row) => row.kind === "reasoning");
49500
49640
  const live = [...reasoning].reverse().find((row) => row.streaming === true);
49501
49641
  let thinkRow = live;
@@ -49511,10 +49651,12 @@ function dockBlocks(rows, options = {}) {
49511
49651
  }
49512
49652
  }
49513
49653
  }
49654
+ const scene = activityScene(hasRunningSubagent, thinkRow !== undefined);
49655
+ const effectiveThinkMax = scene === "A" ? 1 : gearThinkMaxLines;
49514
49656
  if (thinkRow !== undefined) {
49515
49657
  const stopAt = skinStopAt(thinkRow);
49516
49658
  const fadeOutAt = thinkRow.streaming === true ? undefined : stopAt;
49517
- for (const text of thinkBlockLines(thinkRow, dockSpin, maxLines, now)) {
49659
+ for (const text of thinkBlockLines(thinkRow, dockSpin, effectiveThinkMax, now)) {
49518
49660
  think.push({
49519
49661
  text,
49520
49662
  tone: "running",
@@ -49525,7 +49667,8 @@ function dockBlocks(rows, options = {}) {
49525
49667
  });
49526
49668
  }
49527
49669
  }
49528
- const tools = rows.filter((row) => row.kind === "tool" && row.key.startsWith("tool:live:"));
49670
+ const toolMax = scene === "B" ? 0 : scene === "A" ? 1 : maxLines;
49671
+ const tools = toolMax === 0 ? [] : rows.filter((row) => row.kind === "tool" && row.key.startsWith("tool:live:"));
49529
49672
  const visible = tools.filter((row) => {
49530
49673
  if (row.faded === true && row.status !== "running")
49531
49674
  return false;
@@ -49534,7 +49677,7 @@ function dockBlocks(rows, options = {}) {
49534
49677
  const stopAt = skinStopAt(row);
49535
49678
  return stopAt === undefined || dockLineVisibility(stopAt, now, decorated).phase !== "hidden";
49536
49679
  });
49537
- for (const row of visible.slice(-maxLines)) {
49680
+ for (const row of visible.slice(-toolMax)) {
49538
49681
  toolLines.push({
49539
49682
  text: toolLineText(row, dockSpin, now),
49540
49683
  tone: row.status === "running" ? "running" : row.status === "failed" ? "failed" : "ok",
@@ -49799,14 +49942,24 @@ function WidgetsDock(props) {
49799
49942
  decorated: motionDecorationsEnabled(),
49800
49943
  background: bg()
49801
49944
  });
49802
- onAnimationTick(() => motionAnimationRunning() && dockNeedsClock(props.rows) ? motionFrameRate() : undefined, () => setDockSpin((s) => s + 1));
49945
+ onAnimationTick(() => {
49946
+ if (!motionAnimationRunning())
49947
+ return;
49948
+ if (untrack(dockHeightAnimating))
49949
+ return motionFrameRate();
49950
+ return dockNeedsClock(props.rows) ? motionFrameRate() : undefined;
49951
+ }, () => {
49952
+ tickDockHeight();
49953
+ setDockSpin((s) => s + 1);
49954
+ });
49803
49955
  const width = () => Math.max(16, dimensions().width - 4);
49804
49956
  const turnActive = () => props.turnActive?.() ?? dockTurnActive(props.rows);
49805
49957
  createEffect(() => activityFrameLatch.push(turnActive() || mergedLowerHasContent(props.rows)));
49806
49958
  onCleanup(activityFrameLatch.dispose);
49807
49959
  const frame = () => activityFrameMode(dimensions().height);
49808
49960
  const capSpec = () => activityPanelCapSpec(activityPanelGear(), dimensions().height);
49809
- const lineCap = () => capSpec().maxLines;
49961
+ const thinkCap = () => capSpec().maxLines;
49962
+ const toolCap = () => dockLineCap(dimensions().height);
49810
49963
  const mergedSource = (now) => {
49811
49964
  dockSpin();
49812
49965
  return {
@@ -49816,19 +49969,14 @@ function WidgetsDock(props) {
49816
49969
  agents: mergedRunningAgents(props.rows)
49817
49970
  };
49818
49971
  };
49819
- const gearTotal = () => {
49820
- const gear = activityPanelGear();
49821
- if (gear === undefined || gear === "all")
49822
- return MERGED_DOCK_TOTAL_LINES;
49823
- return Number(gear);
49824
- };
49825
49972
  const mergedFrame = () => {
49826
49973
  const now = Date.now();
49827
49974
  const data = mergedSource(now);
49828
49975
  const options = {
49829
49976
  innerWidth: width(),
49830
49977
  now,
49831
- totalLines: Math.min(gearTotal(), MERGED_DOCK_TOTAL_LINES),
49978
+ totalLines: MERGED_DOCK_TOTAL_LINES,
49979
+ thinkLines: thinkCap(),
49832
49980
  cursor: mergedDockCursor()
49833
49981
  };
49834
49982
  return {
@@ -49836,6 +49984,11 @@ function WidgetsDock(props) {
49836
49984
  info: mergedWindowInfo(data, options)
49837
49985
  };
49838
49986
  };
49987
+ createEffect(() => setDockHeightTarget(mergedFrame().lines.length));
49988
+ onCleanup(() => {
49989
+ resetDockHeight();
49990
+ resetTodoBriefClock();
49991
+ });
49839
49992
  const titleSlotWidth = () => dimensions().width - 4;
49840
49993
  const mergedTitleText = () => {
49841
49994
  const {
@@ -49890,7 +50043,15 @@ function WidgetsDock(props) {
49890
50043
  bindings: ["session.dock.scroll.up", "session.dock.scroll.down"]
49891
50044
  }));
49892
50045
  }
49893
- const frameHeight = () => 2 + mergedFrame().lines.length;
50046
+ const frameLines = () => {
50047
+ const lines = mergedFrame().lines;
50048
+ const target = lines.length;
50049
+ const tweened = Math.max(0, dockHeightContentLines(target, dockFrameNow));
50050
+ const animating = untrack(dockHeightAnimating);
50051
+ const count = !animating || tweened >= target ? target : Math.min(target, tweened);
50052
+ return lines.slice(0, count);
50053
+ };
50054
+ const frameHeight = () => 2 + frameLines().length;
49894
50055
  const compactSummary = () => mergedCompactSummary(props.rows);
49895
50056
  const compactHeight = () => 2 + (compactSummary() === "" ? 0 : 1);
49896
50057
  const accentFg = (accent) => dockAccentColor(theme, accent);
@@ -49948,10 +50109,10 @@ function WidgetsDock(props) {
49948
50109
  return skinCtx();
49949
50110
  },
49950
50111
  get maxLines() {
49951
- return lineCap();
50112
+ return toolCap();
49952
50113
  },
49953
- get totalMaxLines() {
49954
- return capSpec().totalMaxLines;
50114
+ get thinkMaxLines() {
50115
+ return thinkCap();
49955
50116
  }
49956
50117
  });
49957
50118
  },
@@ -50000,7 +50161,7 @@ function WidgetsDock(props) {
50000
50161
  setProp(_el$4, "onMouseScroll", onMergedWheel);
50001
50162
  insert(_el$4, createComponent2(For, {
50002
50163
  get each() {
50003
- return mergedFrame().lines;
50164
+ return frameLines();
50004
50165
  },
50005
50166
  children: mergedLineView
50006
50167
  }));
@@ -50026,9 +50187,7 @@ function WidgetsDock(props) {
50026
50187
  function FlatDock(props) {
50027
50188
  const dockOptions = () => ({
50028
50189
  maxLines: props.maxLines,
50029
- ...props.totalMaxLines !== undefined ? {
50030
- totalMaxLines: props.totalMaxLines
50031
- } : {}
50190
+ thinkMaxLines: props.thinkMaxLines
50032
50191
  });
50033
50192
  return (() => {
50034
50193
  var _el$7 = createElement("box");
@@ -50082,7 +50241,7 @@ function dockLineNode(line, width, ctx, fgFor, accentFg) {
50082
50241
  return _el$9;
50083
50242
  })();
50084
50243
  }
50085
- var SKIN_FADE_IN_MS = 400, SKIN_NOTICE_FADE_MS = 500, SKIN_PULSE_MS = 1200, SKIN_PULSE_CYCLES = 3, SKIN_PULSE_DIM = 0.45, SKIN_FAINT_MIX = 0.78, ACTIVITY_PANEL_GEARS, PANEL_UNBOUNDED_LINES = 1e6, activityPanelGear, setActivityPanelGear, LINE_FIRST_SEEN_MAX = 512, lineFirstSeen, dockSpin, setDockSpin, mergedDockCursor, setMergedDockCursor, TODO_TOOL_NAMES, ACTIVITY_FRAME_BORDER_FALLBACK = "#7aa2f7", ACTIVITY_FRAME_MIN_CONTRAST = 6, ACTIVITY_BLUE_STEPS, BLUE_HUE_MIN = 190, BLUE_HUE_MAX = 250, BLUE_MIN_SATURATION = 0.25, AUTO_POLE_LIGHT = "#ffffff", AUTO_POLE_DARK = "#000000", DOCK_ACCENT_STEPS, DOCK_ACCENT_HUES, DOCK_ACCENT_FALLBACK, ACTIVITY_FRAME_DEFER_MS = 60, activityFrameLatch;
50244
+ var SKIN_FADE_IN_MS = 400, SKIN_NOTICE_FADE_MS = 500, SKIN_PULSE_MS = 1200, SKIN_PULSE_CYCLES = 3, SKIN_PULSE_DIM = 0.45, SKIN_FAINT_MIX = 0.78, ACTIVITY_PANEL_GEARS, ACTIVITY_PANEL_ALL_LINES = 10, activityPanelGear, setActivityPanelGear, DOCK_HEIGHT_ANIM_MS = 200, dockHeightTween, setDockHeightTween, dockHeightSettled = undefined, dockFrameNow = 0, LINE_FIRST_SEEN_MAX = 512, lineFirstSeen, dockSpin, setDockSpin, mergedDockCursor, setMergedDockCursor, todoSetSignature = (todos) => todos.map((todo) => todo.content).sort().join("\x01"), todoSetFirstSeen, TODO_TOOL_NAMES, ACTIVITY_FRAME_BORDER_FALLBACK = "#7aa2f7", ACTIVITY_FRAME_MIN_CONTRAST = 6, ACTIVITY_BLUE_STEPS, BLUE_HUE_MIN = 190, BLUE_HUE_MAX = 250, BLUE_MIN_SATURATION = 0.25, AUTO_POLE_LIGHT = "#ffffff", AUTO_POLE_DARK = "#000000", DOCK_ACCENT_STEPS, DOCK_ACCENT_HUES, DOCK_ACCENT_FALLBACK, ACTIVITY_FRAME_DEFER_MS = 60, activityFrameLatch;
50086
50245
  var init_widgets_dock = __esm(() => {
50087
50246
  init_index_bun();
50088
50247
  init_index_bun();
@@ -50108,9 +50267,11 @@ var init_widgets_dock = __esm(() => {
50108
50267
  init_input_ownership();
50109
50268
  ACTIVITY_PANEL_GEARS = ["1", "5", "7", "10", "all"];
50110
50269
  [activityPanelGear, setActivityPanelGear] = createSignal(undefined);
50270
+ [dockHeightTween, setDockHeightTween] = createSignal(undefined);
50111
50271
  lineFirstSeen = new Map;
50112
50272
  [dockSpin, setDockSpin] = createSignal(0);
50113
50273
  [mergedDockCursor, setMergedDockCursor] = createSignal(0);
50274
+ todoSetFirstSeen = new Map;
50114
50275
  TODO_TOOL_NAMES = new Set(["todowrite", "todo_write"]);
50115
50276
  ACTIVITY_BLUE_STEPS = [200, 100, 300, 400, 500, 600, 700];
50116
50277
  DOCK_ACCENT_STEPS = {
@@ -50296,6 +50457,17 @@ function Transcript(props) {
50296
50457
  setProp(_el$3, "paddingLeft", 2);
50297
50458
  setProp(_el$3, "border", ["top", "bottom", "left", "right"]);
50298
50459
  setProp(_el$3, "borderStyle", "single");
50460
+ insert(_el$3, createComponent2(Show, {
50461
+ get when() {
50462
+ return row.unconfirmed === true;
50463
+ },
50464
+ get children() {
50465
+ var _el$4 = createElement("text");
50466
+ insert(_el$4, () => t("recovery.input.unconfirmed"));
50467
+ effect((_$p) => setProp(_el$4, "fg", color.pendingQueue(), _$p));
50468
+ return _el$4;
50469
+ }
50470
+ }), null);
50299
50471
  insert(_el$3, createComponent2(UserMessageFade, {
50300
50472
  get target() {
50301
50473
  return color.user();
@@ -50306,10 +50478,32 @@ function Transcript(props) {
50306
50478
  get text() {
50307
50479
  return row.text;
50308
50480
  }
50309
- }));
50481
+ }), null);
50310
50482
  effect((_$p) => setProp(_el$3, "borderColor", unfocusedBorderColor(theme), _$p));
50311
50483
  return _el$3;
50312
50484
  })();
50485
+ case "interrupted":
50486
+ return (() => {
50487
+ var _el$5 = createElement("box"), _el$6 = createElement("text");
50488
+ insertNode(_el$5, _el$6);
50489
+ setProp(_el$5, "flexShrink", 0);
50490
+ setProp(_el$5, "paddingLeft", 2);
50491
+ setProp(_el$5, "border", ["top", "bottom", "left", "right"]);
50492
+ setProp(_el$5, "borderStyle", "single");
50493
+ insert(_el$6, () => t("recovery.turn.interrupted", {
50494
+ turnId: row.turnId
50495
+ }));
50496
+ effect((_p$) => {
50497
+ var _v$6 = color.running(), _v$7 = color.running();
50498
+ _v$6 !== _p$.e && (_p$.e = setProp(_el$5, "borderColor", _v$6, _p$.e));
50499
+ _v$7 !== _p$.t && (_p$.t = setProp(_el$6, "fg", _v$7, _p$.t));
50500
+ return _p$;
50501
+ }, {
50502
+ e: undefined,
50503
+ t: undefined
50504
+ });
50505
+ return _el$5;
50506
+ })();
50313
50507
  case "assistant":
50314
50508
  return assistantRow(row);
50315
50509
  case "ask":
@@ -50322,68 +50516,68 @@ function Transcript(props) {
50322
50516
  props.scrollRef?.(undefined);
50323
50517
  });
50324
50518
  return (() => {
50325
- var _el$4 = createElement("box"), _el$5 = createElement("box"), _el$6 = createElement("box"), _el$7 = createElement("scrollbox");
50326
- insertNode(_el$4, _el$5);
50327
- setProp(_el$4, "flexDirection", "column");
50328
- setProp(_el$4, "flexGrow", 1);
50329
- setProp(_el$4, "minHeight", 0);
50330
- setProp(_el$4, "width", "100%");
50331
- insertNode(_el$5, _el$6);
50332
- setProp(_el$5, "flexDirection", "row");
50333
- setProp(_el$5, "flexGrow", 1);
50334
- setProp(_el$5, "minHeight", 0);
50335
- insertNode(_el$6, _el$7);
50336
- setProp(_el$6, "flexGrow", 1);
50337
- setProp(_el$6, "minHeight", 0);
50338
- setProp(_el$6, "position", "relative");
50339
- setProp(_el$6, "paddingBottom", 1);
50519
+ var _el$7 = createElement("box"), _el$8 = createElement("box"), _el$9 = createElement("box"), _el$0 = createElement("scrollbox");
50520
+ insertNode(_el$7, _el$8);
50521
+ setProp(_el$7, "flexDirection", "column");
50522
+ setProp(_el$7, "flexGrow", 1);
50523
+ setProp(_el$7, "minHeight", 0);
50524
+ setProp(_el$7, "width", "100%");
50525
+ insertNode(_el$8, _el$9);
50526
+ setProp(_el$8, "flexDirection", "row");
50527
+ setProp(_el$8, "flexGrow", 1);
50528
+ setProp(_el$8, "minHeight", 0);
50529
+ insertNode(_el$9, _el$0);
50530
+ setProp(_el$9, "flexGrow", 1);
50531
+ setProp(_el$9, "minHeight", 0);
50532
+ setProp(_el$9, "position", "relative");
50533
+ setProp(_el$9, "paddingBottom", 1);
50340
50534
  use((value) => {
50341
50535
  props.scrollRef?.(value);
50342
- }, _el$7);
50343
- setProp(_el$7, "flexGrow", 1);
50344
- setProp(_el$7, "overflow", "hidden");
50345
- setProp(_el$7, "stickyScroll", true);
50346
- setProp(_el$7, "stickyStart", "bottom");
50347
- insert(_el$7, createComponent2(For, {
50536
+ }, _el$0);
50537
+ setProp(_el$0, "flexGrow", 1);
50538
+ setProp(_el$0, "overflow", "hidden");
50539
+ setProp(_el$0, "stickyScroll", true);
50540
+ setProp(_el$0, "stickyStart", "bottom");
50541
+ insert(_el$0, createComponent2(For, {
50348
50542
  get each() {
50349
50543
  return visibleRows();
50350
50544
  },
50351
50545
  children: (row) => (() => {
50352
- var _el$1 = createElement("box");
50353
- setProp(_el$1, "marginTop", 1);
50354
- setProp(_el$1, "flexShrink", 0);
50355
- insert(_el$1, () => rowView(row));
50356
- effect((_$p) => setProp(_el$1, "id", `seam-row-${row.key}`, _$p));
50357
- return _el$1;
50546
+ var _el$12 = createElement("box");
50547
+ setProp(_el$12, "marginTop", 1);
50548
+ setProp(_el$12, "flexShrink", 0);
50549
+ insert(_el$12, () => rowView(row));
50550
+ effect((_$p) => setProp(_el$12, "id", `seam-row-${row.key}`, _$p));
50551
+ return _el$12;
50358
50552
  })()
50359
50553
  }), null);
50360
- insert(_el$7, createComponent2(Show, {
50554
+ insert(_el$0, createComponent2(Show, {
50361
50555
  get when() {
50362
50556
  return projection.hydrated() === false;
50363
50557
  },
50364
50558
  get children() {
50365
- var _el$8 = createElement("box"), _el$9 = createElement("text");
50366
- insertNode(_el$8, _el$9);
50367
- setProp(_el$8, "flexShrink", 0);
50368
- insert(_el$9, () => t("transcript.loading"));
50369
- effect((_$p) => setProp(_el$9, "fg", color.loading(), _$p));
50370
- return _el$8;
50559
+ var _el$1 = createElement("box"), _el$10 = createElement("text");
50560
+ insertNode(_el$1, _el$10);
50561
+ setProp(_el$1, "flexShrink", 0);
50562
+ insert(_el$10, () => t("transcript.loading"));
50563
+ effect((_$p) => setProp(_el$10, "fg", color.loading(), _$p));
50564
+ return _el$1;
50371
50565
  }
50372
50566
  }), null);
50373
- insert(_el$7, createComponent2(For, {
50567
+ insert(_el$0, createComponent2(For, {
50374
50568
  get each() {
50375
50569
  return props.pending?.() ?? [];
50376
50570
  },
50377
50571
  children: (row) => (() => {
50378
- var _el$10 = createElement("box");
50379
- setProp(_el$10, "marginTop", 1);
50380
- setProp(_el$10, "flexShrink", 0);
50381
- insert(_el$10, (() => {
50572
+ var _el$13 = createElement("box");
50573
+ setProp(_el$13, "marginTop", 1);
50574
+ setProp(_el$13, "flexShrink", 0);
50575
+ insert(_el$13, (() => {
50382
50576
  var _c$ = memo2(() => row.kind === "queue");
50383
50577
  return () => _c$() ? (() => {
50384
- var _el$11 = createElement("text");
50385
- setProp(_el$11, "wrapMode", "word");
50386
- insert(_el$11, (() => {
50578
+ var _el$14 = createElement("text");
50579
+ setProp(_el$14, "wrapMode", "word");
50580
+ insert(_el$14, (() => {
50387
50581
  var _c$2 = memo2(() => row.state === "paused");
50388
50582
  return () => _c$2() ? t("transcript.pending.queue.paused", {
50389
50583
  order: row.order ?? 1,
@@ -50394,19 +50588,19 @@ function Transcript(props) {
50394
50588
  });
50395
50589
  })());
50396
50590
  effect((_p$) => {
50397
- var _v$12 = color.pendingQueue(), _v$13 = TextAttributes6.ITALIC;
50398
- _v$12 !== _p$.e && (_p$.e = setProp(_el$11, "fg", _v$12, _p$.e));
50399
- _v$13 !== _p$.t && (_p$.t = setProp(_el$11, "attributes", _v$13, _p$.t));
50591
+ var _v$14 = color.pendingQueue(), _v$15 = TextAttributes6.ITALIC;
50592
+ _v$14 !== _p$.e && (_p$.e = setProp(_el$14, "fg", _v$14, _p$.e));
50593
+ _v$15 !== _p$.t && (_p$.t = setProp(_el$14, "attributes", _v$15, _p$.t));
50400
50594
  return _p$;
50401
50595
  }, {
50402
50596
  e: undefined,
50403
50597
  t: undefined
50404
50598
  });
50405
- return _el$11;
50599
+ return _el$14;
50406
50600
  })() : (() => {
50407
- var _el$12 = createElement("text");
50408
- setProp(_el$12, "wrapMode", "word");
50409
- insert(_el$12, (() => {
50601
+ var _el$15 = createElement("text");
50602
+ setProp(_el$15, "wrapMode", "word");
50603
+ insert(_el$15, (() => {
50410
50604
  var _c$3 = memo2(() => row.state === "delivered");
50411
50605
  return () => _c$3() ? t("transcript.pending.steer.delivered", {
50412
50606
  text: row.text
@@ -50414,35 +50608,35 @@ function Transcript(props) {
50414
50608
  text: row.text
50415
50609
  });
50416
50610
  })());
50417
- effect((_$p) => setProp(_el$12, "fg", color.pendingSteer(), _$p));
50418
- return _el$12;
50611
+ effect((_$p) => setProp(_el$15, "fg", color.pendingSteer(), _$p));
50612
+ return _el$15;
50419
50613
  })();
50420
50614
  })());
50421
- effect((_$p) => setProp(_el$10, "id", `pending-row-${row.id}`, _$p));
50422
- return _el$10;
50615
+ effect((_$p) => setProp(_el$13, "id", `pending-row-${row.id}`, _$p));
50616
+ return _el$13;
50423
50617
  })()
50424
50618
  }), null);
50425
- insert(_el$4, createComponent2(Show, {
50619
+ insert(_el$7, createComponent2(Show, {
50426
50620
  get when() {
50427
50621
  return props.status || props.widgets || props.children || props.footer || props.notices;
50428
50622
  },
50429
50623
  get children() {
50430
- var _el$0 = createElement("box");
50431
- setProp(_el$0, "width", "100%");
50432
- setProp(_el$0, "flexShrink", 0);
50433
- setProp(_el$0, "flexDirection", "column");
50434
- insert(_el$0, () => props.status, null);
50435
- insert(_el$0, () => props.widgets, null);
50436
- insert(_el$0, () => props.children, null);
50437
- insert(_el$0, () => props.footer, null);
50438
- insert(_el$0, () => props.notices, null);
50439
- return _el$0;
50624
+ var _el$11 = createElement("box");
50625
+ setProp(_el$11, "width", "100%");
50626
+ setProp(_el$11, "flexShrink", 0);
50627
+ setProp(_el$11, "flexDirection", "column");
50628
+ insert(_el$11, () => props.status, null);
50629
+ insert(_el$11, () => props.widgets, null);
50630
+ insert(_el$11, () => props.children, null);
50631
+ insert(_el$11, () => props.footer, null);
50632
+ insert(_el$11, () => props.notices, null);
50633
+ return _el$11;
50440
50634
  }
50441
50635
  }), null);
50442
50636
  effect((_p$) => {
50443
- var _v$6 = color.background(), _v$7 = frame().border, _v$8 = frame().borderStyle, _v$9 = frame().borderColor, _v$0 = frame().title, _v$1 = frame().titleColor, _v$10 = {
50637
+ var _v$8 = color.background(), _v$9 = frame().border, _v$0 = frame().borderStyle, _v$1 = frame().borderColor, _v$10 = frame().title, _v$11 = frame().titleColor, _v$12 = {
50444
50638
  paddingRight: props.scrollbar ? 1 : 0
50445
- }, _v$11 = {
50639
+ }, _v$13 = {
50446
50640
  paddingLeft: 1,
50447
50641
  visible: props.scrollbar ?? false,
50448
50642
  trackOptions: {
@@ -50450,14 +50644,14 @@ function Transcript(props) {
50450
50644
  foregroundColor: color.reasoningBorder()
50451
50645
  }
50452
50646
  };
50453
- _v$6 !== _p$.e && (_p$.e = setProp(_el$4, "backgroundColor", _v$6, _p$.e));
50454
- _v$7 !== _p$.t && (_p$.t = setProp(_el$5, "border", _v$7, _p$.t));
50455
- _v$8 !== _p$.a && (_p$.a = setProp(_el$5, "borderStyle", _v$8, _p$.a));
50456
- _v$9 !== _p$.o && (_p$.o = setProp(_el$5, "borderColor", _v$9, _p$.o));
50457
- _v$0 !== _p$.i && (_p$.i = setProp(_el$5, "title", _v$0, _p$.i));
50458
- _v$1 !== _p$.n && (_p$.n = setProp(_el$5, "titleColor", _v$1, _p$.n));
50459
- _v$10 !== _p$.s && (_p$.s = setProp(_el$7, "viewportOptions", _v$10, _p$.s));
50460
- _v$11 !== _p$.h && (_p$.h = setProp(_el$7, "verticalScrollbarOptions", _v$11, _p$.h));
50647
+ _v$8 !== _p$.e && (_p$.e = setProp(_el$7, "backgroundColor", _v$8, _p$.e));
50648
+ _v$9 !== _p$.t && (_p$.t = setProp(_el$8, "border", _v$9, _p$.t));
50649
+ _v$0 !== _p$.a && (_p$.a = setProp(_el$8, "borderStyle", _v$0, _p$.a));
50650
+ _v$1 !== _p$.o && (_p$.o = setProp(_el$8, "borderColor", _v$1, _p$.o));
50651
+ _v$10 !== _p$.i && (_p$.i = setProp(_el$8, "title", _v$10, _p$.i));
50652
+ _v$11 !== _p$.n && (_p$.n = setProp(_el$8, "titleColor", _v$11, _p$.n));
50653
+ _v$12 !== _p$.s && (_p$.s = setProp(_el$0, "viewportOptions", _v$12, _p$.s));
50654
+ _v$13 !== _p$.h && (_p$.h = setProp(_el$0, "verticalScrollbarOptions", _v$13, _p$.h));
50461
50655
  return _p$;
50462
50656
  }, {
50463
50657
  e: undefined,
@@ -50469,7 +50663,7 @@ function Transcript(props) {
50469
50663
  s: undefined,
50470
50664
  h: undefined
50471
50665
  });
50472
- return _el$4;
50666
+ return _el$7;
50473
50667
  })();
50474
50668
  }
50475
50669
  function AskReplayBlock(props) {
@@ -50479,55 +50673,55 @@ function AskReplayBlock(props) {
50479
50673
  const askAnswerOf = (entry) => entry.selected.map((label) => splitRecommended(label).label).join(", ") || entry.custom || t("transcript.ask.declined");
50480
50674
  const askDeclinedOf = (entry) => entry.declined || entry.selected.length === 0 && !entry.custom;
50481
50675
  return (() => {
50482
- var _el$13 = createElement("box");
50483
- setProp(_el$13, "flexDirection", "column");
50484
- setProp(_el$13, "gap", 1);
50485
- insert(_el$13, createComponent2(For, {
50676
+ var _el$16 = createElement("box");
50677
+ setProp(_el$16, "flexDirection", "column");
50678
+ setProp(_el$16, "gap", 1);
50679
+ insert(_el$16, createComponent2(For, {
50486
50680
  get each() {
50487
50681
  return props.row.entries;
50488
50682
  },
50489
50683
  children: (entry) => (() => {
50490
- var _el$14 = createElement("box"), _el$15 = createElement("text"), _el$16 = createElement("text");
50491
- insertNode(_el$14, _el$15);
50492
- insertNode(_el$14, _el$16);
50493
- setProp(_el$14, "flexDirection", "column");
50494
- insert(_el$14, createComponent2(Show, {
50684
+ var _el$17 = createElement("box"), _el$18 = createElement("text"), _el$19 = createElement("text");
50685
+ insertNode(_el$17, _el$18);
50686
+ insertNode(_el$17, _el$19);
50687
+ setProp(_el$17, "flexDirection", "column");
50688
+ insert(_el$17, createComponent2(Show, {
50495
50689
  get when() {
50496
50690
  return entry.header;
50497
50691
  },
50498
50692
  children: (header) => (() => {
50499
- var _el$17 = createElement("text");
50500
- insert(_el$17, header);
50501
- effect((_$p) => setProp(_el$17, "fg", reasoning(), _$p));
50502
- return _el$17;
50693
+ var _el$20 = createElement("text");
50694
+ insert(_el$20, header);
50695
+ effect((_$p) => setProp(_el$20, "fg", reasoning(), _$p));
50696
+ return _el$20;
50503
50697
  })()
50504
- }), _el$15);
50505
- insert(_el$15, () => `\u2713 ${entry.question}`);
50506
- insert(_el$14, createComponent2(Show, {
50698
+ }), _el$18);
50699
+ insert(_el$18, () => `\u2713 ${entry.question}`);
50700
+ insert(_el$17, createComponent2(Show, {
50507
50701
  get when() {
50508
50702
  return entry.detail;
50509
50703
  },
50510
50704
  children: (detail) => (() => {
50511
- var _el$18 = createElement("text");
50512
- insert(_el$18, detail);
50513
- effect((_$p) => setProp(_el$18, "fg", reasoning(), _$p));
50514
- return _el$18;
50705
+ var _el$21 = createElement("text");
50706
+ insert(_el$21, detail);
50707
+ effect((_$p) => setProp(_el$21, "fg", reasoning(), _$p));
50708
+ return _el$21;
50515
50709
  })()
50516
- }), _el$16);
50517
- insert(_el$16, () => ` \u2192 ${askAnswerOf(entry)}`);
50710
+ }), _el$19);
50711
+ insert(_el$19, () => ` \u2192 ${askAnswerOf(entry)}`);
50518
50712
  effect((_p$) => {
50519
- var _v$14 = reasoning(), _v$15 = askDeclinedOf(entry) ? reasoning() : answer();
50520
- _v$14 !== _p$.e && (_p$.e = setProp(_el$15, "fg", _v$14, _p$.e));
50521
- _v$15 !== _p$.t && (_p$.t = setProp(_el$16, "fg", _v$15, _p$.t));
50713
+ var _v$16 = reasoning(), _v$17 = askDeclinedOf(entry) ? reasoning() : answer();
50714
+ _v$16 !== _p$.e && (_p$.e = setProp(_el$18, "fg", _v$16, _p$.e));
50715
+ _v$17 !== _p$.t && (_p$.t = setProp(_el$19, "fg", _v$17, _p$.t));
50522
50716
  return _p$;
50523
50717
  }, {
50524
50718
  e: undefined,
50525
50719
  t: undefined
50526
50720
  });
50527
- return _el$14;
50721
+ return _el$17;
50528
50722
  })()
50529
50723
  }));
50530
- return _el$13;
50724
+ return _el$16;
50531
50725
  })();
50532
50726
  }
50533
50727
  var SIDES_RULE, SIDES_FRAME, CODE_RENDER_NODE_CACHE_MAX = 256, codeRenderNodeCache;
@@ -50811,6 +51005,252 @@ var init_notices_dock = __esm(() => {
50811
51005
  noticeList = notices;
50812
51006
  });
50813
51007
 
51008
+ // ../tui-base/src/routes/session/recovery-banner.tsx
51009
+ function widthSafeBannerReason(banner) {
51010
+ const reason = banner?.reason ?? "";
51011
+ const holder = banner?.holder;
51012
+ if (holder === undefined || holder.length <= 8 || !reason.includes(holder))
51013
+ return reason;
51014
+ return reason.replace(holder, `${holder.slice(0, 8)}\u2026`);
51015
+ }
51016
+ function RecoveryBanner(props) {
51017
+ const theme = useThemeOptional();
51018
+ const [version, setVersion] = createSignal(0);
51019
+ onCleanup(props.controller.subscribe(() => setVersion((v) => v + 1)));
51020
+ const controller = props.controller;
51021
+ const banner = () => {
51022
+ version();
51023
+ return controller.banner;
51024
+ };
51025
+ const actions = () => {
51026
+ if (banner() === undefined)
51027
+ return [];
51028
+ return banner()?.kind === "failed" ? [{
51029
+ label: controller.texts.reconnect(),
51030
+ run: () => void controller.recover()
51031
+ }, {
51032
+ label: controller.texts.newSession(),
51033
+ run: () => controller.newSession()
51034
+ }, {
51035
+ label: controller.texts.quit(),
51036
+ run: () => controller.quit()
51037
+ }] : [{
51038
+ label: controller.texts.retry(),
51039
+ run: () => void controller.recover()
51040
+ }, {
51041
+ label: controller.texts.newSession(),
51042
+ run: () => controller.newSession()
51043
+ }];
51044
+ };
51045
+ const warning = () => theme?.text.feedback.warning.base ?? "#e0af68";
51046
+ return createComponent2(Show, {
51047
+ get when() {
51048
+ return banner() !== undefined;
51049
+ },
51050
+ fallback: null,
51051
+ get children() {
51052
+ var _el$ = createElement("box"), _el$2 = createElement("text"), _el$3 = createElement("box");
51053
+ insertNode(_el$, _el$2);
51054
+ insertNode(_el$, _el$3);
51055
+ setProp(_el$, "flexShrink", 0);
51056
+ setProp(_el$, "width", "100%");
51057
+ setProp(_el$, "flexDirection", "column");
51058
+ setProp(_el$, "border", true);
51059
+ setProp(_el$, "borderStyle", "single");
51060
+ setProp(_el$, "paddingLeft", 1);
51061
+ setProp(_el$, "paddingRight", 1);
51062
+ setProp(_el$2, "wrapMode", "none");
51063
+ insert(_el$2, () => widthSafeBannerReason(banner()));
51064
+ setProp(_el$3, "flexDirection", "row");
51065
+ setProp(_el$3, "gap", 2);
51066
+ setProp(_el$3, "height", 1);
51067
+ insert(_el$3, createComponent2(For, {
51068
+ get each() {
51069
+ return actions();
51070
+ },
51071
+ children: (action) => (() => {
51072
+ var _el$4 = createElement("text");
51073
+ setProp(_el$4, "wrapMode", "none");
51074
+ setProp(_el$4, "onMouseUp", () => action.run());
51075
+ insert(_el$4, () => action.label);
51076
+ effect((_$p) => setProp(_el$4, "fg", theme?.text.muted ?? "#9aa5ce", _$p));
51077
+ return _el$4;
51078
+ })()
51079
+ }));
51080
+ effect((_p$) => {
51081
+ var _v$ = warning(), _v$2 = warning();
51082
+ _v$ !== _p$.e && (_p$.e = setProp(_el$, "borderColor", _v$, _p$.e));
51083
+ _v$2 !== _p$.t && (_p$.t = setProp(_el$2, "fg", _v$2, _p$.t));
51084
+ return _p$;
51085
+ }, {
51086
+ e: undefined,
51087
+ t: undefined
51088
+ });
51089
+ return _el$;
51090
+ }
51091
+ });
51092
+ }
51093
+ var init_recovery_banner = __esm(() => {
51094
+ init_index_bun();
51095
+ init_index_bun();
51096
+ init_index_bun();
51097
+ init_index_bun();
51098
+ init_index_bun();
51099
+ init_index_bun();
51100
+ init_server();
51101
+ init_theme3();
51102
+ });
51103
+
51104
+ // ../tui-base/src/routes/session/recovery-ui.ts
51105
+ function asRecord3(value) {
51106
+ return typeof value === "object" && value !== null ? value : {};
51107
+ }
51108
+ function reasonOf(details) {
51109
+ const error = asRecord3(details.error);
51110
+ for (const value of [error.message, details.message]) {
51111
+ if (typeof value === "string" && value.trim() !== "")
51112
+ return value;
51113
+ }
51114
+ return "";
51115
+ }
51116
+
51117
+ class RecoveryUiController {
51118
+ texts;
51119
+ #recover;
51120
+ #onNotice;
51121
+ #onNewSession;
51122
+ #onQuit;
51123
+ #phase = "ready";
51124
+ #banner;
51125
+ #listeners = new Set;
51126
+ constructor(options) {
51127
+ this.#recover = options.recover;
51128
+ this.texts = options.texts;
51129
+ this.#onNotice = options.onNotice;
51130
+ this.#onNewSession = options.onNewSession;
51131
+ this.#onQuit = options.onQuit;
51132
+ }
51133
+ get phase() {
51134
+ return this.#phase;
51135
+ }
51136
+ get banner() {
51137
+ return this.#banner;
51138
+ }
51139
+ get composerDisabled() {
51140
+ return this.#phase === "recovering";
51141
+ }
51142
+ get footerStatus() {
51143
+ if (this.#phase === "recovering")
51144
+ return "recovering";
51145
+ if (this.#phase === "ready")
51146
+ return "ready";
51147
+ return "dead";
51148
+ }
51149
+ canRecover() {
51150
+ return this.#phase === "dead" || this.#phase === "failed" || this.#phase === "locked";
51151
+ }
51152
+ subscribe(listener) {
51153
+ this.#listeners.add(listener);
51154
+ return () => this.#listeners.delete(listener);
51155
+ }
51156
+ #emit() {
51157
+ for (const listener of [...this.#listeners])
51158
+ listener();
51159
+ }
51160
+ #phaseTo(next) {
51161
+ if (this.#phase === next)
51162
+ return;
51163
+ this.#phase = next;
51164
+ this.#emit();
51165
+ }
51166
+ #bannerTo(next) {
51167
+ this.#banner = next;
51168
+ this.#emit();
51169
+ }
51170
+ handleEvent(event) {
51171
+ switch (event.type) {
51172
+ case "bridge.dead":
51173
+ this.#bannerTo(undefined);
51174
+ this.#phaseTo("dead");
51175
+ return;
51176
+ case "bridge.recovered": {
51177
+ const details = asRecord3(event.details);
51178
+ const count = typeof details.applied === "number" ? details.applied : 0;
51179
+ this.#bannerTo(undefined);
51180
+ this.#phaseTo("ready");
51181
+ this.#onNotice?.(this.texts.recovered(count), RECOVERY_NOTICE_TTL_MS);
51182
+ return;
51183
+ }
51184
+ case "bridge.recovery.failed": {
51185
+ const reason = reasonOf(asRecord3(event.details));
51186
+ this.#phaseTo("failed");
51187
+ this.#bannerTo({ kind: "failed", reason: this.texts.failedReason(reason) });
51188
+ return;
51189
+ }
51190
+ case "bridge.recovery.locked": {
51191
+ const details = asRecord3(event.details);
51192
+ const sessionId = typeof details.sessionId === "string" ? details.sessionId : undefined;
51193
+ const detailMessage = typeof details.message === "string" && details.message.trim() !== "" ? details.message : undefined;
51194
+ const rawReason = detailMessage ?? reasonOf(details);
51195
+ const errorDetail = asRecord3(asRecord3(details.error).detail);
51196
+ const holderValue = typeof details.holder === "string" ? details.holder : errorDetail.holder;
51197
+ const holder = typeof holderValue === "string" && holderValue !== "" && holderValue !== "unknown" ? holderValue : undefined;
51198
+ const holderSuffix = holder !== undefined && rawReason.includes(holder) ? undefined : holder;
51199
+ const reason = this.texts.locked(rawReason !== "" ? rawReason : undefined, holderSuffix);
51200
+ this.#phaseTo("locked");
51201
+ this.#bannerTo({ kind: "locked", reason, sessionId, holder });
51202
+ this.#onNotice?.(reason, RECOVERY_NOTICE_TTL_MS);
51203
+ return;
51204
+ }
51205
+ default:
51206
+ return;
51207
+ }
51208
+ }
51209
+ async recover() {
51210
+ if (!this.canRecover())
51211
+ return;
51212
+ this.#bannerTo(undefined);
51213
+ this.#phaseTo("recovering");
51214
+ this.#onNotice?.(this.texts.transient(), RECOVERY_NOTICE_TTL_MS);
51215
+ try {
51216
+ await this.#recover();
51217
+ } catch (err) {
51218
+ const code = err?.code;
51219
+ const detail = asRecord3(err?.detail);
51220
+ if (code === "BRIDGE_RECOVERY_COOLDOWN" && typeof detail.remainingMs === "number" && Number.isFinite(detail.remainingMs)) {
51221
+ this.#phaseTo("dead");
51222
+ this.#onNotice?.(this.texts.cooldown(detail.remainingMs), RECOVERY_NOTICE_TTL_MS);
51223
+ return;
51224
+ }
51225
+ const reason = err instanceof Error ? err.message : String(err);
51226
+ this.#phaseTo("failed");
51227
+ this.#bannerTo({ kind: "failed", reason: this.texts.failedReason(reason) });
51228
+ }
51229
+ }
51230
+ clearRecoveryState() {
51231
+ this.#bannerTo(undefined);
51232
+ this.#phaseTo("ready");
51233
+ }
51234
+ newSession() {
51235
+ this.#onNewSession?.();
51236
+ this.clearRecoveryState();
51237
+ }
51238
+ quit() {
51239
+ this.#onQuit?.();
51240
+ }
51241
+ reconnectCommand() {
51242
+ return {
51243
+ id: RECOVERY_RECONNECT_COMMAND,
51244
+ title: this.texts.reconnect(),
51245
+ group: "Session",
51246
+ bind: RECOVERY_RECONNECT_BIND,
51247
+ enabled: () => this.canRecover(),
51248
+ run: () => void this.recover()
51249
+ };
51250
+ }
51251
+ }
51252
+ var RECOVERY_NOTICE_TTL_MS = 4000, RECOVERY_RECONNECT_BIND = "r", RECOVERY_RECONNECT_COMMAND = "session.bridge.recover";
51253
+
50814
51254
  // ../tui-base/src/routes/session/comet-track.tsx
50815
51255
  import { parseColor as parseColor4, Renderable as Renderable7 } from "@opentui/core";
50816
51256
  function cometHeadColor(theme) {
@@ -51180,6 +51620,7 @@ function rowSearchText(row) {
51180
51620
  case "user":
51181
51621
  case "assistant":
51182
51622
  case "reasoning":
51623
+ case "interrupted":
51183
51624
  return row.text;
51184
51625
  case "tool":
51185
51626
  return `${row.name}${row.args ? `(${row.args})` : ""}${row.output ? ` ${row.output}` : ""}`;
@@ -51795,6 +52236,18 @@ async function stopEverything(seam) {
51795
52236
  }
51796
52237
 
51797
52238
  // ../tui-base/src/routes/session/turn-overlay-controller.ts
52239
+ function askSignature(questions) {
52240
+ return JSON.stringify(questions.map((question) => [
52241
+ question.id,
52242
+ question.prompt,
52243
+ question.header,
52244
+ question.description,
52245
+ question.detail,
52246
+ question.multiSelect === true,
52247
+ question.options.map((option) => [option.label, option.description])
52248
+ ]));
52249
+ }
52250
+
51798
52251
  class TurnOverlayController {
51799
52252
  #approvals = [];
51800
52253
  #asks = [];
@@ -51802,10 +52255,94 @@ class TurnOverlayController {
51802
52255
  #listeners = new Set;
51803
52256
  #idleHandlers = new Set;
51804
52257
  #busy = false;
52258
+ #pendingAsks;
51805
52259
  subscribe(fn) {
51806
52260
  this.#listeners.add(fn);
51807
52261
  return () => this.#listeners.delete(fn);
51808
52262
  }
52263
+ attachPendingAsks(read) {
52264
+ this.#pendingAsks = read;
52265
+ }
52266
+ invalidateAsk(eventId, reason) {
52267
+ if (eventId === "")
52268
+ return;
52269
+ if (this.#approvals.some((entry) => entry.request.invalidatedReason !== undefined && entry.request.eventId === eventId))
52270
+ return;
52271
+ this.#approvals = this.#approvals.filter((entry) => {
52272
+ if (entry.request.eventId !== eventId)
52273
+ return true;
52274
+ entry.resolve("rejected");
52275
+ return false;
52276
+ });
52277
+ this.#asks = this.#asks.filter((entry) => {
52278
+ if (entry.eventId !== eventId)
52279
+ return true;
52280
+ entry.resolve([]);
52281
+ return false;
52282
+ });
52283
+ this.#approvals.push({
52284
+ request: {
52285
+ id: ++this.#seq,
52286
+ name: "ask",
52287
+ args: {},
52288
+ eventId,
52289
+ escalation: false,
52290
+ invalidatedReason: reason
52291
+ },
52292
+ resolve: () => {}
52293
+ });
52294
+ this.#changed();
52295
+ }
52296
+ invalidateAll(reason) {
52297
+ if (reason === "")
52298
+ return;
52299
+ const open = this.#approvals.length + this.#asks.length;
52300
+ if (open === 0)
52301
+ return;
52302
+ const terminals = [];
52303
+ for (const entry of this.#approvals) {
52304
+ terminals.push({
52305
+ request: {
52306
+ id: ++this.#seq,
52307
+ name: "ask",
52308
+ args: {},
52309
+ ...entry.request.eventId !== undefined ? { eventId: entry.request.eventId } : {},
52310
+ escalation: false,
52311
+ invalidatedReason: reason
52312
+ },
52313
+ resolve: () => {}
52314
+ });
52315
+ }
52316
+ for (const entry of this.#asks) {
52317
+ terminals.push({
52318
+ request: {
52319
+ id: ++this.#seq,
52320
+ name: "ask",
52321
+ args: {},
52322
+ ...entry.eventId !== undefined ? { eventId: entry.eventId } : {},
52323
+ escalation: false,
52324
+ invalidatedReason: reason
52325
+ },
52326
+ resolve: () => {}
52327
+ });
52328
+ }
52329
+ for (const entry of this.#approvals)
52330
+ entry.resolve("rejected");
52331
+ for (const entry of this.#asks)
52332
+ entry.resolve([]);
52333
+ this.#approvals = terminals;
52334
+ this.#asks = [];
52335
+ this.#changed();
52336
+ }
52337
+ pendingInvalidated() {
52338
+ const out = new Map;
52339
+ for (const entry of this.#approvals) {
52340
+ if (entry.request.invalidatedReason !== undefined && entry.request.eventId !== undefined) {
52341
+ out.set(entry.request.eventId, entry.request.invalidatedReason);
52342
+ }
52343
+ }
52344
+ return out;
52345
+ }
51809
52346
  onIdle(fn) {
51810
52347
  this.#idleHandlers.add(fn);
51811
52348
  return () => this.#idleHandlers.delete(fn);
@@ -51829,10 +52366,36 @@ class TurnOverlayController {
51829
52366
  return this.#asks.length;
51830
52367
  }
51831
52368
  requestApproval(name, args) {
51832
- return new Promise((resolve) => {
51833
- this.#approvals.push({ request: { id: ++this.#seq, name, args }, resolve });
52369
+ const ask = this.#matchApproval(name, args);
52370
+ const promise = new Promise((resolve) => {
52371
+ this.#approvals.push({
52372
+ request: {
52373
+ id: ++this.#seq,
52374
+ name,
52375
+ args,
52376
+ escalation: ask?.escalation === true,
52377
+ ...ask !== undefined ? { eventId: ask.eventId } : {}
52378
+ },
52379
+ resolve
52380
+ });
51834
52381
  this.#changed();
51835
52382
  });
52383
+ return promise;
52384
+ }
52385
+ #matchApproval(name, args) {
52386
+ const asks = (this.#pendingAsks?.() ?? []).filter((ask) => ask.kind === "approval");
52387
+ if (asks.length === 0)
52388
+ return;
52389
+ const callId = typeof args.callId === "string" ? args.callId : undefined;
52390
+ if (callId !== undefined) {
52391
+ const byCall = asks.filter((ask) => ask.callId === callId);
52392
+ return byCall.length > 0 ? byCall[byCall.length - 1] : undefined;
52393
+ }
52394
+ const reason = typeof args.reason === "string" ? args.reason : undefined;
52395
+ const byName = asks.filter((ask) => (ask.toolName ?? "tool") === name && (reason === undefined || ask.reason === reason));
52396
+ if (byName.length > 0)
52397
+ return byName[byName.length - 1];
52398
+ return asks.length === 1 ? asks[0] : undefined;
51836
52399
  }
51837
52400
  confirmApproval() {
51838
52401
  this.#settleApproval("allowed-once");
@@ -51840,6 +52403,17 @@ class TurnOverlayController {
51840
52403
  rejectApproval() {
51841
52404
  this.#settleApproval("rejected");
51842
52405
  }
52406
+ approveAlways() {
52407
+ this.#settleEscalated("always");
52408
+ }
52409
+ approveSession() {
52410
+ this.#settleEscalated("session");
52411
+ }
52412
+ #settleEscalated(verdict) {
52413
+ if (this.#approvals[0]?.request.escalation !== true)
52414
+ return;
52415
+ this.#settleApproval(verdict);
52416
+ }
51843
52417
  #settleApproval(verdict) {
51844
52418
  const head = this.#approvals.shift();
51845
52419
  if (!head)
@@ -51847,12 +52421,65 @@ class TurnOverlayController {
51847
52421
  head.resolve(verdict);
51848
52422
  this.#changed();
51849
52423
  }
52424
+ syncPendingAsks() {
52425
+ if (this.#pendingAsks === undefined)
52426
+ return;
52427
+ const asks = this.#pendingAsks();
52428
+ let changed = false;
52429
+ const approvalsBefore = this.#approvals.length;
52430
+ this.#approvals = this.#approvals.filter((entry) => {
52431
+ if (this.#approvalStillPending(entry.request, asks))
52432
+ return true;
52433
+ entry.resolve("rejected");
52434
+ return false;
52435
+ });
52436
+ if (this.#approvals.length !== approvalsBefore)
52437
+ changed = true;
52438
+ const questionsBefore = this.#asks.length;
52439
+ this.#asks = this.#asks.filter((entry) => {
52440
+ if (this.#questionStillPending(entry, asks))
52441
+ return true;
52442
+ entry.resolve([]);
52443
+ return false;
52444
+ });
52445
+ if (this.#asks.length !== questionsBefore)
52446
+ changed = true;
52447
+ if (changed)
52448
+ this.#changed();
52449
+ }
52450
+ #approvalStillPending(request, asks) {
52451
+ if (request.eventId !== undefined)
52452
+ return asks.some((ask) => ask.eventId === request.eventId);
52453
+ return asks.some((ask) => ask.kind === "approval");
52454
+ }
52455
+ #questionStillPending(entry, asks) {
52456
+ if (entry.eventId !== undefined)
52457
+ return asks.some((ask) => ask.eventId === entry.eventId);
52458
+ return asks.some((ask) => ask.kind === "questions");
52459
+ }
52460
+ cancelAllApprovals() {
52461
+ if (this.#approvals.length === 0)
52462
+ return;
52463
+ const entries = this.#approvals.splice(0);
52464
+ for (const entry of entries)
52465
+ entry.resolve("rejected");
52466
+ this.#changed();
52467
+ }
52468
+ cancelAllAsks() {
52469
+ if (this.#asks.length === 0)
52470
+ return;
52471
+ const entries = this.#asks.splice(0);
52472
+ for (const entry of entries)
52473
+ entry.resolve([]);
52474
+ this.#changed();
52475
+ }
51850
52476
  get pendingAsk() {
51851
52477
  const head = this.#asks[0];
51852
52478
  if (!head)
51853
52479
  return;
51854
52480
  return {
51855
52481
  id: head.id,
52482
+ ...head.eventId !== undefined ? { eventId: head.eventId } : {},
51856
52483
  questions: head.questions,
51857
52484
  index: head.index,
51858
52485
  picks: head.picks,
@@ -51868,12 +52495,28 @@ class TurnOverlayController {
51868
52495
  const head = this.#asks[0];
51869
52496
  return head?.questions[head.index];
51870
52497
  }
52498
+ #matchAsk(questions) {
52499
+ const asks = (this.#pendingAsks?.() ?? []).filter((ask) => ask.kind === "questions");
52500
+ if (asks.length === 0)
52501
+ return;
52502
+ const claimed = new Set(this.#asks.map((entry) => entry.eventId));
52503
+ const available = asks.filter((ask) => !claimed.has(ask.eventId));
52504
+ if (available.length === 0)
52505
+ return;
52506
+ const signature = askSignature(questions);
52507
+ const exact = available.filter((ask) => askSignature(ask.questions ?? []) === signature);
52508
+ if (exact.length > 0)
52509
+ return exact[0];
52510
+ return available.length === 1 ? available[0] : undefined;
52511
+ }
51871
52512
  answer(questions) {
51872
52513
  if (questions.length === 0)
51873
52514
  return Promise.resolve([]);
52515
+ const ask = this.#matchAsk(questions);
51874
52516
  return new Promise((resolve) => {
51875
52517
  this.#asks.push({
51876
52518
  id: ++this.#seq,
52519
+ ...ask !== undefined ? { eventId: ask.eventId } : {},
51877
52520
  questions,
51878
52521
  index: 0,
51879
52522
  picks: questions.map((question) => recommendedPicks(question)),
@@ -52200,9 +52843,13 @@ function DialogConfirm(props) {
52200
52843
  props.onCancel?.();
52201
52844
  dialog.clear();
52202
52845
  };
52846
+ const chooseExtra = (action) => {
52847
+ action.onTrigger();
52848
+ dialog.clear();
52849
+ };
52203
52850
  Keymap2.createLayer(() => ({
52204
52851
  mode: "modal",
52205
- commands: newDesigns() ? [{
52852
+ commands: [...newDesigns() ? [{
52206
52853
  bind: "return",
52207
52854
  title: "Confirm",
52208
52855
  group: "Dialog",
@@ -52231,7 +52878,12 @@ function DialogConfirm(props) {
52231
52878
  run: () => {
52232
52879
  setStore("active", store.active === "confirm" ? "cancel" : "confirm");
52233
52880
  }
52234
- }]
52881
+ }], ...(props.extraActions ?? []).map((action) => ({
52882
+ bind: action.bind,
52883
+ title: action.title ?? action.label,
52884
+ group: "Dialog",
52885
+ run: () => chooseExtra(action)
52886
+ }))]
52235
52887
  }));
52236
52888
  return createComponent2(DialogLayout, {
52237
52889
  get header() {
@@ -52264,6 +52916,11 @@ function DialogConfirm(props) {
52264
52916
  get footer() {
52265
52917
  return {
52266
52918
  actions: {
52919
+ secondary: (props.extraActions ?? []).map((action) => ({
52920
+ title: action.label.toLowerCase(),
52921
+ key: action.bind,
52922
+ onTrigger: () => chooseExtra(action)
52923
+ })),
52267
52924
  primary: [
52268
52925
  {
52269
52926
  title: (props.label?.cancel ?? "cancel").toLowerCase(),
@@ -52281,28 +52938,48 @@ function DialogConfirm(props) {
52281
52938
  },
52282
52939
  get legacyFooter() {
52283
52940
  return (() => {
52284
- var _el$4 = createElement("box");
52941
+ var _el$4 = createElement("box"), _el$5 = createElement("box"), _el$6 = createElement("box");
52942
+ insertNode(_el$4, _el$5);
52943
+ insertNode(_el$4, _el$6);
52285
52944
  setProp(_el$4, "flexDirection", "row");
52286
- setProp(_el$4, "justifyContent", "flex-end");
52287
- insert(_el$4, createComponent2(For, {
52945
+ setProp(_el$4, "justifyContent", "space-between");
52946
+ setProp(_el$4, "gap", 1);
52947
+ setProp(_el$5, "flexDirection", "row");
52948
+ insert(_el$5, createComponent2(For, {
52949
+ get each() {
52950
+ return props.extraActions ?? [];
52951
+ },
52952
+ children: (action) => (() => {
52953
+ var _el$7 = createElement("box"), _el$8 = createElement("text");
52954
+ insertNode(_el$7, _el$8);
52955
+ setProp(_el$7, "paddingLeft", 1);
52956
+ setProp(_el$7, "paddingRight", 1);
52957
+ setProp(_el$7, "onMouseUp", () => chooseExtra(action));
52958
+ insert(_el$8, () => `${action.label} [${action.bind}]`);
52959
+ effect((_$p) => setProp(_el$8, "fg", theme.text.muted, _$p));
52960
+ return _el$7;
52961
+ })()
52962
+ }));
52963
+ setProp(_el$6, "flexDirection", "row");
52964
+ insert(_el$6, createComponent2(For, {
52288
52965
  each: ["cancel", "confirm"],
52289
52966
  children: (key) => (() => {
52290
- var _el$5 = createElement("box"), _el$6 = createElement("text");
52291
- insertNode(_el$5, _el$6);
52292
- setProp(_el$5, "paddingLeft", 1);
52293
- setProp(_el$5, "paddingRight", 1);
52294
- setProp(_el$5, "onMouseUp", () => choose(key));
52295
- insert(_el$6, () => titlecase(props.label?.[key] ?? key));
52967
+ var _el$9 = createElement("box"), _el$0 = createElement("text");
52968
+ insertNode(_el$9, _el$0);
52969
+ setProp(_el$9, "paddingLeft", 1);
52970
+ setProp(_el$9, "paddingRight", 1);
52971
+ setProp(_el$9, "onMouseUp", () => choose(key));
52972
+ insert(_el$0, () => titlecase(props.label?.[key] ?? key));
52296
52973
  effect((_p$) => {
52297
52974
  var _v$3 = key === store.active ? row().backgroundColor : undefined, _v$4 = key === store.active ? row().textColor : theme.text.muted;
52298
- _v$3 !== _p$.e && (_p$.e = setProp(_el$5, "backgroundColor", _v$3, _p$.e));
52299
- _v$4 !== _p$.t && (_p$.t = setProp(_el$6, "fg", _v$4, _p$.t));
52975
+ _v$3 !== _p$.e && (_p$.e = setProp(_el$9, "backgroundColor", _v$3, _p$.e));
52976
+ _v$4 !== _p$.t && (_p$.t = setProp(_el$0, "fg", _v$4, _p$.t));
52300
52977
  return _p$;
52301
52978
  }, {
52302
52979
  e: undefined,
52303
52980
  t: undefined
52304
52981
  });
52305
- return _el$5;
52982
+ return _el$9;
52306
52983
  })()
52307
52984
  }));
52308
52985
  return _el$4;
@@ -52323,6 +53000,7 @@ var init_dialog_confirm = __esm(() => {
52323
53000
  init_index_bun();
52324
53001
  init_index_bun();
52325
53002
  init_index_bun();
53003
+ init_index_bun();
52326
53004
  init_keymap();
52327
53005
  init_theme3();
52328
53006
  init_config();
@@ -53447,23 +54125,40 @@ function summarizeArgs(name, args, limit = 160) {
53447
54125
  return `${name} ${body}`.trim();
53448
54126
  }
53449
54127
  function ApprovalCard(props) {
54128
+ const invalidated = () => props.invalidatedReason !== undefined;
53450
54129
  return createComponent2(DialogConfirm, {
53451
54130
  get title() {
53452
- return t("overlay.ask.approvalTitle", {
54131
+ return memo2(() => !!invalidated())() ? t("overlay.ask.invalidatedTitle") : t("overlay.ask.approvalTitle", {
53453
54132
  name: props.name
53454
54133
  });
53455
54134
  },
53456
54135
  get message() {
53457
- return summarizeArgs(props.name, props.args);
54136
+ return memo2(() => !!invalidated())() ? t("overlay.ask.invalidated", {
54137
+ reason: props.invalidatedReason ?? ""
54138
+ }) : summarizeArgs(props.name, props.args);
53458
54139
  },
53459
54140
  get label() {
53460
- return {
54141
+ return memo2(() => !!invalidated())() ? {
54142
+ confirm: t("overlay.ask.invalidatedAck"),
54143
+ cancel: t("overlay.ask.invalidatedAck")
54144
+ } : {
53461
54145
  confirm: t("overlay.ask.allow"),
53462
54146
  cancel: t("overlay.ask.reject")
53463
54147
  };
53464
54148
  },
53465
54149
  onConfirm: () => props.onVerdict("allowed-once"),
53466
- onCancel: () => props.onVerdict("rejected")
54150
+ onCancel: () => props.onVerdict("rejected"),
54151
+ get extraActions() {
54152
+ return memo2(() => !!(!invalidated() && props.escalation === true))() ? [{
54153
+ label: t("overlay.ask.allowAlways"),
54154
+ bind: "a",
54155
+ onTrigger: () => props.onVerdict("always")
54156
+ }, {
54157
+ label: t("overlay.ask.allowSession"),
54158
+ bind: "s",
54159
+ onTrigger: () => props.onVerdict("session")
54160
+ }] : undefined;
54161
+ }
53467
54162
  });
53468
54163
  }
53469
54164
  function ReminderBadge() {
@@ -53496,6 +54191,8 @@ function TurnOverlayHost(props) {
53496
54191
  onMount(() => {
53497
54192
  const unsubscribe = props.controller.subscribe(() => setVersion((value) => value + 1));
53498
54193
  onCleanup(unsubscribe);
54194
+ const timer = setInterval(() => props.controller.syncPendingAsks(), 200);
54195
+ onCleanup(() => clearInterval(timer));
53499
54196
  });
53500
54197
  props.controller.onIdle(() => {
53501
54198
  setTimeout(() => props.reclaimFocus?.(), 3);
@@ -53520,29 +54217,55 @@ function TurnOverlayHost(props) {
53520
54217
  const key = approvalWins ? `approval:${approval.id}` : askAdmitted ? `ask:${ask.id}` : "";
53521
54218
  if (key === shown)
53522
54219
  return;
54220
+ const previousKey = shown;
53523
54221
  shown = key;
54222
+ if (previousKey?.startsWith("approval:") === true && dialog.stack.at(-1)?.key === previousKey) {
54223
+ dialog.clear();
54224
+ }
53524
54225
  if (approvalWins) {
53525
54226
  closeAsk();
53526
54227
  const atOpen = key;
53527
- dialog.replace(() => createComponent2(ApprovalCard, {
53528
- get name() {
53529
- return approval.name;
53530
- },
53531
- get args() {
53532
- return approval.args;
53533
- },
53534
- onVerdict: (verdict) => {
53535
- if (verdict === "allowed-once")
53536
- props.controller.confirmApproval();
53537
- else
54228
+ const approvalId = approval.id;
54229
+ try {
54230
+ dialog.replace(() => createComponent2(ApprovalCard, {
54231
+ get name() {
54232
+ return approval.name;
54233
+ },
54234
+ get args() {
54235
+ return approval.args;
54236
+ },
54237
+ get escalation() {
54238
+ return approval.escalation;
54239
+ },
54240
+ get invalidatedReason() {
54241
+ return approval.invalidatedReason;
54242
+ },
54243
+ onVerdict: (verdict) => {
54244
+ switch (verdict) {
54245
+ case "allowed-once":
54246
+ props.controller.confirmApproval();
54247
+ break;
54248
+ case "always":
54249
+ props.controller.approveAlways();
54250
+ break;
54251
+ case "session":
54252
+ props.controller.approveSession();
54253
+ break;
54254
+ default:
54255
+ props.controller.rejectApproval();
54256
+ }
54257
+ }
54258
+ }), () => {
54259
+ if (shown === atOpen && props.controller.pendingApproval?.id === approvalId) {
53538
54260
  props.controller.rejectApproval();
53539
- }
53540
- }), () => {
53541
- if (shown === atOpen)
53542
- props.controller.rejectApproval();
53543
- }, {
53544
- tone: "warning"
53545
- });
54261
+ }
54262
+ }, {
54263
+ key,
54264
+ tone: "warning"
54265
+ });
54266
+ } catch {
54267
+ props.controller.rejectApproval();
54268
+ }
53546
54269
  return;
53547
54270
  }
53548
54271
  if (ask !== undefined && askAdmitted) {
@@ -53580,7 +54303,30 @@ function TurnOverlayHost(props) {
53580
54303
  children: null
53581
54304
  });
53582
54305
  }
53583
- function registerTurnOverlays(seam, controller) {
54306
+ function registerTurnOverlays(seam, controller, options) {
54307
+ if (typeof seam.pendingAsks === "function") {
54308
+ const read = seam.pendingAsks.bind(seam);
54309
+ controller.attachPendingAsks(() => read() ?? []);
54310
+ }
54311
+ if (typeof seam.onSessionEvent === "function") {
54312
+ seam.onSessionEvent((event) => {
54313
+ if (event.type === "bridge.dead") {
54314
+ const configured = options?.deadReason;
54315
+ if (configured === undefined)
54316
+ return;
54317
+ const reason = typeof configured === "function" ? configured(event.details) : configured;
54318
+ if (reason !== "")
54319
+ controller.invalidateAll(reason);
54320
+ return;
54321
+ }
54322
+ if (event.type !== "bridge.ask.invalidated")
54323
+ return;
54324
+ const details = event.details;
54325
+ if (typeof details?.eventId !== "string")
54326
+ return;
54327
+ controller.invalidateAsk(details.eventId, typeof details.reason === "string" ? details.reason : "");
54328
+ });
54329
+ }
53584
54330
  seam.registerAskProvider((questions) => controller.answer(questions));
53585
54331
  }
53586
54332
  var init_turn_overlays = __esm(() => {
@@ -53590,6 +54336,7 @@ var init_turn_overlays = __esm(() => {
53590
54336
  init_index_bun();
53591
54337
  init_index_bun();
53592
54338
  init_index_bun();
54339
+ init_index_bun();
53593
54340
  init_server();
53594
54341
  init_index_bun();
53595
54342
  init_dialog_confirm();
@@ -53632,8 +54379,8 @@ function sessionInfoRows(info) {
53632
54379
  return [
53633
54380
  { field: "session", value: info.sessionId ?? "\u2014" },
53634
54381
  { field: "model", value: info.model ?? "\u2014" },
53635
- { field: "messages", value: String(info.messageCount) },
53636
- { field: "turns", value: String(info.turnCount) },
54382
+ { field: "messages", value: info.messageCount === undefined ? "\u2014" : String(info.messageCount) },
54383
+ { field: "turns", value: info.turnCount === undefined ? "\u2014" : String(info.turnCount) },
53637
54384
  { field: "tokens in/out", value: `${info.tokensIn} / ${info.tokensOut}` },
53638
54385
  { field: "cache read/write", value: `${info.cacheRead} / ${info.cacheWrite}` },
53639
54386
  { field: "speed", value: speed }
@@ -53971,6 +54718,7 @@ function coreCommands() {
53971
54718
  ctx.seam.newSession();
53972
54719
  ctx.clear();
53973
54720
  await ctx.reload();
54721
+ ctx.clearRecoveryUi?.();
53974
54722
  ctx.say(t("command.new.created", { id: ctx.seam.currentSessionId() ?? "(unnamed)" }));
53975
54723
  }
53976
54724
  },
@@ -54787,7 +55535,8 @@ function buildSlashDeps(base, hooks) {
54787
55535
  openSubagents: hooks.openSubagents,
54788
55536
  refreshFooter: hooks.refreshFooter,
54789
55537
  invalidateFooter: hooks.invalidateFooter,
54790
- flushQueue: hooks.flushQueue
55538
+ flushQueue: hooks.flushQueue,
55539
+ clearRecoveryUi: hooks.clearRecoveryUi
54791
55540
  };
54792
55541
  }
54793
55542
  function carrySlashHooks(deps) {
@@ -54814,7 +55563,8 @@ var init_slash_deps = __esm(() => {
54814
55563
  "openSubagents",
54815
55564
  "refreshFooter",
54816
55565
  "invalidateFooter",
54817
- "flushQueue"
55566
+ "flushQueue",
55567
+ "clearRecoveryUi"
54818
55568
  ];
54819
55569
  });
54820
55570
 
@@ -61706,7 +62456,7 @@ var init_agents_panel = __esm(() => {
61706
62456
  });
61707
62457
 
61708
62458
  // ../tui-base/src/routes/session/history-data.ts
61709
- function asRecord3(value) {
62459
+ function asRecord4(value) {
61710
62460
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
61711
62461
  }
61712
62462
  function blocksText2(content) {
@@ -61714,7 +62464,7 @@ function blocksText2(content) {
61714
62464
  return "";
61715
62465
  let text = "";
61716
62466
  for (const block of content) {
61717
- const typed = asRecord3(block);
62467
+ const typed = asRecord4(block);
61718
62468
  if (typeof typed.text === "string" && typed.type === "text") {
61719
62469
  text += (text === "" ? "" : `
61720
62470
  `) + typed.text;
@@ -61723,7 +62473,7 @@ function blocksText2(content) {
61723
62473
  return text.trim();
61724
62474
  }
61725
62475
  function sourceKind2(data) {
61726
- return asRecord3(data.source).kind;
62476
+ return asRecord4(data.source).kind;
61727
62477
  }
61728
62478
  function groupHistoryTurns(entries) {
61729
62479
  const turns = [];
@@ -61779,7 +62529,7 @@ function groupHistoryTurns(entries) {
61779
62529
  break;
61780
62530
  }
61781
62531
  case "assistant/message": {
61782
- const message = asRecord3(entry.data.message);
62532
+ const message = asRecord4(entry.data.message);
61783
62533
  const text = blocksText2(message.content);
61784
62534
  if (text !== "")
61785
62535
  open.assistantTexts.push(text);
@@ -61797,7 +62547,7 @@ function groupHistoryTurns(entries) {
61797
62547
  break;
61798
62548
  }
61799
62549
  case "tool/result": {
61800
- const message = asRecord3(entry.data.message);
62550
+ const message = asRecord4(entry.data.message);
61801
62551
  const callId = entry.data.callId !== undefined ? String(entry.data.callId) : message.toolCallId !== undefined ? String(message.toolCallId) : "";
61802
62552
  const index = callId === "" ? undefined : open.callIndex.get(callId);
61803
62553
  if (index === undefined)
@@ -61811,9 +62561,9 @@ function groupHistoryTurns(entries) {
61811
62561
  case "turn/end": {
61812
62562
  open.seqEnd = entry.seq;
61813
62563
  open.endTime = typeof entry.time === "number" ? entry.time : undefined;
61814
- const reason = asRecord3(entry.data.reason);
62564
+ const reason = asRecord4(entry.data.reason);
61815
62565
  open.endReason = typeof reason.kind === "string" ? reason.kind : "completed";
61816
- const error = asRecord3(reason.error);
62566
+ const error = asRecord4(reason.error);
61817
62567
  open.endError = typeof error.message === "string" ? error.message : undefined;
61818
62568
  close();
61819
62569
  break;
@@ -62904,7 +63654,7 @@ var init_subagents_viewer = __esm(() => {
62904
63654
  import { TextAttributes as TextAttributes12 } from "@opentui/core";
62905
63655
  function resolveVersion() {
62906
63656
  try {
62907
- return "0.21.1";
63657
+ return "0.23.0";
62908
63658
  } catch {
62909
63659
  return "dev";
62910
63660
  }
@@ -65200,6 +65950,2011 @@ var init_session_seam_adapter = __esm(() => {
65200
65950
  NOTICE_SOURCE_KINDS = new Set(["subagent-settled", "agent-message", "team-message", "webhook"]);
65201
65951
  });
65202
65952
 
65953
+ // src/client/bridge-session-seam.ts
65954
+ function askTurnId(eventId) {
65955
+ const i = eventId.lastIndexOf(":ask-");
65956
+ return i === -1 ? "" : eventId.slice(0, i);
65957
+ }
65958
+ function optionalStringField(row, key) {
65959
+ const value = row[key];
65960
+ return typeof value === "string" && value !== "" ? value : undefined;
65961
+ }
65962
+ function parseAskRequest(value) {
65963
+ const row = asRecord5(value);
65964
+ const eventId = optionalStringField(row, "eventId");
65965
+ const sessionId = optionalStringField(row, "sessionId");
65966
+ const kind = row.kind;
65967
+ if (eventId === undefined || sessionId === undefined || kind !== "approval" && kind !== "questions") {
65968
+ return;
65969
+ }
65970
+ const out = { eventId, sessionId, kind };
65971
+ for (const key of ["toolName", "callId", "reason"]) {
65972
+ const v = optionalStringField(row, key);
65973
+ if (v !== undefined)
65974
+ out[key] = v;
65975
+ }
65976
+ for (const key of ["deadlineAt", "detachGraceMs"]) {
65977
+ const v = row[key];
65978
+ if (typeof v === "number" && Number.isFinite(v))
65979
+ out[key] = v;
65980
+ }
65981
+ if (row.escalation === true)
65982
+ out.escalation = true;
65983
+ if (Array.isArray(row.questions)) {
65984
+ const questions = [];
65985
+ for (const raw of row.questions) {
65986
+ const q = asRecord5(raw);
65987
+ const id = optionalStringField(q, "id");
65988
+ const prompt = optionalStringField(q, "prompt");
65989
+ if (id === undefined || prompt === undefined || !Array.isArray(q.options))
65990
+ continue;
65991
+ const options = [];
65992
+ for (const rawOpt of q.options) {
65993
+ const opt = asRecord5(rawOpt);
65994
+ const label = optionalStringField(opt, "label");
65995
+ if (label === undefined)
65996
+ continue;
65997
+ const description = optionalStringField(opt, "description");
65998
+ options.push({ label, ...description !== undefined ? { description } : {} });
65999
+ }
66000
+ if (options.length === 0)
66001
+ continue;
66002
+ const question = { id, prompt, options };
66003
+ for (const key of ["header", "description", "detail"]) {
66004
+ const v = optionalStringField(q, key);
66005
+ if (v !== undefined)
66006
+ question[key] = v;
66007
+ }
66008
+ if (q.multiSelect === true)
66009
+ question.multiSelect = true;
66010
+ questions.push(question);
66011
+ }
66012
+ if (questions.length > 0)
66013
+ out.questions = questions;
66014
+ }
66015
+ return out;
66016
+ }
66017
+ function approvalArgs(request) {
66018
+ return {
66019
+ ...request.callId !== undefined ? { callId: request.callId } : {},
66020
+ ...request.reason !== undefined ? { reason: request.reason } : {}
66021
+ };
66022
+ }
66023
+ function approvalQuestion(request) {
66024
+ const toolName = request.toolName ?? "tool";
66025
+ return {
66026
+ id: request.eventId,
66027
+ prompt: request.reason ?? `Allow ${toolName}?`,
66028
+ options: [{ label: "allow" }, { label: "deny" }],
66029
+ header: "Approval",
66030
+ ...request.callId !== undefined ? { detail: `callId: ${request.callId}` } : {}
66031
+ };
66032
+ }
66033
+ function approvalVerdictFromPicks(request, picks) {
66034
+ const pick = picks.find((p) => p.questionId === request.eventId);
66035
+ const choice = pick?.custom ?? pick?.selections?.[0] ?? pick?.selected ?? "";
66036
+ return /^(allow|allowed-once|yes|approve)$/i.test(choice) ? "allowed-once" : "rejected";
66037
+ }
66038
+ function answersFor(request, picks) {
66039
+ const questions = request.questions ?? [];
66040
+ if (questions.length === 0) {
66041
+ return picks.map((pick) => ({
66042
+ id: pick.questionId,
66043
+ selected: pick.selections?.length ? [...pick.selections] : [pick.selected],
66044
+ ...pick.custom !== undefined && pick.custom !== "" ? { custom: pick.custom } : {}
66045
+ }));
66046
+ }
66047
+ return questions.map((q) => {
66048
+ const pick = picks.find((p) => p.questionId === q.id);
66049
+ if (pick?.custom !== undefined && pick.custom !== "")
66050
+ return { id: q.id, selected: [], custom: pick.custom };
66051
+ if (pick === undefined || pick.selected === "" && (pick.custom ?? "") === "") {
66052
+ return { id: q.id, selected: [], custom: "declined" };
66053
+ }
66054
+ return {
66055
+ id: q.id,
66056
+ selected: pick.selections?.length ? [...pick.selections] : [pick.selected]
66057
+ };
66058
+ });
66059
+ }
66060
+ function unavailableResponse(request) {
66061
+ return request.kind === "questions" ? { eventId: request.eventId, kind: "questions", verdict: "unavailable", answers: answersFor(request, []) } : { eventId: request.eventId, kind: "approval", verdict: "unavailable" };
66062
+ }
66063
+ function asRecord5(value) {
66064
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
66065
+ }
66066
+ function unsupported(capability) {
66067
+ throw new BridgeProtocolError("UNSUPPORTED", `${capability} is not backed by the in-process bridge`, { capability });
66068
+ }
66069
+ function projectBridgeSessionList(items, limit = 12) {
66070
+ const rows = Array.isArray(items) ? items : [];
66071
+ const out = [];
66072
+ for (const item of rows) {
66073
+ const row = asRecord5(item);
66074
+ if (row.origin === "subagent")
66075
+ continue;
66076
+ const id = typeof row.sessionId === "string" ? row.sessionId : "";
66077
+ if (!id)
66078
+ continue;
66079
+ const updatedAt = typeof row.updatedAt === "number" ? String(row.updatedAt) : "";
66080
+ const values = asRecord5(asRecord5(row.projections).values);
66081
+ const title = typeof values.title === "string" ? values.title : "";
66082
+ out.push({
66083
+ id,
66084
+ title: title.slice(0, 40),
66085
+ ...updatedAt ? { updatedAt } : {},
66086
+ ...typeof row.cwd === "string" && row.cwd ? { cwd: row.cwd } : {},
66087
+ ...typeof row.sizeBytes === "number" && Number.isFinite(row.sizeBytes) ? { sizeBytes: row.sizeBytes } : {},
66088
+ ...typeof row.blank === "boolean" ? { blank: row.blank } : {}
66089
+ });
66090
+ }
66091
+ return out.sort((a, b) => String(b.updatedAt ?? "").localeCompare(String(a.updatedAt ?? ""))).slice(0, limit);
66092
+ }
66093
+ function bridgeReplayRowsToSeamTranscript(rows, skip = 0) {
66094
+ const entries = rows.map((row) => ({
66095
+ type: row.type,
66096
+ seq: row.seq,
66097
+ time: 0,
66098
+ data: asRecord5(row.payload)
66099
+ }));
66100
+ const durable = journalToTranscriptRows(entries, skip);
66101
+ return durable.map((row) => {
66102
+ if (row.kind === "ask") {
66103
+ return { kind: "ask", text: "", final: true, entries: row.entries };
66104
+ }
66105
+ if (row.kind === "tool") {
66106
+ return { kind: "tool", text: row.name, final: true, args: row.args, output: row.brief, ok: row.ok };
66107
+ }
66108
+ return { kind: row.kind, text: row.text, final: true };
66109
+ });
66110
+ }
66111
+ function seamReplayEventKey(event) {
66112
+ const details = asRecord5(event.details);
66113
+ return `${event.type}:${String(details.id ?? details.messageID ?? "")}:${String(asRecord5(details.part).id ?? "")}`;
66114
+ }
66115
+ function bridgeReplayRowsToSeamEvents(rows, sessionId) {
66116
+ const events = [];
66117
+ const seen = new Set;
66118
+ const push = (event) => {
66119
+ const key = seamReplayEventKey(event);
66120
+ if (seen.has(key))
66121
+ return;
66122
+ seen.add(key);
66123
+ events.push(event);
66124
+ };
66125
+ const toolCalls = new Map;
66126
+ for (const row of rows) {
66127
+ const entry = { type: row.type, seq: row.seq, time: 0, data: asRecord5(row.payload) };
66128
+ for (const event of projectJournalRecord(entry, sessionId))
66129
+ push(event);
66130
+ const data = entry.data;
66131
+ if (row.type === "tool/call") {
66132
+ const callId = data.callId === undefined ? "" : String(data.callId);
66133
+ if (callId) {
66134
+ toolCalls.set(callId, {
66135
+ seq: row.seq,
66136
+ name: typeof data.name === "string" ? data.name : "tool",
66137
+ args: typeof data.arguments === "string" ? data.arguments : ""
66138
+ });
66139
+ }
66140
+ } else if (row.type === "tool/result") {
66141
+ const message = asRecord5(data.message);
66142
+ const callId = data.callId !== undefined ? String(data.callId) : message.toolCallId !== undefined ? String(message.toolCallId) : "";
66143
+ const call = callId ? toolCalls.get(callId) : undefined;
66144
+ if (call !== undefined) {
66145
+ toolCalls.delete(callId);
66146
+ const messageID = `journal-${call.seq}`;
66147
+ const ok = data.isError !== true && message.isError !== true;
66148
+ push({
66149
+ type: "message.part.updated",
66150
+ details: {
66151
+ messageID,
66152
+ sessionID: sessionId,
66153
+ part: {
66154
+ type: "tool",
66155
+ id: callId,
66156
+ name: call.name,
66157
+ input: call.args,
66158
+ status: ok ? "done" : "failed",
66159
+ output: JSON.stringify(data.output ?? data).slice(0, 300)
66160
+ }
66161
+ }
66162
+ });
66163
+ }
66164
+ }
66165
+ }
66166
+ return events;
66167
+ }
66168
+ function bridgeAgentRunKey(runId, seq) {
66169
+ return `${runId}:${seq}`;
66170
+ }
66171
+ function bridgeSettledStatus(outcome) {
66172
+ return outcome === "failed" || outcome === "cancelled" ? outcome : "completed";
66173
+ }
66174
+ function bridgeSettleChild(existing, outcome, startedAt, now) {
66175
+ return {
66176
+ id: existing.id,
66177
+ label: existing.label,
66178
+ ...existing.model !== undefined ? { model: existing.model } : {},
66179
+ status: bridgeSettledStatus(outcome),
66180
+ rounds: existing.rounds,
66181
+ elapsedSec: Number(((now - startedAt) / 1000).toFixed(1)),
66182
+ endedAt: now,
66183
+ ...existing.injectedRound !== undefined ? { injectedRound: existing.injectedRound } : {},
66184
+ ...existing.hardStopRound !== undefined ? { hardStopRound: existing.hardStopRound } : {},
66185
+ ...existing.spinStopRound !== undefined ? { spinStopRound: existing.spinStopRound } : {},
66186
+ ...existing.lastLine !== undefined ? { lastLine: existing.lastLine } : {}
66187
+ };
66188
+ }
66189
+ function bridgeFoldAgentRecord(children, runSeq, liveStarts, type, data, now, live) {
66190
+ if (type === "user/message") {
66191
+ const source = asRecord5(data.source);
66192
+ if (source.kind !== BRIDGE_SUBAGENT_SETTLED)
66193
+ return false;
66194
+ const childId = typeof source.senderSessionId === "string" ? source.senderSessionId : "";
66195
+ if (!childId)
66196
+ return false;
66197
+ const existing = children.get(childId);
66198
+ if (!existing || existing.status !== "running")
66199
+ return false;
66200
+ children.set(childId, bridgeSettleChild(existing, source.stopReason, existing.startedAt ?? now, now));
66201
+ return true;
66202
+ }
66203
+ if (type === BRIDGE_SUBAGENT_CATALOG) {
66204
+ const childId = typeof data.childId === "string" ? data.childId : "";
66205
+ if (!childId)
66206
+ return false;
66207
+ const label = typeof data.label === "string" && data.label ? data.label : typeof data.name === "string" ? data.name : "";
66208
+ const childCreatedAt = typeof data.childCreatedAt === "number" && Number.isFinite(data.childCreatedAt) ? data.childCreatedAt : undefined;
66209
+ const existing = children.get(childId);
66210
+ if (existing !== undefined && existing.status !== "running") {
66211
+ runSeq.set(bridgeAgentRunKey(`${BRIDGE_CATALOG_RUN_PREFIX}${childId}`, 0), childId);
66212
+ children.set(childId, {
66213
+ id: existing.id,
66214
+ label: label || existing.label,
66215
+ status: "running",
66216
+ rounds: 0,
66217
+ startedAt: childCreatedAt ?? now,
66218
+ ...existing.model !== undefined ? { model: existing.model } : {}
66219
+ });
66220
+ if (live)
66221
+ liveStarts.add(childId);
66222
+ return true;
66223
+ }
66224
+ return bridgeFoldAgentRecord(children, runSeq, liveStarts, BRIDGE_AGENT_START, {
66225
+ childId,
66226
+ label,
66227
+ runId: `${BRIDGE_CATALOG_RUN_PREFIX}${childId}`,
66228
+ seq: 0,
66229
+ ...childCreatedAt !== undefined ? { childCreatedAt } : {},
66230
+ viaCatalog: true
66231
+ }, now, live);
66232
+ }
66233
+ if (type === BRIDGE_AGENT_START) {
66234
+ const childId = typeof data.childId === "string" ? data.childId : "";
66235
+ if (!childId)
66236
+ return false;
66237
+ const runId = data.runId === undefined ? "" : String(data.runId);
66238
+ if (data.viaCatalog !== true && runId.startsWith(BRIDGE_CATALOG_RUN_PREFIX))
66239
+ return false;
66240
+ const seq = typeof data.seq === "number" ? data.seq : -1;
66241
+ runSeq.set(bridgeAgentRunKey(runId, seq), childId);
66242
+ const childCreatedAt = typeof data.childCreatedAt === "number" && Number.isFinite(data.childCreatedAt) ? data.childCreatedAt : undefined;
66243
+ const existing = children.get(childId);
66244
+ if (existing !== undefined) {
66245
+ const newLabel = typeof data.label === "string" ? data.label : "";
66246
+ const labelChanged = newLabel !== "" && newLabel !== existing.label;
66247
+ const upgradeStart = live && existing.status === "running" && !liveStarts.has(childId);
66248
+ if (!labelChanged && !upgradeStart)
66249
+ return false;
66250
+ children.set(childId, {
66251
+ ...existing,
66252
+ ...labelChanged ? { label: newLabel } : {},
66253
+ ...upgradeStart ? { startedAt: childCreatedAt ?? now } : {}
66254
+ });
66255
+ if (upgradeStart)
66256
+ liveStarts.add(childId);
66257
+ return true;
66258
+ }
66259
+ const label = typeof data.label === "string" && data.label ? data.label : `subagent ${childId.slice(0, 8)}`;
66260
+ children.set(childId, { id: childId, label, status: "running", rounds: 0, startedAt: childCreatedAt ?? now });
66261
+ if (live)
66262
+ liveStarts.add(childId);
66263
+ return true;
66264
+ }
66265
+ if (type === BRIDGE_AGENT_END) {
66266
+ const runId = data.runId === undefined ? "" : String(data.runId);
66267
+ const seq = typeof data.seq === "number" ? data.seq : -1;
66268
+ const key = bridgeAgentRunKey(runId, seq);
66269
+ const childId = runSeq.get(key);
66270
+ if (!childId)
66271
+ return false;
66272
+ const existing = children.get(childId);
66273
+ if (!existing || existing.status !== "running")
66274
+ return false;
66275
+ children.set(childId, bridgeSettleChild(existing, data.outcome, existing.startedAt ?? now, now));
66276
+ runSeq.delete(key);
66277
+ return true;
66278
+ }
66279
+ return false;
66280
+ }
66281
+ function bridgeSweepSettledChildIds(rows, parentId, locallyRunning) {
66282
+ if (parentId === undefined || parentId === "")
66283
+ return [];
66284
+ const settled = [];
66285
+ for (const raw of rows) {
66286
+ const row = asRecord5(raw);
66287
+ if (row.origin !== "subagent")
66288
+ continue;
66289
+ if (row.parentSessionId !== parentId)
66290
+ continue;
66291
+ const id = row.sessionId;
66292
+ if (typeof id !== "string" || id === "")
66293
+ continue;
66294
+ if (row.running !== false)
66295
+ continue;
66296
+ if (!locallyRunning.has(id) || settled.includes(id))
66297
+ continue;
66298
+ settled.push(id);
66299
+ }
66300
+ return settled;
66301
+ }
66302
+ function bridgeBlocksText(content) {
66303
+ if (typeof content === "string")
66304
+ return content.trim();
66305
+ if (!Array.isArray(content))
66306
+ return "";
66307
+ let text = "";
66308
+ for (const block of content) {
66309
+ const typed = block;
66310
+ if (typed?.type === "text" && typeof typed.text === "string") {
66311
+ text += (text === "" ? "" : `
66312
+ `) + typed.text;
66313
+ }
66314
+ }
66315
+ return text.trim();
66316
+ }
66317
+ function bridgeLastContentLine(text) {
66318
+ if (text === undefined)
66319
+ return;
66320
+ const lines = text.replace(/\r\n?/g, `
66321
+ `).split(`
66322
+ `);
66323
+ for (let i = lines.length - 1;i >= 0; i--) {
66324
+ const line = lines[i].trim();
66325
+ if (line !== "")
66326
+ return line.replace(/\s+/gu, " ").slice(0, 240);
66327
+ }
66328
+ return;
66329
+ }
66330
+ function bridgeChildJournalMeta(rows) {
66331
+ let rounds = 0;
66332
+ let lastLine;
66333
+ let contextModel;
66334
+ let descriptorModel;
66335
+ for (const row of rows) {
66336
+ const data = asRecord5(row.payload);
66337
+ if (row.type === "assistant/message") {
66338
+ rounds += 1;
66339
+ const message = asRecord5(data.message);
66340
+ const tail = bridgeLastContentLine(bridgeBlocksText(message.content ?? data.content));
66341
+ if (tail !== undefined)
66342
+ lastLine = tail;
66343
+ } else if (row.type === "tool/result") {
66344
+ if (data.isError !== true) {
66345
+ const message = asRecord5(data.message);
66346
+ const tail = bridgeLastContentLine(bridgeBlocksText(message.content ?? data.content));
66347
+ if (tail !== undefined)
66348
+ lastLine = tail;
66349
+ }
66350
+ } else if (row.type === "request/context") {
66351
+ if (contextModel === undefined && typeof data.model === "string" && data.model !== "") {
66352
+ contextModel = data.model;
66353
+ }
66354
+ } else if (row.type === "subagent/descriptor") {
66355
+ if (descriptorModel === undefined && typeof data.agentModel === "string" && data.agentModel !== "") {
66356
+ descriptorModel = data.agentModel;
66357
+ }
66358
+ }
66359
+ }
66360
+ const model = contextModel ?? descriptorModel;
66361
+ return {
66362
+ rounds,
66363
+ ...lastLine !== undefined ? { lastLine } : {},
66364
+ ...model !== undefined ? { model } : {}
66365
+ };
66366
+ }
66367
+ function bridgeChildJournalKey(view) {
66368
+ return `${view.id}@${view.startedAt ?? ""}`;
66369
+ }
66370
+ function bridgeRestoreSettled(view, snap) {
66371
+ const { startedAt: _startedAt, ...rest } = view;
66372
+ return { ...rest, status: snap.status, elapsedSec: snap.elapsedSec, endedAt: snap.endedAt };
66373
+ }
66374
+ function lastJournalTurnTerminal(rows, startOutsideWindow = false) {
66375
+ if (startOutsideWindow) {
66376
+ let nextStart = Infinity;
66377
+ const startIds = new Set;
66378
+ for (const row of rows) {
66379
+ if (row.type === "turn/start") {
66380
+ nextStart = Math.min(nextStart, row.seq);
66381
+ const id = journalTurnId(row);
66382
+ if (id !== undefined)
66383
+ startIds.add(id);
66384
+ }
66385
+ }
66386
+ let latest;
66387
+ for (const row of rows) {
66388
+ if (row.type !== "turn/end" && row.type !== "turn/error")
66389
+ continue;
66390
+ if (row.seq >= nextStart)
66391
+ continue;
66392
+ const id = journalTurnId(row);
66393
+ if (id !== undefined && startIds.has(id))
66394
+ continue;
66395
+ if (latest === undefined || row.seq > latest.seq)
66396
+ latest = row;
66397
+ }
66398
+ return latest;
66399
+ }
66400
+ let lastStart = -Infinity;
66401
+ let hasStart = false;
66402
+ for (const row of rows) {
66403
+ if (row.type === "turn/start") {
66404
+ lastStart = row.seq;
66405
+ hasStart = true;
66406
+ }
66407
+ }
66408
+ let latest;
66409
+ for (const row of rows) {
66410
+ if ((row.type === "turn/end" || row.type === "turn/error") && (!hasStart || row.seq > lastStart)) {
66411
+ if (latest === undefined || row.seq > latest.seq)
66412
+ latest = row;
66413
+ }
66414
+ }
66415
+ return latest;
66416
+ }
66417
+ function journalTurnId(row) {
66418
+ const payload = asRecord5(row.payload);
66419
+ if (typeof payload.turn === "number" && Number.isFinite(payload.turn))
66420
+ return payload.turn;
66421
+ if (typeof payload.turnId === "string" && payload.turnId !== "")
66422
+ return payload.turnId;
66423
+ return;
66424
+ }
66425
+ function projectBridgeEvent(frame, sessionId) {
66426
+ const payload = asRecord5(frame.payload);
66427
+ const turnId = typeof payload.turnId === "string" ? payload.turnId : "";
66428
+ if (frame.type === "turn.start") {
66429
+ return [{ type: "session.updated", details: { sessionID: sessionId, turnId, turn: "starting" } }];
66430
+ }
66431
+ if (frame.type === "turn.end") {
66432
+ return [{ type: "session.updated", details: { sessionID: sessionId, turnId, turn: "idle" } }];
66433
+ }
66434
+ if (frame.type === "turn.error") {
66435
+ return [{
66436
+ type: "session.error",
66437
+ details: {
66438
+ sessionID: sessionId,
66439
+ turnId,
66440
+ code: typeof payload.code === "string" ? payload.code : "INTERNAL",
66441
+ message: typeof payload.message === "string" ? payload.message : "turn failed"
66442
+ }
66443
+ }];
66444
+ }
66445
+ return [];
66446
+ }
66447
+ function parseUsage(value) {
66448
+ const u = asRecord5(value);
66449
+ const num = (...aliases) => {
66450
+ let present = false;
66451
+ let best = 0;
66452
+ for (const alias of aliases) {
66453
+ const v = u[alias];
66454
+ if (typeof v === "number" && Number.isFinite(v)) {
66455
+ present = true;
66456
+ best = Math.max(best, v);
66457
+ }
66458
+ }
66459
+ return present ? best : undefined;
66460
+ };
66461
+ const out = {};
66462
+ const prompt = num("prompt", "promptTokens", "inputTokens", "prompt_tokens");
66463
+ if (prompt !== undefined)
66464
+ out.prompt = prompt;
66465
+ const completion = num("completion", "completionTokens", "outputTokens", "completion_tokens");
66466
+ if (completion !== undefined)
66467
+ out.completion = completion;
66468
+ const cacheRead = num("cacheRead", "cacheReadTokens", "cache_read_tokens");
66469
+ if (cacheRead !== undefined)
66470
+ out.cacheRead = cacheRead;
66471
+ const cacheWrite = num("cacheWrite", "cacheWriteTokens", "cache_write_tokens");
66472
+ if (cacheWrite !== undefined)
66473
+ out.cacheWrite = cacheWrite;
66474
+ return out;
66475
+ }
66476
+ function journalUsage(payload) {
66477
+ const usage = asRecord5(asRecord5(payload).usage);
66478
+ const parsed = parseUsage(usage);
66479
+ if (Object.keys(parsed).length === 0)
66480
+ return;
66481
+ const billed = (parsed.prompt ?? 0) + (parsed.cacheRead ?? 0) + (parsed.cacheWrite ?? 0);
66482
+ const rawTotal = usage.totalTokens;
66483
+ const total = typeof rawTotal === "number" && Number.isFinite(rawTotal) && rawTotal > 0 ? rawTotal : billed + (parsed.completion ?? 0);
66484
+ return { ...parsed, total };
66485
+ }
66486
+ function asDeadCause(value) {
66487
+ const r = asRecord5(value);
66488
+ const stage = r.stage;
66489
+ const stages = ["spawn", "handshake", "runtime", "closed"];
66490
+ return {
66491
+ stage: typeof stage === "string" && stages.includes(stage) ? stage : "runtime",
66492
+ code: typeof r.code === "number" ? r.code : null,
66493
+ signal: typeof r.signal === "string" ? r.signal : null,
66494
+ message: typeof r.message === "string" ? r.message : "bridge connection lost",
66495
+ ...r.recoverability === "permanent" || r.recoverability === "retriable" ? { recoverability: r.recoverability } : {},
66496
+ ...Array.isArray(r.mismatches) && r.mismatches.every((m) => typeof m === "string") ? { mismatches: r.mismatches } : {}
66497
+ };
66498
+ }
66499
+
66500
+ class BridgeSessionSeam {
66501
+ #transport;
66502
+ #ctx;
66503
+ #unsubEvent;
66504
+ #listeners = [];
66505
+ #onDead;
66506
+ #subagentViews = new Map;
66507
+ #subagentRunSeq = new Map;
66508
+ #subagentLiveStarts = new Set;
66509
+ #subagentListeners = new Set;
66510
+ #subagentSessionId;
66511
+ #subagentJournalLoaded = new Set;
66512
+ #subagentJournalMeta = new Map;
66513
+ #sweepSettledRuns = new Map;
66514
+ #subagentSettleSnapshots = new Map;
66515
+ #connection = "disconnected";
66516
+ #turn = "idle";
66517
+ #bridgeLink = "ready";
66518
+ #sessionAttached = false;
66519
+ #currentSessionId;
66520
+ #lastAppliedSeq;
66521
+ #lastAppliedSessionId;
66522
+ #appliedReplayKeys = new Set;
66523
+ #recoveryState = "idle";
66524
+ #pendingOpen;
66525
+ #inFlightTurnId;
66526
+ #activeCallbacks;
66527
+ #turnDone;
66528
+ #turnGeneration = 0;
66529
+ #inFlightGeneration = 0;
66530
+ #degradedOnce = new Set;
66531
+ #usage = { turns: 0, prompt: 0, completion: 0, cacheRead: 0, cacheWrite: 0 };
66532
+ #decodeWindowStart;
66533
+ #lastTurnDecode;
66534
+ #decodeTotals = { tokens: 0, ms: 0 };
66535
+ #sessionInfoInFlight;
66536
+ #sessionInfoStats;
66537
+ #askFrameSeen = false;
66538
+ #permissionNoticeShown = false;
66539
+ #onPermissionUnavailable;
66540
+ #askProvider;
66541
+ #pendingAsks = new Map;
66542
+ #bufferedPendingSnapshot;
66543
+ #replayDrainPending = false;
66544
+ #deadInFlight;
66545
+ #inFlightPartial = "";
66546
+ #invalidatedAsks = new Map;
66547
+ #disposed = false;
66548
+ constructor(options) {
66549
+ this.#transport = options.transport;
66550
+ this.#ctx = options.ctx;
66551
+ this.#onDead = options.onDead;
66552
+ this.#onPermissionUnavailable = options.onPermissionUnavailable;
66553
+ this.#unsubEvent = this.#transport.onEvent((frame) => this.#onBridgeEvent(frame));
66554
+ }
66555
+ async connect() {
66556
+ try {
66557
+ await this.#transport.request("bridge.ping");
66558
+ this.#connection = "connected";
66559
+ } catch (err) {
66560
+ this.#connection = "disconnected";
66561
+ this.#ctx.logger.warn("[bridge-seam] bridge.ping failed, status connection=disconnected: %s", err);
66562
+ }
66563
+ }
66564
+ status() {
66565
+ if (this.#connection === "disconnected") {
66566
+ this.#degradeOnce("status", "no handshake/status frame; returning disconnected/idle");
66567
+ }
66568
+ return { connection: this.#connection, turn: this.#turn, sessionAttached: this.#sessionAttached, bridge: this.#bridgeLink };
66569
+ }
66570
+ currentSessionId() {
66571
+ return this.#currentSessionId;
66572
+ }
66573
+ resumeSession(id) {
66574
+ this.#pendingOpen = { mode: "resume", id };
66575
+ return "ok";
66576
+ }
66577
+ newSession() {
66578
+ this.#currentSessionId = undefined;
66579
+ this.#pendingOpen = { mode: "new" };
66580
+ this.#settleSuspendedTurn();
66581
+ this.#deadInFlight = undefined;
66582
+ this.#inFlightPartial = "";
66583
+ }
66584
+ stagedSessionId() {
66585
+ return this.#pendingOpen?.mode === "resume" ? this.#pendingOpen.id : undefined;
66586
+ }
66587
+ recoveryState() {
66588
+ return this.#recoveryState;
66589
+ }
66590
+ async recoverSession() {
66591
+ const sessionId = this.#currentSessionId ?? this.stagedSessionId();
66592
+ const emit = (event) => {
66593
+ for (const listener of [...this.#listeners]) {
66594
+ try {
66595
+ listener(event);
66596
+ } catch {}
66597
+ }
66598
+ };
66599
+ const fail = (code, message) => {
66600
+ this.#recoveryState = "failed";
66601
+ this.#sessionAttached = false;
66602
+ this.#connection = "connected";
66603
+ this.#bridgeLink = "ready";
66604
+ this.#bufferedPendingSnapshot = undefined;
66605
+ this.#replayDrainPending = false;
66606
+ this.#settleSuspendedTurn();
66607
+ const result = {
66608
+ state: "failed",
66609
+ sessionId,
66610
+ applied: 0,
66611
+ from: 0,
66612
+ cursor: 0,
66613
+ rows: [],
66614
+ error: { code, message }
66615
+ };
66616
+ emit({ type: "bridge.recovery.failed", details: { ...result, message: `\u6062\u590D\u5931\u8D25: ${message}` } });
66617
+ return result;
66618
+ };
66619
+ if (this.#disposed)
66620
+ return fail("DISPOSED", "bridge seam is disposed");
66621
+ if (sessionId === undefined || sessionId === "") {
66622
+ return fail("NO_SESSION_TO_RESUME", "no session was open before DEAD");
66623
+ }
66624
+ this.#recoveryState = "recovering";
66625
+ this.#connection = "connected";
66626
+ this.#bridgeLink = "ready";
66627
+ this.#sessionAttached = false;
66628
+ this.#replayDrainPending = true;
66629
+ let opened;
66630
+ try {
66631
+ opened = asRecord5(await this.#transport.request("session.open", { mode: "resume", id: sessionId }));
66632
+ } catch (err) {
66633
+ const code = err instanceof BridgeProtocolError ? err.code : "SESSION_OPEN_FAILED";
66634
+ const message = err instanceof Error ? err.message : String(err);
66635
+ if (code === "SESSION_LOCKED") {
66636
+ this.#recoveryState = "locked";
66637
+ this.#sessionAttached = false;
66638
+ this.#bufferedPendingSnapshot = undefined;
66639
+ this.#replayDrainPending = false;
66640
+ this.#settleSuspendedTurn();
66641
+ const errorDetail = err instanceof BridgeProtocolError ? asRecord5(err.detail) : {};
66642
+ const holder = typeof errorDetail.holder === "string" && errorDetail.holder.trim() !== "" ? errorDetail.holder : undefined;
66643
+ const result = {
66644
+ state: "locked",
66645
+ sessionId,
66646
+ applied: 0,
66647
+ from: 0,
66648
+ cursor: 0,
66649
+ rows: [],
66650
+ error: { code, message }
66651
+ };
66652
+ emit({
66653
+ type: "bridge.recovery.locked",
66654
+ details: {
66655
+ ...result,
66656
+ message,
66657
+ ...holder !== undefined ? { holder } : {}
66658
+ }
66659
+ });
66660
+ return result;
66661
+ }
66662
+ this.#ctx.logger.error("[bridge-seam] recovery session.open failed: %s", err);
66663
+ return fail(code, message);
66664
+ }
66665
+ const boundId = typeof opened.sessionId === "string" ? opened.sessionId : sessionId;
66666
+ this.#currentSessionId = boundId;
66667
+ if (this.#pendingOpen?.mode === "resume" && this.#pendingOpen.id === boundId)
66668
+ this.#pendingOpen = undefined;
66669
+ if (this.#lastAppliedSessionId !== boundId) {
66670
+ this.#lastAppliedSessionId = boundId;
66671
+ this.#lastAppliedSeq = undefined;
66672
+ this.#appliedReplayKeys.clear();
66673
+ }
66674
+ this.#sessionAttached = true;
66675
+ const from = this.#lastAppliedSeq === undefined ? 1 : this.#lastAppliedSeq + 1;
66676
+ let drained;
66677
+ try {
66678
+ drained = await this.#drainJournal(boundId, from);
66679
+ } catch (err) {
66680
+ const code = err instanceof BridgeProtocolError ? err.code : "JOURNAL_REPLAY_FAILED";
66681
+ const message = err instanceof Error ? err.message : String(err);
66682
+ this.#ctx.logger.error("[bridge-seam] recovery journal.replay failed: %s", err);
66683
+ return fail(code, message);
66684
+ }
66685
+ if (drained.clamped) {
66686
+ this.#ctx.logger.warn("[bridge-seam] recovery replay from=%d is ahead of journal max=%d; clamped to %d", from, Math.max(0, drained.cursor - 1), drained.cursor);
66687
+ }
66688
+ this.#foldAgentReplayRows(drained.rows, boundId);
66689
+ await this.#sweepSubagents(boundId);
66690
+ const rows = bridgeReplayRowsToSeamTranscript(drained.rows);
66691
+ if (drained.rows.length > 0) {
66692
+ const maxSeq = drained.rows.reduce((m, row) => Math.max(m, row.seq), -Infinity);
66693
+ this.#lastAppliedSeq = Math.max(this.#lastAppliedSeq ?? 0, maxSeq);
66694
+ this.#lastAppliedSessionId = boundId;
66695
+ }
66696
+ const buffered = this.#bufferedPendingSnapshot;
66697
+ this.#bufferedPendingSnapshot = undefined;
66698
+ this.#replayDrainPending = false;
66699
+ if (buffered !== undefined)
66700
+ this.#applyPendingSnapshot(buffered);
66701
+ const dead = this.#deadInFlight;
66702
+ this.#deadInFlight = undefined;
66703
+ if (dead !== undefined) {
66704
+ const firstStart = drained.rows.find((r) => r.type === "turn/start")?.seq;
66705
+ const firstTerminal = drained.rows.find((r) => r.type === "turn/end" || r.type === "turn/error")?.seq;
66706
+ const startOutsideWindow = firstStart !== undefined && firstTerminal !== undefined && firstTerminal < firstStart;
66707
+ const terminal = lastJournalTurnTerminal(drained.rows, startOutsideWindow);
66708
+ if (terminal !== undefined) {
66709
+ emit({
66710
+ type: "bridge.turn.terminal",
66711
+ details: {
66712
+ sessionID: boundId,
66713
+ turnId: dead.turnId,
66714
+ seq: terminal.seq,
66715
+ terminalType: terminal.type,
66716
+ reason: asRecord5(terminal.payload).reason,
66717
+ payload: terminal.payload,
66718
+ source: "journal"
66719
+ }
66720
+ });
66721
+ this.#settleSuspendedTurn();
66722
+ } else {
66723
+ emit({
66724
+ type: "bridge.turn.interrupted",
66725
+ details: {
66726
+ sessionID: boundId,
66727
+ turnId: dead.turnId,
66728
+ partial: dead.partial,
66729
+ reason: "connection lost while the turn was in flight",
66730
+ code: "INTERRUPTED",
66731
+ seq: null,
66732
+ source: "local"
66733
+ }
66734
+ });
66735
+ this.#settleSuspendedTurn();
66736
+ }
66737
+ }
66738
+ await new Promise((resolve) => setTimeout(resolve, 0));
66739
+ for (const event of bridgeReplayRowsToSeamEvents(drained.rows, boundId)) {
66740
+ const key = seamReplayEventKey(event);
66741
+ if (this.#appliedReplayKeys.has(key))
66742
+ continue;
66743
+ this.#appliedReplayKeys.add(key);
66744
+ emit(event);
66745
+ }
66746
+ this.#sessionAttached = true;
66747
+ this.#connection = "connected";
66748
+ this.#bridgeLink = "ready";
66749
+ this.#recoveryState = "attached";
66750
+ const result = {
66751
+ state: "attached",
66752
+ sessionId: boundId,
66753
+ applied: drained.rows.length,
66754
+ from,
66755
+ cursor: drained.cursor,
66756
+ rows
66757
+ };
66758
+ emit({ type: "bridge.recovered", details: { ...result, message: `\u5DF2\u6062\u590D\uFF0C\u8865\u9F50 ${result.applied} \u6761\u4E8B\u4EF6` } });
66759
+ return result;
66760
+ }
66761
+ async#drainJournal(sessionId, startFrom) {
66762
+ let from = startFrom;
66763
+ let floor = startFrom;
66764
+ let cursor = 0;
66765
+ let clamped = false;
66766
+ const seen = new Set;
66767
+ const collected = [];
66768
+ for (;; ) {
66769
+ const value = asRecord5(await this.#transport.request("journal.replay", { sessionId, from }));
66770
+ const rawRows = Array.isArray(value.rows) ? value.rows : [];
66771
+ if (typeof value.cursor === "number" && Number.isFinite(value.cursor))
66772
+ cursor = value.cursor;
66773
+ if (!clamped && cursor > 0 && from > cursor) {
66774
+ clamped = true;
66775
+ from = cursor;
66776
+ floor = cursor;
66777
+ continue;
66778
+ }
66779
+ let added = 0;
66780
+ let pageMax = from - 1;
66781
+ for (const raw of rawRows) {
66782
+ const row = asRecord5(raw);
66783
+ const seq = row.seq;
66784
+ if (typeof seq !== "number" || !Number.isFinite(seq) || seq < floor || seen.has(seq))
66785
+ continue;
66786
+ seen.add(seq);
66787
+ collected.push({ seq, type: typeof row.type === "string" ? row.type : "", payload: row.payload });
66788
+ added += 1;
66789
+ if (seq > pageMax)
66790
+ pageMax = seq;
66791
+ }
66792
+ if (added === 0)
66793
+ break;
66794
+ from = pageMax + 1;
66795
+ if (cursor > 0 && from >= cursor)
66796
+ break;
66797
+ }
66798
+ collected.sort((a, b) => a.seq - b.seq);
66799
+ return { rows: collected, cursor, clamped };
66800
+ }
66801
+ interrupt() {
66802
+ const turnId = this.#inFlightTurnId;
66803
+ if (turnId === undefined || turnId === "") {
66804
+ this.#degrade("interrupt", "no in-flight turnId; turn.abort skipped (no-op)");
66805
+ return;
66806
+ }
66807
+ const fail = (message, code) => {
66808
+ this.#ctx.logger.warn("[bridge-seam] %s", message);
66809
+ const cb = this.#activeCallbacks;
66810
+ if (cb !== undefined) {
66811
+ try {
66812
+ cb.onError(message);
66813
+ } catch {}
66814
+ }
66815
+ const [event] = projectBridgeEvent({ type: "turn.error", payload: { turnId, code, message } }, this.#currentSessionId ?? "");
66816
+ if (event !== undefined) {
66817
+ for (const listener of this.#listeners) {
66818
+ try {
66819
+ listener(event);
66820
+ } catch {}
66821
+ }
66822
+ }
66823
+ if (this.#inFlightTurnId === turnId) {
66824
+ this.#inFlightTurnId = undefined;
66825
+ this.#turn = "idle";
66826
+ this.#turnDone?.();
66827
+ }
66828
+ };
66829
+ const attempt = (remaining) => {
66830
+ this.#transport.request("turn.abort", { turnId }).then((result) => {
66831
+ if (asRecord5(result).noop === true) {
66832
+ fail(`turn.abort was a noop for turn ${turnId}; turn may still be running`, "TURN_ABORT_NOOP");
66833
+ }
66834
+ }).catch((err) => {
66835
+ if (remaining > 0) {
66836
+ attempt(remaining - 1);
66837
+ return;
66838
+ }
66839
+ const code = err instanceof BridgeProtocolError ? err.code : "TURN_ABORT_FAILED";
66840
+ const reason = err instanceof Error ? err.message : String(err);
66841
+ fail(`turn.abort failed for turn ${turnId}: ${reason}`, code);
66842
+ });
66843
+ };
66844
+ attempt(1);
66845
+ }
66846
+ usageSummary() {
66847
+ if (this.#usage.turns === 0) {
66848
+ this.#degradeOnce("usageSummary", "no turn.end usage captured yet; returning []");
66849
+ return [];
66850
+ }
66851
+ const u = this.#usage;
66852
+ return [
66853
+ `turns ${u.turns}`,
66854
+ `prompt ${fmtTokens(u.prompt)} tok`,
66855
+ `completion ${fmtTokens(u.completion)} tok`
66856
+ ];
66857
+ }
66858
+ cacheHitRate(mode) {
66859
+ const stats = this.#liveStats();
66860
+ if (stats === undefined || stats.cacheRead + stats.cacheWrite <= 0)
66861
+ return null;
66862
+ if (mode === "session") {
66863
+ const billed = stats.cachePrompt + stats.cacheRead + stats.cacheWrite;
66864
+ return billed > 0 ? stats.cacheRead / billed * 100 : null;
66865
+ }
66866
+ return stats.lastCacheHitRate;
66867
+ }
66868
+ contextTokens() {
66869
+ return this.#liveStats()?.contextTokens ?? null;
66870
+ }
66871
+ contextWindow() {
66872
+ return this.#liveContextWindow();
66873
+ }
66874
+ #liveStats() {
66875
+ const stats = this.#sessionInfoStats;
66876
+ return stats !== undefined && stats.sessionId === this.currentSessionId() ? stats : undefined;
66877
+ }
66878
+ #liveContextWindow() {
66879
+ const stats = this.#liveStats();
66880
+ if (stats?.contextWindow === undefined)
66881
+ return null;
66882
+ if (stats.contextWindowKey !== undefined && stats.selectionKey !== undefined && stats.contextWindowKey !== stats.selectionKey)
66883
+ return null;
66884
+ return stats.contextWindow;
66885
+ }
66886
+ sessionInfo() {
66887
+ const existing = this.#sessionInfoInFlight;
66888
+ if (existing !== undefined)
66889
+ return existing;
66890
+ const run = this.#computeSessionInfo();
66891
+ this.#sessionInfoInFlight = run;
66892
+ const release = () => {
66893
+ if (this.#sessionInfoInFlight === run)
66894
+ this.#sessionInfoInFlight = undefined;
66895
+ };
66896
+ run.then(release, release);
66897
+ return run;
66898
+ }
66899
+ async#computeSessionInfo() {
66900
+ const sessionId = this.currentSessionId();
66901
+ if (!sessionId)
66902
+ return;
66903
+ let counts;
66904
+ try {
66905
+ let stats = this.#sessionInfoStats;
66906
+ if (stats === undefined || stats.sessionId !== sessionId) {
66907
+ stats = {
66908
+ sessionId,
66909
+ lastSeq: 0,
66910
+ userRows: 0,
66911
+ assistantRows: 0,
66912
+ rawAssistants: 0,
66913
+ cachePrompt: 0,
66914
+ cacheRead: 0,
66915
+ cacheWrite: 0,
66916
+ lastCacheHitRate: null,
66917
+ contextTokens: null,
66918
+ contextWindow: undefined,
66919
+ contextWindowKey: undefined,
66920
+ selectionKey: undefined
66921
+ };
66922
+ this.#sessionInfoStats = stats;
66923
+ }
66924
+ let from = stats.lastSeq + 1;
66925
+ let drained = await this.#drainJournal(sessionId, from);
66926
+ if (drained.clamped && from > 1) {
66927
+ stats = {
66928
+ sessionId,
66929
+ lastSeq: 0,
66930
+ userRows: 0,
66931
+ assistantRows: 0,
66932
+ rawAssistants: 0,
66933
+ cachePrompt: 0,
66934
+ cacheRead: 0,
66935
+ cacheWrite: 0,
66936
+ lastCacheHitRate: null,
66937
+ contextTokens: null,
66938
+ contextWindow: undefined,
66939
+ contextWindowKey: undefined,
66940
+ selectionKey: undefined
66941
+ };
66942
+ this.#sessionInfoStats = stats;
66943
+ from = 1;
66944
+ drained = await this.#drainJournal(sessionId, 1);
66945
+ }
66946
+ this.#foldAgentReplayRows(drained.rows, sessionId);
66947
+ for (const row of drained.rows) {
66948
+ if (row.type === "assistant/message") {
66949
+ stats.rawAssistants++;
66950
+ const usage = journalUsage(row.payload);
66951
+ if (usage !== undefined) {
66952
+ const prompt = usage.prompt ?? 0;
66953
+ const cacheRead = usage.cacheRead ?? 0;
66954
+ const cacheWrite = usage.cacheWrite ?? 0;
66955
+ if (prompt > 0)
66956
+ stats.cachePrompt += prompt;
66957
+ if (cacheRead > 0)
66958
+ stats.cacheRead += cacheRead;
66959
+ if (cacheWrite > 0)
66960
+ stats.cacheWrite += cacheWrite;
66961
+ const billed = prompt + cacheRead + cacheWrite;
66962
+ if (billed > 0)
66963
+ stats.lastCacheHitRate = cacheRead / billed * 100;
66964
+ stats.contextTokens = usage.total;
66965
+ }
66966
+ } else if (row.type === "request/context") {
66967
+ const data = asRecord5(row.payload);
66968
+ const window = data.contextWindow;
66969
+ if (typeof window === "number" && Number.isFinite(window) && window > 0) {
66970
+ const provider = typeof data.provider === "string" ? data.provider : "";
66971
+ const model = typeof data.model === "string" ? data.model : "";
66972
+ stats.contextWindow = window;
66973
+ stats.contextWindowKey = provider && model ? `${provider}/${model}` : undefined;
66974
+ }
66975
+ }
66976
+ }
66977
+ for (const row of bridgeReplayRowsToSeamTranscript(drained.rows)) {
66978
+ if (row.kind === "user")
66979
+ stats.userRows++;
66980
+ else if (row.kind === "assistant")
66981
+ stats.assistantRows++;
66982
+ }
66983
+ for (const row of drained.rows) {
66984
+ if (row.seq > stats.lastSeq)
66985
+ stats.lastSeq = row.seq;
66986
+ }
66987
+ counts = {
66988
+ msgCount: stats.rawAssistants,
66989
+ messageCount: stats.userRows + stats.assistantRows,
66990
+ turnCount: stats.userRows
66991
+ };
66992
+ } catch (err) {
66993
+ this.#ctx.logger.warn("[bridge-seam] sessionInfo journal.replay failed: %s", err);
66994
+ }
66995
+ const selection = await this.currentModelSelection().catch(() => {
66996
+ return;
66997
+ });
66998
+ const stats = this.#liveStats();
66999
+ const selectionKey = selection ? `${selection.providerID}/${selection.modelID}` : undefined;
67000
+ if (stats !== undefined)
67001
+ stats.selectionKey = selectionKey;
67002
+ const u = this.#usage;
67003
+ const last = this.#lastTurnDecode;
67004
+ return {
67005
+ sessionId,
67006
+ model: selectionKey ?? null,
67007
+ ...counts !== undefined ? counts : {},
67008
+ tokensIn: u.prompt,
67009
+ tokensOut: u.completion,
67010
+ cacheRead: u.cacheRead,
67011
+ cacheWrite: u.cacheWrite,
67012
+ lastTurnTps: last && last.ms > 0 ? tokensPerSecond(last.tokens, last.ms) : null,
67013
+ sessionAvgTps: this.#decodeTotals.ms > 0 ? tokensPerSecond(this.#decodeTotals.tokens, this.#decodeTotals.ms) : null,
67014
+ contextTokens: stats?.contextTokens ?? null,
67015
+ contextWindow: this.#liveContextWindow()
67016
+ };
67017
+ }
67018
+ onSessionEvent(listener) {
67019
+ this.#degradeOnce("onSessionEvent", "only turn.* lifecycle/error events project; permission.asked / bridge.shutdown absent");
67020
+ this.#listeners.push(listener);
67021
+ return () => {
67022
+ const i = this.#listeners.indexOf(listener);
67023
+ if (i >= 0)
67024
+ this.#listeners.splice(i, 1);
67025
+ };
67026
+ }
67027
+ subagentViews() {
67028
+ return [...this.#subagentViews.values()].map((view) => ({ ...view }));
67029
+ }
67030
+ #freezeSettles(before) {
67031
+ for (const [childId, startedAt] of before) {
67032
+ const view = this.#subagentViews.get(childId);
67033
+ if (view === undefined || view.status === "running")
67034
+ continue;
67035
+ if (view.elapsedSec === undefined || view.endedAt === undefined)
67036
+ continue;
67037
+ const runKey = `${childId}@${startedAt ?? ""}`;
67038
+ const frozen = this.#subagentSettleSnapshots.get(runKey);
67039
+ if (frozen !== undefined) {
67040
+ this.#subagentViews.set(childId, bridgeRestoreSettled(view, frozen));
67041
+ } else {
67042
+ this.#subagentSettleSnapshots.set(runKey, {
67043
+ status: view.status,
67044
+ elapsedSec: view.elapsedSec,
67045
+ endedAt: view.endedAt
67046
+ });
67047
+ }
67048
+ }
67049
+ }
67050
+ #foldWithFrozenSettle(type, data, now, live) {
67051
+ const before = new Map;
67052
+ for (const [id, v] of this.#subagentViews) {
67053
+ if (v.status === "running")
67054
+ before.set(id, v.startedAt);
67055
+ }
67056
+ const changed = bridgeFoldAgentRecord(this.#subagentViews, this.#subagentRunSeq, this.#subagentLiveStarts, type, data, now, live);
67057
+ if (changed)
67058
+ this.#freezeSettles(before);
67059
+ return changed;
67060
+ }
67061
+ async#sweepSubagents(parentId) {
67062
+ let value;
67063
+ try {
67064
+ value = await this.#transport.request("session.list", { _request: {} });
67065
+ } catch {
67066
+ return;
67067
+ }
67068
+ const items = asRecord5(value).items;
67069
+ if (!Array.isArray(items))
67070
+ return;
67071
+ const locallyRunning = new Set;
67072
+ for (const view of this.#subagentViews.values()) {
67073
+ if (view.status === "running")
67074
+ locallyRunning.add(view.id);
67075
+ }
67076
+ const toSettle = bridgeSweepSettledChildIds(items, parentId, locallyRunning);
67077
+ if (toSettle.length === 0)
67078
+ return;
67079
+ const now = Date.now();
67080
+ let changed = false;
67081
+ for (const childId of toSettle) {
67082
+ const existing = this.#subagentViews.get(childId);
67083
+ if (existing !== undefined)
67084
+ this.#sweepSettledRuns.set(childId, bridgeChildJournalKey(existing));
67085
+ if (this.#foldWithFrozenSettle("user/message", {
67086
+ source: { kind: BRIDGE_SUBAGENT_SETTLED, stopReason: "completed", senderSessionId: childId }
67087
+ }, now, false))
67088
+ changed = true;
67089
+ }
67090
+ if (changed) {
67091
+ this.#syncSubagentMeta(false);
67092
+ this.#emitSubagentViews();
67093
+ }
67094
+ }
67095
+ async#ensureChildJournal(childId, startedAt) {
67096
+ const key = `${childId}@${startedAt ?? ""}`;
67097
+ if (this.#subagentJournalLoaded.has(key))
67098
+ return;
67099
+ this.#subagentJournalLoaded.add(key);
67100
+ const sessionAtStart = this.#subagentSessionId;
67101
+ try {
67102
+ const value = asRecord5(await this.#transport.request("journal.replay", { sessionId: childId }));
67103
+ const rows = value.rows;
67104
+ if (!Array.isArray(rows))
67105
+ return;
67106
+ const cleanRows = rows.filter((row) => row !== null && typeof row === "object" && !Array.isArray(row));
67107
+ const meta = bridgeChildJournalMeta(cleanRows);
67108
+ if (this.#subagentSessionId !== sessionAtStart || this.#disposed)
67109
+ return;
67110
+ this.#subagentJournalMeta.set(key, meta);
67111
+ const existing = this.#subagentViews.get(childId);
67112
+ if (existing === undefined || bridgeChildJournalKey(existing) !== key)
67113
+ return;
67114
+ this.#subagentViews.set(childId, {
67115
+ ...existing,
67116
+ rounds: meta.rounds,
67117
+ ...meta.lastLine !== undefined ? { lastLine: meta.lastLine } : {},
67118
+ ...meta.model !== undefined ? { model: meta.model } : {}
67119
+ });
67120
+ this.#emitSubagentViews();
67121
+ } catch {}
67122
+ }
67123
+ #syncSubagentMeta(emit = true) {
67124
+ let changed = false;
67125
+ if (this.#sweepSettledRuns.size > 0) {
67126
+ for (const view of [...this.#subagentViews.values()]) {
67127
+ if (view.status !== "running")
67128
+ continue;
67129
+ const recordedKey = this.#sweepSettledRuns.get(view.id);
67130
+ if (recordedKey === undefined)
67131
+ continue;
67132
+ const key = bridgeChildJournalKey(view);
67133
+ if (key !== recordedKey) {
67134
+ this.#degradeOnce("sweep-sticky-run-key-mismatch", `sweep settle run key ${recordedKey} != replay key ${key} for ${view.id}`);
67135
+ continue;
67136
+ }
67137
+ const frozen = this.#subagentSettleSnapshots.get(recordedKey);
67138
+ if (frozen !== undefined) {
67139
+ this.#subagentViews.set(view.id, bridgeRestoreSettled(view, frozen));
67140
+ changed = true;
67141
+ } else {
67142
+ if (this.#foldWithFrozenSettle("user/message", {
67143
+ source: { kind: BRIDGE_SUBAGENT_SETTLED, stopReason: "completed", senderSessionId: view.id }
67144
+ }, Date.now(), false))
67145
+ changed = true;
67146
+ }
67147
+ }
67148
+ }
67149
+ for (const view of [...this.#subagentViews.values()]) {
67150
+ const key = bridgeChildJournalKey(view);
67151
+ const exactMeta = this.#subagentJournalMeta.get(key);
67152
+ const meta = exactMeta ?? (key === `${view.id}@` ? this.#priorRunMeta(view.id) : undefined);
67153
+ if (meta !== undefined) {
67154
+ const restored = {
67155
+ ...view,
67156
+ rounds: meta.rounds,
67157
+ ...meta.lastLine !== undefined ? { lastLine: meta.lastLine } : {},
67158
+ ...meta.model !== undefined ? { model: meta.model } : {}
67159
+ };
67160
+ if (restored.rounds !== view.rounds || restored.lastLine !== view.lastLine || restored.model !== view.model) {
67161
+ this.#subagentViews.set(view.id, restored);
67162
+ changed = true;
67163
+ }
67164
+ }
67165
+ if (exactMeta === undefined && !this.#subagentJournalLoaded.has(key)) {
67166
+ this.#ensureChildJournal(view.id, view.startedAt);
67167
+ }
67168
+ }
67169
+ if (changed && emit)
67170
+ this.#emitSubagentViews();
67171
+ }
67172
+ #priorRunMeta(childId) {
67173
+ const prefix = `${childId}@`;
67174
+ let best;
67175
+ let bestStart = -Infinity;
67176
+ for (const [key, meta] of this.#subagentJournalMeta) {
67177
+ if (!key.startsWith(prefix))
67178
+ continue;
67179
+ const suffix = key.slice(prefix.length);
67180
+ if (suffix === "")
67181
+ continue;
67182
+ const start = Number(suffix);
67183
+ if (Number.isFinite(start) && start > bestStart) {
67184
+ bestStart = start;
67185
+ best = meta;
67186
+ }
67187
+ }
67188
+ return best;
67189
+ }
67190
+ onSubagentViews(listener) {
67191
+ this.#subagentListeners.add(listener);
67192
+ listener(this.subagentViews());
67193
+ return () => {
67194
+ this.#subagentListeners.delete(listener);
67195
+ };
67196
+ }
67197
+ #emitSubagentViews() {
67198
+ if (this.#subagentListeners.size === 0)
67199
+ return;
67200
+ const snapshot = this.subagentViews();
67201
+ for (const listener of [...this.#subagentListeners]) {
67202
+ try {
67203
+ listener(snapshot);
67204
+ } catch {}
67205
+ }
67206
+ }
67207
+ #foldAgentFrame(frame) {
67208
+ const payload = asRecord5(frame.payload);
67209
+ const frameSession = typeof payload.sessionId === "string" ? payload.sessionId : "";
67210
+ if (this.#subagentSessionId !== undefined && frameSession !== "" && frameSession !== this.#subagentSessionId)
67211
+ return;
67212
+ const now = Date.now();
67213
+ let changed = false;
67214
+ if (frame.type === "agent.spawn") {
67215
+ changed = this.#foldWithFrozenSettle(BRIDGE_AGENT_START, payload, now, true);
67216
+ } else if (frame.type === "agent.settle") {
67217
+ changed = this.#foldWithFrozenSettle(BRIDGE_AGENT_END, payload, now, true);
67218
+ }
67219
+ if (changed) {
67220
+ this.#syncSubagentMeta(false);
67221
+ this.#emitSubagentViews();
67222
+ }
67223
+ }
67224
+ #foldAgentReplayRows(rows, sessionId) {
67225
+ let rosterReset = false;
67226
+ if (sessionId !== this.#subagentSessionId) {
67227
+ this.#subagentViews.clear();
67228
+ this.#subagentRunSeq.clear();
67229
+ this.#subagentLiveStarts.clear();
67230
+ this.#subagentJournalLoaded.clear();
67231
+ this.#subagentJournalMeta.clear();
67232
+ this.#sweepSettledRuns.clear();
67233
+ this.#subagentSettleSnapshots.clear();
67234
+ this.#subagentSessionId = sessionId;
67235
+ rosterReset = true;
67236
+ }
67237
+ let changed = false;
67238
+ const now = Date.now();
67239
+ for (const row of rows) {
67240
+ if (this.#foldWithFrozenSettle(row.type, asRecord5(row.payload), now, false))
67241
+ changed = true;
67242
+ }
67243
+ if (rosterReset || changed) {
67244
+ this.#syncSubagentMeta(false);
67245
+ this.#emitSubagentViews();
67246
+ }
67247
+ }
67248
+ configLoad() {
67249
+ this.#degradeOnce("configLoad", "no config frame on the in-process bridge; returning {} (no stored override)");
67250
+ return {};
67251
+ }
67252
+ configRaw() {
67253
+ this.#degradeOnce("configRaw", "no config frame on the in-process bridge; returning {} (no profile layer)");
67254
+ return {};
67255
+ }
67256
+ workspaceConfig() {
67257
+ this.#degradeOnce("workspaceConfig", "no config frame on the in-process bridge; returning {} (no workspace overlay)");
67258
+ return {};
67259
+ }
67260
+ async permissionCatalog() {
67261
+ const answererReady = this.#askProvider !== undefined || this.#inFlightGeneration !== 0 && this.#activeCallbacks !== undefined || this.#askFrameSeen;
67262
+ const providerConfirmed = this.#connection === "connected" && answererReady && !this.#degradedOnce.has("ask.no-provider");
67263
+ if (providerConfirmed)
67264
+ return { options: [], defaultOptions: [], defaultPreset: "" };
67265
+ if (!this.#permissionNoticeShown) {
67266
+ this.#permissionNoticeShown = true;
67267
+ const reason = this.#degradedOnce.has("ask.no-provider") ? "ask-no-provider" : this.#connection === "disconnected" ? "bridge-offline" : "no-provider";
67268
+ this.#onPermissionUnavailable?.(reason);
67269
+ }
67270
+ return;
67271
+ }
67272
+ async listSessions(limit) {
67273
+ const value = await this.#transport.request("session.list");
67274
+ return projectBridgeSessionList(asRecord5(value).items, limit);
67275
+ }
67276
+ async storedTranscript(id, skip = 0) {
67277
+ const value = await this.#transport.request("journal.replay", { sessionId: id });
67278
+ const rows = Array.isArray(asRecord5(value).rows) ? asRecord5(value).rows : [];
67279
+ this.#foldAgentReplayRows(rows, id);
67280
+ this.#sweepSubagents(id);
67281
+ return bridgeReplayRowsToSeamTranscript(rows, skip);
67282
+ }
67283
+ async currentModelSelection() {
67284
+ const selection = await this.#transport.request("model.currentSelection");
67285
+ if (selection === undefined || selection === null)
67286
+ return;
67287
+ const s = asRecord5(selection);
67288
+ const providerID = typeof s.provider === "string" ? s.provider : "";
67289
+ const modelID = typeof s.model === "string" ? s.model : "";
67290
+ if (!providerID || !modelID)
67291
+ return;
67292
+ return { providerID, modelID };
67293
+ }
67294
+ #settleSuspendedTurn() {
67295
+ const done = this.#turnDone;
67296
+ const endedTurnId = this.#inFlightTurnId;
67297
+ this.#turnDone = undefined;
67298
+ this.#activeCallbacks = undefined;
67299
+ this.#inFlightTurnId = undefined;
67300
+ this.#inFlightGeneration = 0;
67301
+ this.#turn = "idle";
67302
+ if (endedTurnId !== undefined)
67303
+ this.#cancelAsksForTurn(endedTurnId);
67304
+ done?.();
67305
+ }
67306
+ async turn(userText, cb) {
67307
+ if (this.#inFlightGeneration !== 0) {
67308
+ throw new BridgeProtocolError("TURN_REENTRANT", "turn() called while another turn is in flight; await the first turn()", { activeTurnId: this.#inFlightTurnId });
67309
+ }
67310
+ const gen = ++this.#turnGeneration;
67311
+ this.#inFlightGeneration = gen;
67312
+ this.#deadInFlight = undefined;
67313
+ this.#inFlightPartial = "";
67314
+ let sendFailed;
67315
+ try {
67316
+ if (this.#pendingOpen === undefined && !this.#sessionAttached) {
67317
+ this.#pendingOpen = { mode: "new" };
67318
+ }
67319
+ if (this.#pendingOpen !== undefined) {
67320
+ const pending = this.#pendingOpen;
67321
+ this.#pendingOpen = undefined;
67322
+ const params = pending.mode === "resume" ? { mode: "resume", id: pending.id, ...this.#sessionAttached ? { replace: true } : {} } : { mode: "new", ...this.#sessionAttached ? { replace: true } : {} };
67323
+ try {
67324
+ const opened = asRecord5(await this.#transport.request("session.open", params));
67325
+ if (typeof opened.sessionId === "string")
67326
+ this.#currentSessionId = opened.sessionId;
67327
+ if (this.#lastAppliedSessionId !== this.#currentSessionId) {
67328
+ this.#lastAppliedSessionId = this.#currentSessionId;
67329
+ this.#lastAppliedSeq = undefined;
67330
+ this.#appliedReplayKeys.clear();
67331
+ }
67332
+ this.#sessionAttached = true;
67333
+ } catch (err) {
67334
+ throw err;
67335
+ }
67336
+ }
67337
+ this.#activeCallbacks = cb;
67338
+ const done = new Promise((resolve) => {
67339
+ this.#turnDone = resolve;
67340
+ });
67341
+ const sent = asRecord5(await this.#transport.request("session.send", { text: userText }));
67342
+ if (typeof sent.turnId === "string") {
67343
+ this.#inFlightTurnId = sent.turnId;
67344
+ this.#emitEvent({
67345
+ type: "bridge.input.acked",
67346
+ details: { sessionID: this.#currentSessionId ?? "", turnId: sent.turnId, text: userText }
67347
+ });
67348
+ }
67349
+ await done;
67350
+ } catch (err) {
67351
+ sendFailed = err;
67352
+ } finally {
67353
+ if (this.#inFlightGeneration === gen) {
67354
+ const endedTurnId = this.#inFlightTurnId;
67355
+ this.#activeCallbacks = undefined;
67356
+ this.#turnDone = undefined;
67357
+ this.#inFlightTurnId = undefined;
67358
+ this.#inFlightGeneration = 0;
67359
+ this.#turn = "idle";
67360
+ if (endedTurnId !== undefined)
67361
+ this.#cancelAsksForTurn(endedTurnId);
67362
+ }
67363
+ }
67364
+ if (sendFailed !== undefined)
67365
+ throw sendFailed;
67366
+ }
67367
+ async dispose() {
67368
+ if (this.#disposed)
67369
+ return;
67370
+ this.#disposed = true;
67371
+ this.#unsubEvent();
67372
+ this.#listeners.length = 0;
67373
+ this.#subagentListeners.clear();
67374
+ this.#subagentViews.clear();
67375
+ this.#subagentRunSeq.clear();
67376
+ this.#subagentLiveStarts.clear();
67377
+ this.#subagentJournalLoaded.clear();
67378
+ this.#subagentJournalMeta.clear();
67379
+ this.#sweepSettledRuns.clear();
67380
+ this.#subagentSettleSnapshots.clear();
67381
+ this.#activeCallbacks = undefined;
67382
+ this.#cancelAllAsks();
67383
+ this.#bufferedPendingSnapshot = undefined;
67384
+ this.#replayDrainPending = false;
67385
+ this.#invalidatedAsks.clear();
67386
+ this.#turnDone?.();
67387
+ this.#turnDone = undefined;
67388
+ this.#inFlightTurnId = undefined;
67389
+ this.#inFlightGeneration = 0;
67390
+ this.#inFlightPartial = "";
67391
+ this.#deadInFlight = undefined;
67392
+ this.#turn = "idle";
67393
+ try {
67394
+ if (this.#sessionAttached)
67395
+ await this.#transport.request("session.close");
67396
+ } catch (err) {
67397
+ this.#ctx.logger.warn("[bridge-seam] session.close failed during dispose: %s", err);
67398
+ }
67399
+ this.#sessionAttached = false;
67400
+ this.#currentSessionId = undefined;
67401
+ }
67402
+ async searchSessions(_query) {
67403
+ return unsupported("searchSessions");
67404
+ }
67405
+ async renameSession(_title) {
67406
+ return unsupported("renameSession");
67407
+ }
67408
+ steer(_text) {
67409
+ this.#degrade("steer", "no session.steer frame; steer is a no-op");
67410
+ }
67411
+ registerAskProvider(onAsk) {
67412
+ this.#askProvider = onAsk;
67413
+ }
67414
+ pendingAsks() {
67415
+ return [...this.#pendingAsks.values()].map((entry) => ({ ...entry.request }));
67416
+ }
67417
+ invalidatedAsks() {
67418
+ return new Map(this.#invalidatedAsks);
67419
+ }
67420
+ async listProviders() {
67421
+ return unsupported("listProviders");
67422
+ }
67423
+ async modelCatalog(_force) {
67424
+ return unsupported("modelCatalog");
67425
+ }
67426
+ selectModel(_providerID, _modelID) {
67427
+ return Promise.reject(new BridgeProtocolError("UNSUPPORTED", "selectModel is not backed by the in-process bridge", { capability: "selectModel" }));
67428
+ }
67429
+ #approvalParams(request, verdict) {
67430
+ const base = { eventId: request.eventId, kind: "approval" };
67431
+ switch (verdict) {
67432
+ case "allowed-once":
67433
+ return { ...base, verdict: "allowed-once" };
67434
+ case "rejected":
67435
+ return { ...base, verdict: "rejected" };
67436
+ case "always":
67437
+ case "session":
67438
+ if (request.escalation !== true) {
67439
+ this.#degradeOnce("ask.invalid-escalation", `behavior:${verdict} needs a granted escalation; refusing to send ask.response (ASK_INVALID_RESPONSE)`);
67440
+ return;
67441
+ }
67442
+ return { ...base, verdict: "allowed-once", behavior: verdict, escalation: true };
67443
+ default:
67444
+ return { ...base, verdict: "rejected" };
67445
+ }
67446
+ }
67447
+ #applyPendingSnapshot(asks) {
67448
+ this.#cancelAllAsks();
67449
+ for (const request of asks) {
67450
+ this.#invalidatedAsks.delete(request.eventId);
67451
+ this.#enqueueAsk(request);
67452
+ }
67453
+ }
67454
+ #isDeadResponseError(err) {
67455
+ const code = err instanceof BridgeProtocolError ? err.code : err !== null && typeof err === "object" && typeof err.code === "string" ? err.code : undefined;
67456
+ if (code === "ASK_NOT_FOUND" || code === "ASK_UNKNOWN_REQUEST" || code === "ASK_TURN_ENDED" || code === "BRIDGE_DEAD" || code === "BRIDGE_CLOSED") {
67457
+ return err instanceof Error && err.message !== "" ? `${code}: ${err.message}` : code;
67458
+ }
67459
+ return;
67460
+ }
67461
+ #enqueueAsk(request) {
67462
+ if (this.#disposed || this.#pendingAsks.has(request.eventId))
67463
+ return;
67464
+ this.#invalidatedAsks.delete(request.eventId);
67465
+ let finish;
67466
+ const done = new Promise((resolve) => {
67467
+ finish = resolve;
67468
+ });
67469
+ const entry = {
67470
+ request,
67471
+ turnId: askTurnId(request.eventId),
67472
+ cancelled: false,
67473
+ done,
67474
+ finish
67475
+ };
67476
+ this.#pendingAsks.set(request.eventId, entry);
67477
+ this.#answerAsk(entry);
67478
+ }
67479
+ async#answerAsk(entry) {
67480
+ const request = entry.request;
67481
+ let params;
67482
+ try {
67483
+ if (request.kind === "approval") {
67484
+ const cb = this.#inFlightGeneration !== 0 ? this.#activeCallbacks : undefined;
67485
+ if (cb !== undefined) {
67486
+ const verdict = await cb.onApprove(request.toolName ?? "tool", approvalArgs(request));
67487
+ params = this.#approvalParams(request, verdict);
67488
+ } else if (this.#askProvider !== undefined) {
67489
+ const picks = await this.#askProvider([approvalQuestion(request)]);
67490
+ params = this.#approvalParams(request, approvalVerdictFromPicks(request, picks));
67491
+ } else {
67492
+ this.#degradeOnce("ask.no-provider", "no onApprove/ask provider; answering approval unavailable (ASK_CHANNEL_UNAVAILABLE)");
67493
+ this.permissionCatalog();
67494
+ params = unavailableResponse(request);
67495
+ }
67496
+ } else if (this.#askProvider !== undefined) {
67497
+ const picks = await this.#askProvider(request.questions ?? []);
67498
+ params = { eventId: request.eventId, kind: "questions", answers: answersFor(request, picks) };
67499
+ } else {
67500
+ this.#degradeOnce("ask.no-provider", "no ask provider; answering questions unavailable (ASK_CHANNEL_UNAVAILABLE)");
67501
+ this.permissionCatalog();
67502
+ params = unavailableResponse(request);
67503
+ }
67504
+ } catch (err) {
67505
+ this.#degradeOnce("ask.provider-error", "ask provider threw; answering unavailable (ASK_CHANNEL_UNAVAILABLE)");
67506
+ this.#ctx.logger.warn("[bridge-seam] ask provider failed: %s", err);
67507
+ params = unavailableResponse(request);
67508
+ }
67509
+ if (entry.cancelled || this.#pendingAsks.get(request.eventId) !== entry) {
67510
+ entry.finish();
67511
+ return;
67512
+ }
67513
+ if (params !== undefined) {
67514
+ try {
67515
+ await this.#transport.request("ask.response", params);
67516
+ } catch (err) {
67517
+ this.#ctx.logger.warn("[bridge-seam] ask.response failed for %s: %s", request.eventId, err);
67518
+ const reason = this.#isDeadResponseError(err);
67519
+ if (reason !== undefined) {
67520
+ this.#invalidatedAsks.set(request.eventId, reason);
67521
+ this.#emitEvent({
67522
+ type: "bridge.ask.invalidated",
67523
+ details: { eventId: request.eventId, sessionId: request.sessionId, reason }
67524
+ });
67525
+ }
67526
+ }
67527
+ }
67528
+ entry.finish();
67529
+ if (!this.#invalidatedAsks.has(request.eventId) && this.#pendingAsks.get(request.eventId) === entry) {
67530
+ this.#pendingAsks.delete(request.eventId);
67531
+ }
67532
+ }
67533
+ #settlePendingAsk(eventId) {
67534
+ const entry = this.#pendingAsks.get(eventId);
67535
+ if (entry === undefined)
67536
+ return;
67537
+ entry.cancelled = true;
67538
+ this.#pendingAsks.delete(eventId);
67539
+ entry.finish();
67540
+ }
67541
+ #cancelAsksForTurn(turnId) {
67542
+ if (turnId === "")
67543
+ return;
67544
+ for (const [eventId, entry] of [...this.#pendingAsks]) {
67545
+ if (entry.turnId === turnId)
67546
+ this.#settlePendingAsk(eventId);
67547
+ }
67548
+ }
67549
+ #cancelAllAsks() {
67550
+ for (const eventId of [...this.#pendingAsks.keys()])
67551
+ this.#settlePendingAsk(eventId);
67552
+ }
67553
+ #onAskEvent(frame) {
67554
+ const payload = asRecord5(frame.payload);
67555
+ if (frame.type === "ask.request" || frame.type === "ask.pending")
67556
+ this.#askFrameSeen = true;
67557
+ switch (frame.type) {
67558
+ case "ask.request": {
67559
+ const request = parseAskRequest(frame.payload);
67560
+ if (request !== undefined)
67561
+ this.#enqueueAsk(request);
67562
+ return true;
67563
+ }
67564
+ case "ask.cancel": {
67565
+ const eventId = optionalStringField(payload, "eventId");
67566
+ if (eventId !== undefined)
67567
+ this.#settlePendingAsk(eventId);
67568
+ return true;
67569
+ }
67570
+ case "ask.settled": {
67571
+ const eventId = optionalStringField(payload, "eventId");
67572
+ if (eventId !== undefined)
67573
+ this.#settlePendingAsk(eventId);
67574
+ return true;
67575
+ }
67576
+ case "ask.pending": {
67577
+ const asks = [];
67578
+ const rawAsks = Array.isArray(payload.asks) ? payload.asks : [];
67579
+ for (const raw of rawAsks) {
67580
+ const request = parseAskRequest(raw);
67581
+ if (request !== undefined)
67582
+ asks.push(request);
67583
+ }
67584
+ if (this.#replayDrainPending) {
67585
+ this.#bufferedPendingSnapshot = asks;
67586
+ return true;
67587
+ }
67588
+ this.#applyPendingSnapshot(asks);
67589
+ return true;
67590
+ }
67591
+ default:
67592
+ return false;
67593
+ }
67594
+ }
67595
+ #emitEvent(event) {
67596
+ for (const listener of [...this.#listeners]) {
67597
+ try {
67598
+ listener(event);
67599
+ } catch {}
67600
+ }
67601
+ }
67602
+ #degrade(member, reason) {
67603
+ this.#ctx.logger.warn("[bridge-seam] %s degraded: %s", member, reason);
67604
+ }
67605
+ #degradeOnce(member, reason) {
67606
+ if (this.#degradedOnce.has(member))
67607
+ return;
67608
+ this.#degradedOnce.add(member);
67609
+ this.#degrade(member, reason);
67610
+ }
67611
+ #onBridgeEvent(frame) {
67612
+ if (this.#onAskEvent(frame))
67613
+ return;
67614
+ if (frame.type === "agent.spawn" || frame.type === "agent.settle") {
67615
+ this.#foldAgentFrame(frame);
67616
+ return;
67617
+ }
67618
+ if (frame.type === "bridge.dead") {
67619
+ const cause = asDeadCause(frame.payload);
67620
+ if (this.#inFlightGeneration !== 0 && this.#inFlightTurnId !== undefined && this.#inFlightTurnId !== "") {
67621
+ this.#deadInFlight = { turnId: this.#inFlightTurnId, partial: this.#inFlightPartial };
67622
+ }
67623
+ this.#bridgeLink = "dead";
67624
+ this.#connection = "disconnected";
67625
+ this.#turn = "idle";
67626
+ this.#onDead?.(cause);
67627
+ for (const listener of [...this.#listeners]) {
67628
+ try {
67629
+ listener({ type: "bridge.dead", details: cause });
67630
+ } catch {}
67631
+ }
67632
+ return;
67633
+ }
67634
+ const payload = asRecord5(frame.payload);
67635
+ if (frame.type === "turn.start") {
67636
+ this.#turn = "starting";
67637
+ this.#decodeWindowStart = undefined;
67638
+ }
67639
+ if (frame.type === "turn.token" || frame.type === "turn.tool")
67640
+ this.#turn = "running";
67641
+ if (frame.type === "turn.end" || frame.type === "turn.error") {
67642
+ this.#turn = "idle";
67643
+ const endedTurnId = typeof payload.turnId === "string" ? payload.turnId : this.#inFlightTurnId;
67644
+ this.#inFlightTurnId = undefined;
67645
+ if (endedTurnId !== undefined)
67646
+ this.#cancelAsksForTurn(endedTurnId);
67647
+ this.#turnDone?.();
67648
+ if (this.#currentSessionId !== undefined && this.#currentSessionId !== "") {
67649
+ this.#sweepSubagents(this.#currentSessionId);
67650
+ }
67651
+ }
67652
+ if (frame.type === "turn.end") {
67653
+ const usage = parseUsage(payload.usage);
67654
+ if (Object.keys(usage).length > 0) {
67655
+ this.#usage.turns += 1;
67656
+ for (const key of ["prompt", "completion", "cacheRead", "cacheWrite"]) {
67657
+ this.#usage[key] += usage[key] ?? 0;
67658
+ }
67659
+ }
67660
+ const start = this.#decodeWindowStart;
67661
+ const tokens = usage.completion ?? 0;
67662
+ if (start !== undefined && tokens > 0) {
67663
+ const ms = Date.now() - start;
67664
+ if (ms > 0) {
67665
+ this.#lastTurnDecode = { tokens, ms };
67666
+ this.#decodeTotals.tokens += tokens;
67667
+ this.#decodeTotals.ms += ms;
67668
+ }
67669
+ }
67670
+ this.#decodeWindowStart = undefined;
67671
+ }
67672
+ if (frame.type === "turn.token" && payload.kind !== "reasoning" && typeof payload.text === "string" && payload.text) {
67673
+ if (this.#decodeWindowStart === undefined)
67674
+ this.#decodeWindowStart = Date.now();
67675
+ this.#inFlightPartial = (this.#inFlightPartial + payload.text).slice(-4096);
67676
+ }
67677
+ const cb = this.#activeCallbacks;
67678
+ if (cb !== undefined) {
67679
+ if (frame.type === "turn.token") {
67680
+ const text = typeof payload.text === "string" ? payload.text : "";
67681
+ if (payload.kind === "reasoning") {
67682
+ if (text)
67683
+ cb.onThinkingDelta(text);
67684
+ } else if (text) {
67685
+ cb.onContentDelta(text);
67686
+ }
67687
+ } else if (frame.type === "turn.tool") {
67688
+ const name = typeof payload.name === "string" ? payload.name : "tool";
67689
+ const callId = typeof payload.callId === "string" ? payload.callId : undefined;
67690
+ if (payload.input !== undefined) {
67691
+ cb.onToolStart?.({ ...callId !== undefined ? { callId } : {}, name, args: JSON.stringify(payload.input) });
67692
+ } else if (payload.output !== undefined) {
67693
+ cb.onToolRun?.({
67694
+ ...callId !== undefined ? { callId } : {},
67695
+ name,
67696
+ argsPretty: "",
67697
+ output: typeof payload.output === "string" ? payload.output : "",
67698
+ ok: payload.isError !== true
67699
+ });
67700
+ }
67701
+ } else if (frame.type === "turn.error") {
67702
+ cb.onError(typeof payload.message === "string" ? payload.message : "turn failed");
67703
+ }
67704
+ }
67705
+ const events = projectBridgeEvent(frame, this.#currentSessionId ?? "");
67706
+ for (const event of events) {
67707
+ for (const listener of this.#listeners) {
67708
+ try {
67709
+ listener(event);
67710
+ } catch {}
67711
+ }
67712
+ }
67713
+ }
67714
+ }
67715
+ 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:", fmtTokens = (n) => n >= 1000 ? `${(n / 1000).toFixed(1)}k` : `${n}`;
67716
+ var init_bridge_session_seam = __esm(() => {
67717
+ init_remote_session_ops();
67718
+ init_session_seam_adapter();
67719
+ init_loop();
67720
+ BridgeProtocolError = class BridgeProtocolError extends Error {
67721
+ code;
67722
+ detail;
67723
+ constructor(code, message, detail) {
67724
+ super(message);
67725
+ this.name = "BridgeProtocolError";
67726
+ this.code = code;
67727
+ if (detail !== undefined)
67728
+ this.detail = detail;
67729
+ }
67730
+ };
67731
+ });
67732
+
67733
+ // scripts/lib/bridge-failfast-text.mjs
67734
+ function formatBridgeFailFastMessage(diagnosis, repairCommand = BRIDGE_REPAIR_COMMAND) {
67735
+ return [diagnosis, `Fix: ${repairCommand}`, BRIDGE_APPEND_PRESET_NOTICE].join(`
67736
+ `);
67737
+ }
67738
+ 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;
67739
+ var init_bridge_failfast_text = __esm(() => {
67740
+ BRIDGE_REPAIR_HINT = `Run \`${BRIDGE_REPAIR_COMMAND}\` to rebuild the bridge symlink / manifest (it fixes links, not corrupted artifact contents).
67741
+ ${BRIDGE_LEGACY_REMOTE_HINT}`;
67742
+ });
67743
+
67744
+ // scripts/lib/host-compat.mjs
67745
+ function parseVersion(value) {
67746
+ if (typeof value !== "string")
67747
+ return null;
67748
+ const match = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+([0-9A-Za-z.-]+))?$/.exec(value.trim());
67749
+ if (match === null)
67750
+ return null;
67751
+ const prerelease = match[4] === undefined ? [] : match[4].split(".");
67752
+ if (prerelease.some((id) => /^\d+$/.test(id) && id.length > 1 && id.startsWith("0")))
67753
+ return null;
67754
+ return {
67755
+ major: Number(match[1]),
67756
+ minor: Number(match[2]),
67757
+ patch: Number(match[3]),
67758
+ prerelease,
67759
+ build: match[5] ?? ""
67760
+ };
67761
+ }
67762
+ function compareIdentifier(a, b) {
67763
+ const aNumeric = /^\d+$/.test(a);
67764
+ const bNumeric = /^\d+$/.test(b);
67765
+ if (aNumeric && bNumeric)
67766
+ return Math.sign(Number(a) - Number(b));
67767
+ if (aNumeric)
67768
+ return -1;
67769
+ if (bNumeric)
67770
+ return 1;
67771
+ return a < b ? -1 : a > b ? 1 : 0;
67772
+ }
67773
+ function compareVersions(left, right) {
67774
+ const a = parseVersion(left);
67775
+ const b = parseVersion(right);
67776
+ if (a === null || b === null) {
67777
+ throw new Error(`cannot compare non-semver values ${JSON.stringify(left)} / ${JSON.stringify(right)}`);
67778
+ }
67779
+ for (const field of ["major", "minor", "patch"]) {
67780
+ if (a[field] !== b[field])
67781
+ return a[field] < b[field] ? -1 : 1;
67782
+ }
67783
+ if (a.prerelease.length === 0 && b.prerelease.length > 0)
67784
+ return 1;
67785
+ if (a.prerelease.length > 0 && b.prerelease.length === 0)
67786
+ return -1;
67787
+ for (let i = 0;i < Math.max(a.prerelease.length, b.prerelease.length); i++) {
67788
+ if (i >= a.prerelease.length)
67789
+ return -1;
67790
+ if (i >= b.prerelease.length)
67791
+ return 1;
67792
+ const cmp = compareIdentifier(a.prerelease[i], b.prerelease[i]);
67793
+ if (cmp !== 0)
67794
+ return cmp;
67795
+ }
67796
+ return 0;
67797
+ }
67798
+ function isHostVersionSupported(version) {
67799
+ if (parseVersion(version) === null)
67800
+ return false;
67801
+ return compareVersions(version, SUPPORTED_FLOOR) >= 0 && compareVersions(version, SUPPORTED_CAP) < 0;
67802
+ }
67803
+ var HOST_PEER_RANGE = ">=0.2.2-rc.3 <0.3.0", SUPPORTED_FLOOR = "0.2.2-rc.3", SUPPORTED_CAP = "0.3.0";
67804
+ var init_host_compat = () => {};
67805
+
67806
+ // src/client/seam-bootstrap.ts
67807
+ var exports_seam_bootstrap = {};
67808
+ __export(exports_seam_bootstrap, {
67809
+ BRIDGE_APPEND_PRESET_NOTICE: () => BRIDGE_APPEND_PRESET_NOTICE,
67810
+ BRIDGE_PROTOCOL_VERSION: () => BRIDGE_PROTOCOL_VERSION,
67811
+ BRIDGE_REPAIR_COMMAND: () => BRIDGE_REPAIR_COMMAND,
67812
+ BRIDGE_REPAIR_HINT: () => BRIDGE_REPAIR_HINT,
67813
+ BridgeBootstrapError: () => BridgeBootstrapError,
67814
+ createBridgeSessionSeam: () => createBridgeSessionSeam,
67815
+ createSessionSeam: () => createSessionSeam,
67816
+ formatBridgeBootstrapMessage: () => formatBridgeBootstrapMessage,
67817
+ formatDeadNotice: () => formatDeadNotice,
67818
+ isInprocMode: () => isInprocMode,
67819
+ recoverBridgeSession: () => recoverBridgeSession,
67820
+ selectSeamKind: () => selectSeamKind,
67821
+ toBridgeBootstrapError: () => toBridgeBootstrapError,
67822
+ verifyBridgeFingerprint: () => verifyBridgeFingerprint,
67823
+ verifyRecoveryHandshake: () => verifyRecoveryHandshake
67824
+ });
67825
+ function selectSeamKind(input) {
67826
+ return input.inproc ? "bridge" : "remote";
67827
+ }
67828
+ function isInprocMode(env = process.env) {
67829
+ return env.DSH_OPENTUI_INPROC !== "0";
67830
+ }
67831
+ function formatBridgeBootstrapMessage(options) {
67832
+ return formatBridgeFailFastMessage(`dsh-opentui inproc bridge seam failed [${options.code}]: ${options.diagnosis}`, options.repairCommand ?? BRIDGE_REPAIR_COMMAND);
67833
+ }
67834
+ function toBridgeBootstrapError(err, fallbackCode = "BRIDGE_HANDSHAKE_FAILED") {
67835
+ if (err instanceof BridgeBootstrapError)
67836
+ return err;
67837
+ if (err instanceof BridgeProtocolError) {
67838
+ const detail = err.detail === undefined ? "" : ` (detail: ${JSON.stringify(err.detail)})`;
67839
+ return new BridgeBootstrapError({
67840
+ code: err.code || fallbackCode,
67841
+ diagnosis: `bridge handshake rejected: ${err.message}${detail}`
67842
+ });
67843
+ }
67844
+ const message = err instanceof Error ? err.message : String(err);
67845
+ return new BridgeBootstrapError({ code: fallbackCode, diagnosis: `bridge handshake failed: ${message}` });
67846
+ }
67847
+ function asRecord6(value) {
67848
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
67849
+ }
67850
+ function verifyBridgeFingerprint(hello, expectedProtocolVersion = BRIDGE_PROTOCOL_VERSION) {
67851
+ const h = asRecord6(hello);
67852
+ const protocolVersion = h.protocolVersion;
67853
+ if (protocolVersion !== expectedProtocolVersion) {
67854
+ throw new BridgeBootstrapError({
67855
+ code: "VERSION_INCOMPATIBLE",
67856
+ diagnosis: `protocolVersion mismatch: client=${expectedProtocolVersion}, ` + `bridge=${String(protocolVersion)}, host=${String(h.hostVersion ?? "unknown")}`
67857
+ });
67858
+ }
67859
+ const bridgeVersion = h.bridgeVersion;
67860
+ const hostVersion = h.hostVersion;
67861
+ if (typeof bridgeVersion !== "string" || bridgeVersion === "") {
67862
+ throw new BridgeBootstrapError({
67863
+ code: "FINGERPRINT_MISSING",
67864
+ diagnosis: `bridge.hello reply has no bridgeVersion (got ${String(bridgeVersion)})`
67865
+ });
67866
+ }
67867
+ if (typeof hostVersion !== "string" || hostVersion === "") {
67868
+ throw new BridgeBootstrapError({
67869
+ code: "FINGERPRINT_MISSING",
67870
+ diagnosis: `bridge.hello reply has no hostVersion (got ${String(hostVersion)})`
67871
+ });
67872
+ }
67873
+ return { protocolVersion, bridgeVersion, hostVersion };
67874
+ }
67875
+ function verifyRecoveryHandshake(hello, expectedProtocolVersion = BRIDGE_PROTOCOL_VERSION) {
67876
+ const fingerprint = verifyBridgeFingerprint(hello, expectedProtocolVersion);
67877
+ if (!isHostVersionSupported(fingerprint.hostVersion)) {
67878
+ throw new BridgeBootstrapError({
67879
+ code: "HOST_INCOMPATIBLE",
67880
+ diagnosis: `hostVersion ${fingerprint.hostVersion} is outside the supported window ${HOST_PEER_RANGE} ` + `(bridge ${fingerprint.bridgeVersion}, client protocol ${expectedProtocolVersion})`
67881
+ });
67882
+ }
67883
+ return fingerprint;
67884
+ }
67885
+ function formatDeadNotice(cause) {
67886
+ const detail = [];
67887
+ if (cause.code !== null)
67888
+ detail.push(`exit ${cause.code}`);
67889
+ if (cause.signal !== null)
67890
+ detail.push(cause.signal);
67891
+ detail.push(`stage ${cause.stage}`);
67892
+ return `\u26A0 \u8FDE\u63A5\u5DF2\u65AD\u5F00: ${cause.message} (${detail.join(", ")})`;
67893
+ }
67894
+ function deadCauseFromBootstrapError(err) {
67895
+ if (!(err instanceof BridgeProtocolError) || err.code !== "BRIDGE_DEAD")
67896
+ return;
67897
+ const detail = err.detail;
67898
+ if (detail === null || typeof detail !== "object")
67899
+ return;
67900
+ const r = detail;
67901
+ return {
67902
+ stage: "handshake",
67903
+ code: typeof r.code === "number" ? r.code : null,
67904
+ signal: typeof r.signal === "string" ? r.signal : null,
67905
+ message: typeof r.message === "string" ? r.message : err.message
67906
+ };
67907
+ }
67908
+ async function createBridgeSessionSeam(options) {
67909
+ const version = options.expectedProtocolVersion ?? BRIDGE_PROTOCOL_VERSION;
67910
+ let hello;
67911
+ try {
67912
+ hello = await options.transport.request("bridge.hello", { protocolVersion: version });
67913
+ } catch (err) {
67914
+ const cause = deadCauseFromBootstrapError(err);
67915
+ if (cause !== undefined)
67916
+ options.onDead?.(cause);
67917
+ throw toBridgeBootstrapError(err);
67918
+ }
67919
+ verifyBridgeFingerprint(hello, version);
67920
+ const seam = new BridgeSessionSeam({
67921
+ transport: options.transport,
67922
+ ctx: options.ctx,
67923
+ onDead: options.onDead,
67924
+ onPermissionUnavailable: options.onPermissionUnavailable
67925
+ });
67926
+ await seam.connect();
67927
+ return seam;
67928
+ }
67929
+ async function createSessionSeam(options) {
67930
+ if (options.kind === "remote")
67931
+ return options.createRemote();
67932
+ return options.createBridge();
67933
+ }
67934
+ async function recoverBridgeSession(options) {
67935
+ await options.transport.recover();
67936
+ return options.seam.recoverSession();
67937
+ }
67938
+ var BRIDGE_PROTOCOL_VERSION = 1, BridgeBootstrapError;
67939
+ var init_seam_bootstrap = __esm(() => {
67940
+ init_bridge_session_seam();
67941
+ init_bridge_failfast_text();
67942
+ init_host_compat();
67943
+ init_bridge_failfast_text();
67944
+ BridgeBootstrapError = class BridgeBootstrapError extends Error {
67945
+ code;
67946
+ diagnosis;
67947
+ repairCommand;
67948
+ constructor(options) {
67949
+ super(formatBridgeBootstrapMessage(options));
67950
+ this.name = "BridgeBootstrapError";
67951
+ this.code = options.code;
67952
+ this.diagnosis = options.diagnosis;
67953
+ this.repairCommand = options.repairCommand ?? BRIDGE_REPAIR_COMMAND;
67954
+ }
67955
+ };
67956
+ });
67957
+
65203
67958
  // ../tui-base/examples/v2-entry.tsx
65204
67959
  import { join as join15 } from "path";
65205
67960
  import { existsSync as existsSync12 } from "fs";
@@ -65215,16 +67970,17 @@ function resolveWatchdogScript() {
65215
67970
  return null;
65216
67971
  }
65217
67972
  async function loadShell() {
65218
- const [shared, lifecycle, clifecycle, transport, rhs, adapter, git] = await Promise.all([
67973
+ const [shared, lifecycle, clifecycle, transport, rhs, adapter, git, seamBootstrap] = await Promise.all([
65219
67974
  Promise.resolve().then(() => (init_boot_shared(), exports_boot_shared)),
65220
67975
  Promise.resolve().then(() => (init_lifecycle(), exports_lifecycle)),
65221
67976
  Promise.resolve().then(() => (init_client_lifecycle(), exports_client_lifecycle)),
65222
67977
  Promise.resolve().then(() => (init_transport(), exports_transport)),
65223
67978
  Promise.resolve().then(() => (init_remote_host_session(), exports_remote_host_session)),
65224
67979
  Promise.resolve().then(() => (init_session_seam_adapter(), exports_session_seam_adapter)),
65225
- Promise.resolve().then(() => (init_remote_git(), exports_remote_git))
67980
+ Promise.resolve().then(() => (init_remote_git(), exports_remote_git)),
67981
+ Promise.resolve().then(() => (init_seam_bootstrap(), exports_seam_bootstrap))
65226
67982
  ]);
65227
- return { shared, lifecycle, clifecycle, transport, rhs, adapter, git };
67983
+ return { shared, lifecycle, clifecycle, transport, rhs, adapter, git, seamBootstrap };
65228
67984
  }
65229
67985
  function V2SessionPage(props) {
65230
67986
  return createComponent2(DockProvider, {
@@ -65271,6 +68027,39 @@ function V2SessionPageBody(props) {
65271
68027
  const [tools, setTools] = createSignal(0);
65272
68028
  const [effort, setEffort] = createSignal();
65273
68029
  const [remoteInfo, setRemoteInfo] = createSignal();
68030
+ const [bridgeStatus, setBridgeStatus] = createSignal("ready");
68031
+ let recoveryNewSession = () => {};
68032
+ const recoveryQuit = () => props.quit();
68033
+ const recoveryTexts = {
68034
+ transient: () => t("recovery.transient"),
68035
+ recovered: (count) => t("recovery.recovered", { count: String(count) }),
68036
+ failedReason: (reason) => t("recovery.failed.reason", { reason }),
68037
+ locked: (reason, holder) => reason === undefined ? t("recovery.locked") : holder === undefined ? t("recovery.locked.reason", { reason }) : t("recovery.locked.holder", { reason, holder }),
68038
+ cooldown: (remainingMs) => t("recovery.cooldown", { remainingMs: String(remainingMs) }),
68039
+ reconnect: () => t("recovery.action.reconnect"),
68040
+ retry: () => t("recovery.action.retry"),
68041
+ newSession: () => t("recovery.action.newSession"),
68042
+ quit: () => t("recovery.action.quit")
68043
+ };
68044
+ const recovery = new RecoveryUiController({
68045
+ recover: () => props.recoverBridge ? props.recoverBridge() : Promise.reject(new Error("no bridge transport injected")),
68046
+ texts: recoveryTexts,
68047
+ onNotice: (text, ttl, kind) => void showNotice(text, ttl, kind),
68048
+ onNewSession: () => recoveryNewSession(),
68049
+ onQuit: () => recoveryQuit()
68050
+ });
68051
+ const recoveryEvents = new Set([
68052
+ "bridge.dead",
68053
+ "bridge.recovered",
68054
+ "bridge.recovery.locked",
68055
+ "bridge.recovery.failed"
68056
+ ]);
68057
+ onCleanup(seam.onSessionEvent?.((event) => {
68058
+ if (!recoveryEvents.has(event?.type))
68059
+ return;
68060
+ recovery.handleEvent(event);
68061
+ }) ?? (() => {}));
68062
+ onCleanup(recovery.subscribe(() => setBridgeStatus(recovery.footerStatus)));
65274
68063
  const [now, setNow] = createSignal(new Date);
65275
68064
  const [contextRevision, setContextRevision] = createSignal(0);
65276
68065
  let contextFrameTitle;
@@ -65436,7 +68225,6 @@ function V2SessionPageBody(props) {
65436
68225
  return;
65437
68226
  }
65438
68227
  setRemoteInfo({
65439
- messageCount: info.messageCount,
65440
68228
  msgCount: info.msgCount,
65441
68229
  tps: info.lastTurnTps ?? info.sessionAvgTps
65442
68230
  });
@@ -65467,6 +68255,7 @@ function V2SessionPageBody(props) {
65467
68255
  contextWindow: ctxWindow(),
65468
68256
  cacheHitRate: cacheRate(),
65469
68257
  presetLabel: presetLabel(),
68258
+ bridgeStatus: bridgeStatus(),
65470
68259
  theme,
65471
68260
  mode: themeService.mode()
65472
68261
  });
@@ -65579,6 +68368,7 @@ function V2SessionPageBody(props) {
65579
68368
  };
65580
68369
  const reloadSession = (sessionId) => {
65581
68370
  setLastRequest(undefined);
68371
+ setSessionIdFromRecovery(undefined);
65582
68372
  composerRef?.resetDeliveries();
65583
68373
  setComposerPending([]);
65584
68374
  setTools(0);
@@ -65634,8 +68424,10 @@ function V2SessionPageBody(props) {
65634
68424
  footerRefreshSeq++;
65635
68425
  },
65636
68426
  themes: themeFace,
65637
- flushQueue: () => composerRef?.flushQueue() ?? { kind: "empty", started: 0, remaining: 0 }
68427
+ flushQueue: () => composerRef?.flushQueue() ?? { kind: "empty", started: 0, remaining: 0 },
68428
+ clearRecoveryUi: () => recovery.clearRecoveryState()
65638
68429
  }));
68430
+ recoveryNewSession = () => void slash.interceptSubmit("/new");
65639
68431
  Keymap2.createLayer(() => ({
65640
68432
  enabled: () => pageOwns(),
65641
68433
  commands: [
@@ -65647,6 +68439,11 @@ function V2SessionPageBody(props) {
65647
68439
  }
65648
68440
  ]
65649
68441
  }));
68442
+ Keymap2.createLayer(() => ({
68443
+ mode: "global",
68444
+ enabled: () => pageOwns() || recovery.canRecover(),
68445
+ commands: [recovery.reconnectCommand()]
68446
+ }));
65650
68447
  const overlayHost = createComponent2(TurnOverlayHost, {
65651
68448
  controller: overlays,
65652
68449
  reclaimFocus: () => {
@@ -65800,6 +68597,8 @@ function V2SessionPageBody(props) {
65800
68597
  seam,
65801
68598
  send,
65802
68599
  footerHint: false,
68600
+ disabled: () => recovery.composerDisabled,
68601
+ disabledReason: () => t("recovery.composer.disabled"),
65803
68602
  frameTitle: () => contextFrameTitle?.() ?? "",
65804
68603
  onBusyChange: setComposerBusy,
65805
68604
  ref: (r) => composerRef = r,
@@ -65825,6 +68624,7 @@ function V2SessionPageBody(props) {
65825
68624
  }
65826
68625
  }),
65827
68626
  createComponent2(NoticesDock, {}),
68627
+ createComponent2(RecoveryBanner, { controller: recovery }),
65828
68628
  createComponent2(SubagentsPicker, {
65829
68629
  get seam() {
65830
68630
  return seam;
@@ -65886,7 +68686,7 @@ function appendDiagnostic(line) {
65886
68686
  } catch {}
65887
68687
  }
65888
68688
  async function bootClientV2(options = {}) {
65889
- const { shared, lifecycle, clifecycle, transport, rhs, adapter, git } = await loadShell();
68689
+ const { shared, lifecycle, clifecycle, transport, rhs, adapter, git, seamBootstrap } = await loadShell();
65890
68690
  const workspace = process.cwd();
65891
68691
  const profile = lifecycle.DEFAULT_PROFILE;
65892
68692
  const idleExitMs = lifecycle.resolveIdleExitMs();
@@ -65934,16 +68734,46 @@ async function bootClientV2(options = {}) {
65934
68734
  await new Promise((resolve) => setTimeout(resolve, 100));
65935
68735
  }
65936
68736
  }
65937
- const seam = new adapter.RemoteSessionSeam(session);
65938
- registerTurnOverlays(seam, overlays);
65939
68737
  const launchArgs = parseLaunchArgs(options.argv ?? process.argv.slice(2));
68738
+ const seamKind = seamBootstrap.selectSeamKind({
68739
+ inproc: seamBootstrap.isInprocMode()
68740
+ });
68741
+ const seam = await seamBootstrap.createSessionSeam({
68742
+ kind: seamKind,
68743
+ createBridge: async () => {
68744
+ if (options.bridgeTransport === undefined) {
68745
+ throw new seamBootstrap.BridgeBootstrapError({
68746
+ code: "BRIDGE_TRANSPORT_MISSING",
68747
+ diagnosis: "bridge seam is selected (DSH_OPENTUI_INPROC is not 0) but no bridge transport was injected at the synthetic root"
68748
+ });
68749
+ }
68750
+ return seamBootstrap.createBridgeSessionSeam({
68751
+ transport: options.bridgeTransport,
68752
+ ctx: options.bridgeCtx ?? { logger: console },
68753
+ onDead: (cause) => void showNotice(`${seamBootstrap.formatDeadNotice(cause)} \xB7 ${t("recovery.action.reconnect")}`, undefined, "error"),
68754
+ onPermissionUnavailable: (reason) => void showNotice(`${t("notice.permission.unavailable")} \xB7 ${t(`notice.permission.reason.${reason}`)}`, undefined, "error")
68755
+ });
68756
+ },
68757
+ createRemote: () => new adapter.RemoteSessionSeam(session)
68758
+ });
68759
+ const recoverBridge = seamKind === "bridge" && options.bridgeTransport !== undefined ? () => seamBootstrap.recoverBridgeSession({
68760
+ transport: options.bridgeTransport,
68761
+ seam
68762
+ }) : undefined;
68763
+ registerTurnOverlays(seam, overlays, {
68764
+ deadReason: (details) => {
68765
+ const cause = details;
68766
+ const detail = typeof cause?.message === "string" && cause.message.trim() !== "" ? cause.message : "";
68767
+ return detail === "" ? t("overlay.ask.invalidated.disconnected") : `${t("overlay.ask.invalidated.disconnected")} \xB7 ${detail}`;
68768
+ }
68769
+ });
65940
68770
  let initialSessionId;
65941
68771
  let resumeNotice;
65942
68772
  if (launchArgs.sessionId !== undefined) {
65943
68773
  seam.resumeSession(launchArgs.sessionId);
65944
68774
  initialSessionId = launchArgs.sessionId;
65945
68775
  } else {
65946
- const autoResume = await runAutoResume({ config: seam.configLoad(), launch: launchArgs, workspace }, {
68776
+ const autoResume = await runAutoResume({ config: seam.configLoad?.() ?? {}, launch: launchArgs, workspace }, {
65947
68777
  listSessions: (limit) => seam.listSessions(limit),
65948
68778
  resumeSession: (id) => seam.resumeSession(id),
65949
68779
  warn: (message) => console.warn(message)
@@ -65951,7 +68781,7 @@ async function bootClientV2(options = {}) {
65951
68781
  initialSessionId = autoResume?.id;
65952
68782
  resumeNotice = autoResume?.line;
65953
68783
  }
65954
- const agentsHomeConfig = seam.configLoad().agentsHome;
68784
+ const agentsHomeConfig = (seam.configLoad?.() ?? {}).agentsHome;
65955
68785
  const agentsHomeForSkills = resolveAgentsHome(agentsHomeConfig);
65956
68786
  pendingAgentsHomeNotice = agentsHomeEnvWarning(undefined, agentsHomeConfig);
65957
68787
  const skillRows = discoverSkills({
@@ -65964,9 +68794,9 @@ async function bootClientV2(options = {}) {
65964
68794
  curated: join15(host.dshHome, "skills")
65965
68795
  };
65966
68796
  const envTheme = process.env[shared.ENV_THEME];
65967
- const workspaceConfig = seam.workspaceConfig();
68797
+ const workspaceConfig = seam.workspaceConfig?.() ?? {};
65968
68798
  const migration = shared.skinMigrationPlan({
65969
- profileConfig: seam.configRaw(),
68799
+ profileConfig: seam.configRaw?.() ?? {},
65970
68800
  workspaceConfig,
65971
68801
  envTheme
65972
68802
  });
@@ -65997,6 +68827,12 @@ async function bootClientV2(options = {}) {
65997
68827
  try {
65998
68828
  await Promise.race([session.dispose(), new Promise((resolve) => setTimeout(resolve, shared.SHUTDOWN_GRACE_MS))]);
65999
68829
  } catch {}
68830
+ if (seamKind === "bridge") {
68831
+ try {
68832
+ await Promise.race([seam.dispose(), new Promise((resolve) => setTimeout(resolve, shared.SHUTDOWN_GRACE_MS))]);
68833
+ } catch {}
68834
+ options.bridgeTransport?.close?.();
68835
+ }
66000
68836
  if (clientHeartbeat) {
66001
68837
  clientHeartbeat.stop();
66002
68838
  clientHeartbeat.remove();
@@ -66040,6 +68876,7 @@ async function bootClientV2(options = {}) {
66040
68876
  seam,
66041
68877
  themeName,
66042
68878
  quit: () => process.exit(0),
68879
+ recoverBridge,
66043
68880
  workspace,
66044
68881
  profileName: profile,
66045
68882
  probeBranch: (cwd) => git.probeGitBranchOrSha(cwd),
@@ -66114,6 +68951,7 @@ var init_v2_entry = __esm(() => {
66114
68951
  init_widgets_dock();
66115
68952
  init_lastrequest_dock();
66116
68953
  init_notices_dock();
68954
+ init_recovery_banner();
66117
68955
  init_hints_line();
66118
68956
  init_widgets_dock();
66119
68957
  init_src();
@@ -66161,6 +68999,287 @@ var init_v2_entry = __esm(() => {
66161
68999
  if (false) {}
66162
69000
  });
66163
69001
 
69002
+ // src/client/bridge-transport.ts
69003
+ import { spawn as nodeSpawn2 } from "child_process";
69004
+ import { homedir as homedir9 } from "os";
69005
+ import { join as join16 } from "path";
69006
+ function recoveryCause(err, phase) {
69007
+ if (err instanceof BridgeBootstrapError) {
69008
+ return {
69009
+ stage: "handshake",
69010
+ code: null,
69011
+ signal: null,
69012
+ message: err.diagnosis,
69013
+ recoverability: "permanent",
69014
+ mismatches: [err.code]
69015
+ };
69016
+ }
69017
+ if (err instanceof BridgeProtocolError && err.code === "BRIDGE_DEAD") {
69018
+ const detail = asRecord7(err.detail);
69019
+ return {
69020
+ stage: phase,
69021
+ code: typeof detail.code === "number" ? detail.code : null,
69022
+ signal: typeof detail.signal === "string" ? detail.signal : null,
69023
+ message: err.message
69024
+ };
69025
+ }
69026
+ const message = err instanceof Error ? err.message : String(err);
69027
+ return { stage: phase, code: null, signal: null, message };
69028
+ }
69029
+
69030
+ class StdioBridgeTransport {
69031
+ #opts;
69032
+ #child;
69033
+ #nextId = 1;
69034
+ #pending = new Map;
69035
+ #listeners = new Set;
69036
+ #stdoutBuffer = "";
69037
+ #stderrTail = [];
69038
+ #deadError;
69039
+ #deadCause;
69040
+ #state = "initializing";
69041
+ #attempts = 0;
69042
+ #deadAt;
69043
+ #connectionGeneration = 0;
69044
+ constructor(options = {}) {
69045
+ this.#opts = options;
69046
+ }
69047
+ get diagnostics() {
69048
+ return this.#stderrTail.slice(-12).join(`
69049
+ `);
69050
+ }
69051
+ get state() {
69052
+ return this.#state;
69053
+ }
69054
+ get attempts() {
69055
+ return this.#attempts;
69056
+ }
69057
+ get deadCause() {
69058
+ return this.#deadCause;
69059
+ }
69060
+ #setState(next) {
69061
+ if (this.#state === next)
69062
+ return;
69063
+ this.#state = next;
69064
+ this.#opts.onStateChange?.(next);
69065
+ }
69066
+ #spawn() {
69067
+ if (this.#child !== undefined)
69068
+ return this.#child;
69069
+ const dshHome = this.#opts.dshHome ?? process.env.DSH_HOME ?? join16(homedir9(), ".dsh");
69070
+ const env = {
69071
+ ...process.env,
69072
+ ...this.#opts.env ?? {},
69073
+ DSH_HOME: dshHome,
69074
+ DSH_OPENTUI_BRIDGE_STDIO: "1"
69075
+ };
69076
+ const spawnFn = this.#opts.spawnFn ?? ((command, args, options) => nodeSpawn2(command, [...args], options));
69077
+ const child = spawnFn(this.#opts.dshBin ?? "dsh", ["--profile", this.#opts.profile ?? "opentui-inproc"], {
69078
+ env,
69079
+ stdio: ["pipe", "pipe", "pipe"]
69080
+ });
69081
+ const generation = ++this.#connectionGeneration;
69082
+ this.#child = child;
69083
+ child.stdout.on("data", (chunk) => {
69084
+ if (generation !== this.#connectionGeneration)
69085
+ return;
69086
+ this.#onStdout(chunk);
69087
+ });
69088
+ child.stderr.on("data", (chunk) => {
69089
+ if (generation !== this.#connectionGeneration)
69090
+ return;
69091
+ const text = typeof chunk === "string" ? chunk : chunk.toString("utf8");
69092
+ this.#stderrTail.push(...text.split(`
69093
+ `).filter(Boolean));
69094
+ if (this.#stderrTail.length > 64)
69095
+ this.#stderrTail.splice(0, this.#stderrTail.length - 64);
69096
+ });
69097
+ child.on("exit", (code, signal) => {
69098
+ if (generation !== this.#connectionGeneration)
69099
+ return;
69100
+ const exitCode = typeof code === "number" ? code : null;
69101
+ const exitSignal = typeof signal === "string" ? signal : null;
69102
+ const message = `bridge host exited (code ${String(code)}${exitSignal === null ? "" : `, signal ${exitSignal}`})`;
69103
+ this.#onDead(message, { stage: "runtime", code: exitCode, signal: exitSignal, message });
69104
+ });
69105
+ child.on("error", (err) => {
69106
+ if (generation !== this.#connectionGeneration)
69107
+ return;
69108
+ const message = `bridge host error: ${err instanceof Error ? err.message : String(err)}`;
69109
+ this.#onDead(message, { stage: "spawn", code: null, signal: null, message });
69110
+ });
69111
+ return child;
69112
+ }
69113
+ #onStdout(chunk) {
69114
+ this.#stdoutBuffer += typeof chunk === "string" ? chunk : chunk.toString("utf8");
69115
+ let newline = this.#stdoutBuffer.indexOf(`
69116
+ `);
69117
+ while (newline >= 0) {
69118
+ const line = this.#stdoutBuffer.slice(0, newline).trim();
69119
+ this.#stdoutBuffer = this.#stdoutBuffer.slice(newline + 1);
69120
+ if (line !== "")
69121
+ this.#handleFrame(line);
69122
+ newline = this.#stdoutBuffer.indexOf(`
69123
+ `);
69124
+ }
69125
+ }
69126
+ #handleFrame(line) {
69127
+ let frame;
69128
+ try {
69129
+ frame = JSON.parse(line);
69130
+ } catch {
69131
+ return;
69132
+ }
69133
+ const rec = asRecord7(frame);
69134
+ if (typeof rec.id === "number") {
69135
+ const pending = this.#pending.get(rec.id);
69136
+ if (pending === undefined)
69137
+ return;
69138
+ this.#pending.delete(rec.id);
69139
+ clearTimeout(pending.timer);
69140
+ if (rec.ok === true) {
69141
+ if (this.#state === "initializing")
69142
+ this.#setState("ready");
69143
+ pending.resolve(rec.result);
69144
+ } else {
69145
+ const error = asRecord7(rec.error);
69146
+ pending.reject(new BridgeProtocolError(typeof error.code === "string" ? error.code : "BRIDGE_ERROR", typeof error.message === "string" ? error.message : "bridge request failed", error.detail));
69147
+ }
69148
+ return;
69149
+ }
69150
+ if (typeof rec.type === "string") {
69151
+ this.#publish({ type: rec.type, payload: rec.payload });
69152
+ }
69153
+ }
69154
+ #publish(event) {
69155
+ for (const listener of [...this.#listeners]) {
69156
+ try {
69157
+ listener(event);
69158
+ } catch {}
69159
+ }
69160
+ }
69161
+ #onDead(reason, cause) {
69162
+ const firstDead = this.#state !== "dead" && this.#state !== "closed";
69163
+ if (firstDead) {
69164
+ this.#deadAt = (this.#opts.now ?? Date.now)();
69165
+ this.#attempts += 1;
69166
+ }
69167
+ if (this.#state !== "closed")
69168
+ this.#setState("dead");
69169
+ if (this.#deadError === undefined) {
69170
+ const tail = this.diagnostics ? ` (stderr tail: ${this.diagnostics})` : "";
69171
+ this.#deadError = new BridgeProtocolError("BRIDGE_DEAD", `${reason}${tail}`, cause);
69172
+ this.#deadCause = cause;
69173
+ this.#publish({ type: "bridge.dead", payload: cause });
69174
+ }
69175
+ for (const [id, pending] of [...this.#pending]) {
69176
+ this.#pending.delete(id);
69177
+ clearTimeout(pending.timer);
69178
+ pending.reject(this.#deadError);
69179
+ }
69180
+ }
69181
+ request(method, params) {
69182
+ if (this.#state === "closed") {
69183
+ return Promise.reject(new BridgeProtocolError("BRIDGE_CLOSED", "bridge transport is closed"));
69184
+ }
69185
+ if (this.#state === "recovering" || this.#state === "handshake") {
69186
+ return Promise.reject(new BridgeProtocolError("BRIDGE_RECOVERING", "bridge transport is recovering; request rejected", {
69187
+ state: this.#state
69188
+ }));
69189
+ }
69190
+ if (this.#deadError !== undefined)
69191
+ return Promise.reject(this.#deadError);
69192
+ return this.#sendRequest(method, params);
69193
+ }
69194
+ #sendRequest(method, params) {
69195
+ const child = this.#spawn();
69196
+ const id = this.#nextId++;
69197
+ return new Promise((resolve, reject) => {
69198
+ const timer = setTimeout(() => {
69199
+ this.#pending.delete(id);
69200
+ reject(new BridgeProtocolError("BRIDGE_TIMEOUT", `no reply for ${method} within ${this.#opts.replyTimeoutMs ?? 30000}ms`));
69201
+ }, this.#opts.replyTimeoutMs ?? 30000);
69202
+ this.#pending.set(id, { resolve, reject, timer });
69203
+ try {
69204
+ child.stdin.write(`${JSON.stringify({ id, method, ...params === undefined ? {} : { params } })}
69205
+ `);
69206
+ } catch (err) {
69207
+ this.#pending.delete(id);
69208
+ clearTimeout(timer);
69209
+ reject(new BridgeProtocolError("BRIDGE_WRITE_FAILED", String(err)));
69210
+ }
69211
+ });
69212
+ }
69213
+ async recover() {
69214
+ if (this.#state === "closed") {
69215
+ throw new BridgeProtocolError("BRIDGE_CLOSED", "bridge transport is closed; recover() refused");
69216
+ }
69217
+ if (this.#state !== "dead") {
69218
+ throw new BridgeProtocolError("BRIDGE_NOT_DEAD", `recover() requires DEAD state (current: ${this.#state})`, { state: this.#state });
69219
+ }
69220
+ const now = this.#opts.now ?? Date.now;
69221
+ const cooldown = this.#opts.recoverCooldownMs ?? 5000;
69222
+ const elapsed = this.#deadAt === undefined ? cooldown : now() - this.#deadAt;
69223
+ if (elapsed < cooldown) {
69224
+ throw new BridgeProtocolError("BRIDGE_RECOVERY_COOLDOWN", `recover() cooling down; retry in ${cooldown - elapsed}ms`, { remainingMs: cooldown - elapsed });
69225
+ }
69226
+ this.#setState("recovering");
69227
+ this.#deadError = undefined;
69228
+ this.#deadCause = undefined;
69229
+ this.#connectionGeneration++;
69230
+ for (const [id, pending] of [...this.#pending]) {
69231
+ this.#pending.delete(id);
69232
+ clearTimeout(pending.timer);
69233
+ pending.reject(new BridgeProtocolError("BRIDGE_RECOVERING", "bridge recovering; in-flight request dropped"));
69234
+ }
69235
+ this.#nextId = 1;
69236
+ this.#stdoutBuffer = "";
69237
+ try {
69238
+ try {
69239
+ this.#child?.kill("SIGTERM");
69240
+ } catch {}
69241
+ this.#child = undefined;
69242
+ this.#spawn();
69243
+ this.#setState("handshake");
69244
+ const hello = await this.#sendRequest("bridge.hello", { protocolVersion: BRIDGE_PROTOCOL_VERSION });
69245
+ verifyRecoveryHandshake(hello, BRIDGE_PROTOCOL_VERSION);
69246
+ } catch (err) {
69247
+ if (this.#state === "dead" || this.#state === "closed")
69248
+ throw err;
69249
+ const cause = recoveryCause(err, this.#state === "handshake" ? "handshake" : "spawn");
69250
+ this.#onDead(cause.message, cause);
69251
+ throw err;
69252
+ }
69253
+ this.#setState("ready");
69254
+ }
69255
+ onEvent(listener) {
69256
+ this.#listeners.add(listener);
69257
+ return () => {
69258
+ this.#listeners.delete(listener);
69259
+ };
69260
+ }
69261
+ close() {
69262
+ if (this.#state === "closed")
69263
+ return;
69264
+ this.#connectionGeneration++;
69265
+ this.#setState("closed");
69266
+ this.#onDead("bridge transport closed", {
69267
+ stage: "closed",
69268
+ code: null,
69269
+ signal: null,
69270
+ message: "bridge transport closed"
69271
+ });
69272
+ try {
69273
+ this.#child?.kill("SIGTERM");
69274
+ } catch {}
69275
+ }
69276
+ }
69277
+ var asRecord7 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
69278
+ var init_bridge_transport = __esm(() => {
69279
+ init_bridge_session_seam();
69280
+ init_seam_bootstrap();
69281
+ });
69282
+
66164
69283
  // src/client-entry.tsx
66165
69284
  init_client_lifecycle();
66166
69285
  init_boot_shared();
@@ -66169,12 +69288,12 @@ init_lifecycle();
66169
69288
  init_transport();
66170
69289
  init_remote_host_session();
66171
69290
  import { existsSync as existsSync13 } from "fs";
66172
- import { join as join16 } from "path";
69291
+ import { join as join17 } from "path";
66173
69292
  function resolveWatchdogScript2() {
66174
69293
  const candidates = [
66175
- join16(import.meta.dir, "..", "watchdog.mjs"),
66176
- join16(import.meta.dir, "..", "dist", "watchdog.mjs"),
66177
- join16(import.meta.dir, "..", "scripts", "watchdog.mjs")
69294
+ join17(import.meta.dir, "..", "watchdog.mjs"),
69295
+ join17(import.meta.dir, "..", "dist", "watchdog.mjs"),
69296
+ join17(import.meta.dir, "..", "scripts", "watchdog.mjs")
66178
69297
  ];
66179
69298
  for (const candidate of candidates) {
66180
69299
  if (existsSync13(candidate))
@@ -66321,7 +69440,17 @@ async function main() {
66321
69440
  try {
66322
69441
  const v2Specifier = "../../" + "tui-base/examples/v2-entry.tsx";
66323
69442
  const mod = await Promise.resolve().then(() => (init_v2_entry(), {}));
66324
- await bootClientV2();
69443
+ const argv = process.argv.slice(2);
69444
+ let bootOptions = { argv };
69445
+ if (process.env.DSH_OPENTUI_INPROC !== "0") {
69446
+ const bridgeMod = await Promise.resolve().then(() => (init_bridge_transport(), {}));
69447
+ bootOptions = {
69448
+ ...bootOptions,
69449
+ bridgeTransport: new StdioBridgeTransport,
69450
+ bridgeCtx: { logger: console }
69451
+ };
69452
+ }
69453
+ await bootClientV2(bootOptions);
66325
69454
  } catch (error) {
66326
69455
  const message = error instanceof Error ? error.stack ?? error.message : String(error);
66327
69456
  process.stderr.write(`dsh-opentui client boot failed: ${message}
@@ -66342,5 +69471,5 @@ export {
66342
69471
  themeNameFromConfig
66343
69472
  };
66344
69473
 
66345
- //# debugId=83D4422F420B351864756E2164756E21
69474
+ //# debugId=CF96FD408007020364756E2164756E21
66346
69475
  //# sourceMappingURL=index.js.map