@aiwayds/dsh-opentui 0.28.2 → 0.29.1

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.
@@ -3587,6 +3587,56 @@ var init_terminal_size = __esm(() => {
3587
3587
  });
3588
3588
 
3589
3589
  // ../tui-base/src/routes/session/composer-state.ts
3590
+ function isAbortTurnCode(code) {
3591
+ return code === "ABORTED" || code === "USER_ABORT" || code === "SESSION_CLOSED" || code === "FORKED" || code === "INTERRUPTED" || code === "TURN_ABORT_NOOP";
3592
+ }
3593
+
3594
+ class TurnOutcomeTracker {
3595
+ activeTurnId;
3596
+ outcome;
3597
+ beginTurn() {
3598
+ this.activeTurnId = undefined;
3599
+ this.outcome = undefined;
3600
+ }
3601
+ onEvent(event) {
3602
+ const details = event?.details ?? {};
3603
+ if (event?.type === "session.updated" && details.turn === "starting") {
3604
+ const id = details.turnId;
3605
+ if (typeof id === "string" && id !== "")
3606
+ this.activeTurnId = id;
3607
+ return;
3608
+ }
3609
+ if (this.activeTurnId === undefined)
3610
+ return;
3611
+ if (event?.type === "session.error") {
3612
+ if (details.turnId !== this.activeTurnId)
3613
+ return;
3614
+ const code = typeof details.code === "string" ? details.code : "INTERNAL";
3615
+ this.outcome = isAbortTurnCode(code) ? "aborted" : "failed";
3616
+ return;
3617
+ }
3618
+ if (event?.type === "bridge.turn.terminal") {
3619
+ if (details.turnId !== this.activeTurnId)
3620
+ return;
3621
+ if (details.terminalType === "turn/error") {
3622
+ const reason = details.reason ?? {};
3623
+ const code = typeof reason.code === "string" ? reason.code : "INTERNAL";
3624
+ this.outcome = isAbortTurnCode(code) ? "aborted" : "failed";
3625
+ }
3626
+ return;
3627
+ }
3628
+ if (event?.type === "bridge.turn.interrupted" && details.turnId === this.activeTurnId) {
3629
+ this.outcome = "aborted";
3630
+ }
3631
+ }
3632
+ isFailed() {
3633
+ return this.outcome === "failed";
3634
+ }
3635
+ isAborted() {
3636
+ return this.outcome === "aborted";
3637
+ }
3638
+ }
3639
+
3590
3640
  class ComposerHistory {
3591
3641
  entries = [];
3592
3642
  index = null;
@@ -3637,11 +3687,13 @@ class ComposerController {
3637
3687
  history;
3638
3688
  send;
3639
3689
  steer;
3690
+ onSteerRejected;
3640
3691
  onBusyChange;
3641
3692
  chooseDelivery;
3642
3693
  onPendingChange;
3643
3694
  onQueuePaused;
3644
3695
  isTurnAborted;
3696
+ isTurnFailed;
3645
3697
  disabled;
3646
3698
  busyState = false;
3647
3699
  pendingTurn;
@@ -3649,14 +3701,18 @@ class ComposerController {
3649
3701
  pendingRows = [];
3650
3702
  deliverySeq = 0;
3651
3703
  deliveryEpoch = 0;
3704
+ turnGeneration = 0;
3705
+ steerTurnById = new Map;
3652
3706
  constructor(options) {
3653
3707
  this.send = options.send;
3654
3708
  this.steer = options.steer;
3709
+ this.onSteerRejected = options.onSteerRejected;
3655
3710
  this.onBusyChange = options.onBusyChange;
3656
3711
  this.chooseDelivery = options.chooseDelivery;
3657
3712
  this.onPendingChange = options.onPendingChange;
3658
3713
  this.onQueuePaused = options.onQueuePaused;
3659
3714
  this.isTurnAborted = options.isTurnAborted;
3715
+ this.isTurnFailed = options.isTurnFailed;
3660
3716
  this.disabled = options.disabled;
3661
3717
  this.history = options.history ?? new ComposerHistory;
3662
3718
  }
@@ -3695,22 +3751,26 @@ class ComposerController {
3695
3751
  return "cancelled";
3696
3752
  if (delivery === undefined)
3697
3753
  return "cancelled";
3698
- this.history.append(prompt);
3699
3754
  if (!this.busyState) {
3700
- this.startTurn(prompt);
3755
+ this.history.append(prompt);
3756
+ this.startTurn(prompt, "queue");
3701
3757
  return "sent";
3702
3758
  }
3703
3759
  if (delivery === "queue") {
3760
+ this.history.append(prompt);
3704
3761
  this.enqueue(prompt);
3705
3762
  return "queued";
3706
3763
  }
3707
- this.injectSteer(prompt);
3764
+ if (!await this.injectSteer(prompt))
3765
+ return "cancelled";
3766
+ this.history.append(prompt);
3708
3767
  return "steered";
3709
3768
  }
3710
3769
  resetDeliveries() {
3711
3770
  this.deliveryEpoch += 1;
3712
3771
  this.queueItems = [];
3713
3772
  this.pendingRows = [];
3773
+ this.steerTurnById.clear();
3714
3774
  this.emitPending();
3715
3775
  }
3716
3776
  flushQueue() {
@@ -3736,18 +3796,21 @@ class ComposerController {
3736
3796
  emitPending() {
3737
3797
  this.onPendingChange?.(this.pendingRows);
3738
3798
  }
3739
- startTurn(prompt) {
3799
+ startTurn(prompt, source = "user") {
3800
+ const generation = ++this.turnGeneration;
3740
3801
  this.setBusy(true);
3741
- let failed = false;
3742
- const turn = (async () => this.send(prompt))().then(() => {
3802
+ let sendRejected = false;
3803
+ const turn = (async () => this.send(prompt, source))().then(() => {
3743
3804
  return;
3744
3805
  }, () => {
3745
- failed = true;
3806
+ sendRejected = true;
3746
3807
  });
3747
3808
  this.pendingTurn = turn.finally(() => {
3748
3809
  this.pendingTurn = undefined;
3810
+ const failed = sendRejected || (this.isTurnFailed?.() ?? false);
3749
3811
  const aborted = !failed && (this.isTurnAborted?.() ?? false);
3750
- this.markSteerDelivered();
3812
+ if (!failed && !aborted)
3813
+ this.markSteerDelivered(generation);
3751
3814
  if (failed || aborted) {
3752
3815
  this.setBusy(false);
3753
3816
  if (this.queueItems.length > 0) {
@@ -3762,7 +3825,7 @@ class ComposerController {
3762
3825
  return;
3763
3826
  }
3764
3827
  this.dropQueueRow(next.id);
3765
- this.startTurn(next.text);
3828
+ this.startTurn(next.text, "queue");
3766
3829
  });
3767
3830
  }
3768
3831
  enqueue(prompt) {
@@ -3774,16 +3837,33 @@ class ComposerController {
3774
3837
  ];
3775
3838
  this.emitPending();
3776
3839
  }
3777
- injectSteer(prompt) {
3840
+ async injectSteer(prompt) {
3841
+ const epoch = this.deliveryEpoch;
3842
+ const generation = this.turnGeneration;
3843
+ let result;
3844
+ try {
3845
+ const awaited = await this.steer(prompt);
3846
+ result = awaited !== null && typeof awaited === "object" && typeof awaited.accepted === "boolean" ? awaited : { accepted: false, reason: "INVALID_STEER_RESULT" };
3847
+ } catch (err) {
3848
+ result = { accepted: false, reason: err instanceof Error ? err.message : String(err) };
3849
+ }
3850
+ if (epoch !== this.deliveryEpoch)
3851
+ return false;
3852
+ if (!result.accepted) {
3853
+ this.onSteerRejected?.({ text: prompt, reason: result.reason });
3854
+ return false;
3855
+ }
3778
3856
  const id = ++this.deliverySeq;
3857
+ this.steerTurnById.set(id, generation);
3779
3858
  this.pendingRows = [...this.pendingRows, { id, kind: "steer", state: "injected", text: prompt }];
3780
3859
  this.emitPending();
3781
- this.steer(prompt);
3860
+ return true;
3782
3861
  }
3783
- markSteerDelivered() {
3784
- if (!this.pendingRows.some((row) => row.kind === "steer" && row.state === "injected"))
3862
+ markSteerDelivered(generation) {
3863
+ const isMine = (row) => row.kind === "steer" && row.state === "injected" && this.steerTurnById.get(row.id) === generation;
3864
+ if (!this.pendingRows.some(isMine))
3785
3865
  return;
3786
- this.pendingRows = this.pendingRows.map((row) => row.kind === "steer" && row.state === "injected" ? { ...row, state: "delivered" } : row);
3866
+ this.pendingRows = this.pendingRows.map((row) => isMine(row) ? { ...row, state: "delivered" } : row);
3787
3867
  this.emitPending();
3788
3868
  }
3789
3869
  dropQueueRow(id) {
@@ -10804,6 +10884,9 @@ function decodeUnknownEffect(schema, options) {
10804
10884
  const parser = run(schema.ast);
10805
10885
  return options === undefined ? parser : (input, overrideOptions) => parser(input, mergeParseOptions(options, overrideOptions));
10806
10886
  }
10887
+ function decodeUnknownOption(schema, options) {
10888
+ return asOption(decodeUnknownEffect(schema, options));
10889
+ }
10807
10890
  function run(ast) {
10808
10891
  return runWithCompiler(normalCompiler, ast);
10809
10892
  }
@@ -10829,6 +10912,20 @@ function runWithCompiler(compiler, ast) {
10829
10912
  return result[args] === missing ? getValue(missing) : result;
10830
10913
  };
10831
10914
  }
10915
+ function asExit(parser) {
10916
+ return (input, options) => runSyncExit2(parser(input, options));
10917
+ }
10918
+ function asOption(parser) {
10919
+ const parserExit = asExit(parser);
10920
+ return (input, options) => {
10921
+ const exit = parserExit(input, options);
10922
+ if (isSuccess3(exit)) {
10923
+ return some2(exit.value);
10924
+ }
10925
+ getSchemaIssueOrThrow(exit.cause, "Option adapter can only return none for schema issues");
10926
+ return none2();
10927
+ };
10928
+ }
10832
10929
  function runSync2(effect, message) {
10833
10930
  const exit = runSyncExit2(effect);
10834
10931
  if (isSuccess3(exit)) {
@@ -11459,7 +11556,7 @@ function dateTimeArbitraryInteger(minimum, maximum) {
11459
11556
  maximum
11460
11557
  }));
11461
11558
  }
11462
- var TypeId23, SchemaError, make10, optionalKey2, optional2, toType2, Any2, Unknown2, Undefined2, String6, Number6, Boolean3, Symbol3, BigInt6, ArraySchema, NonEmptyArray, UndefinedOr, makeFilter2, Finite, isGreaterThan3, isGreaterThanOrEqualTo3, isLessThanOrEqualTo3, isBetween2, Int, NonEmptyString, RegExp3, URLString, URL2, File, URLSearchParams2, Base64String, Uint8Array2, dateTimeUtcFromString, arbitraryMinimumDateTimestamp = -8640000000000000, arbitraryMaximumDateTimestamp = 8640000000000000, arbitraryMinimumZonedDateTimeTimestamp, arbitraryMaximumZonedDateTimeTimestamp, arbitraryMinimumTimeZoneOffset, arbitraryMaximumTimeZoneOffset, DateTimeUtc, Json2, JsonObject;
11559
+ var TypeId23, SchemaError, decodeUnknownOption2, make10, optionalKey2, optional2, toType2, Any2, Unknown2, Undefined2, String6, Number6, Boolean3, Symbol3, BigInt6, ArraySchema, NonEmptyArray, UndefinedOr, makeFilter2, Finite, isGreaterThan3, isGreaterThanOrEqualTo3, isLessThanOrEqualTo3, isBetween2, Int, NonEmptyString, RegExp3, URLString, URL2, File, URLSearchParams2, Base64String, Uint8Array2, dateTimeUtcFromString, arbitraryMinimumDateTimestamp = -8640000000000000, arbitraryMaximumDateTimestamp = 8640000000000000, arbitraryMinimumZonedDateTimeTimestamp, arbitraryMaximumZonedDateTimeTimestamp, arbitraryMinimumTimeZoneOffset, arbitraryMaximumTimeZoneOffset, DateTimeUtc, Json2, JsonObject;
11463
11560
  var init_Schema = __esm(() => {
11464
11561
  init_Cause();
11465
11562
  init_Data();
@@ -11514,6 +11611,7 @@ var init_Schema = __esm(() => {
11514
11611
  return `SchemaError(${this.message})`;
11515
11612
  }
11516
11613
  };
11614
+ decodeUnknownOption2 = decodeUnknownOption;
11517
11615
  make10 = make9;
11518
11616
  optionalKey2 = /* @__PURE__ */ lambda((schema) => make10(optionalKey(schema.ast), {
11519
11617
  schema
@@ -13134,6 +13232,7 @@ var init_keybind = __esm(() => {
13134
13232
  "session.dock.tab.todo": keybind("alt+2", "Show activity todo details"),
13135
13233
  "session.first": keybind("ctrl+home,home,alt+home", "Navigate to first message"),
13136
13234
  "session.last": keybind("ctrl+alt+g,end", "Navigate to last message"),
13235
+ "session.scroll.to_bottom": keybind("alt+shift+end", "Scroll to the latest message"),
13137
13236
  "session.message.next": keybind("none", "Navigate to next message"),
13138
13237
  "session.message.previous": keybind("none", "Navigate to previous message"),
13139
13238
  "session.message.user.next": keybind("none", "Navigate to next user message"),
@@ -32439,13 +32538,27 @@ function SessionComposer(props) {
32439
32538
  onCleanup(props.seam.onSubagentViews(() => {}));
32440
32539
  }
32441
32540
  const controller = new ComposerController({
32442
- send: (text) => props.send(text),
32541
+ send: (text, source) => props.send(text, source),
32443
32542
  steer: (text) => props.seam.steer(text),
32543
+ onSteerRejected: ({
32544
+ text
32545
+ }) => {
32546
+ if (disposed || textarea === undefined || textarea.isDestroyed)
32547
+ return;
32548
+ const current = textarea.plainText;
32549
+ if (current !== "" && current !== text)
32550
+ return;
32551
+ if (current !== text) {
32552
+ textarea.setText(text);
32553
+ traceSet("failure-refill", text);
32554
+ }
32555
+ },
32444
32556
  history: props.history,
32445
32557
  chooseDelivery: props.chooseDelivery,
32446
32558
  onPendingChange: props.onPendingChange,
32447
32559
  onQueuePaused: props.onQueuePaused,
32448
32560
  isTurnAborted: props.isTurnAborted,
32561
+ isTurnFailed: props.isTurnFailed,
32449
32562
  disabled: props.disabled,
32450
32563
  onBusyChange: (value) => {
32451
32564
  if (disposed)
@@ -38521,21 +38634,18 @@ function applyActivityPanelConfig(config) {
38521
38634
  } catch {}
38522
38635
  }
38523
38636
  function activityPanelCapSpec(gear, terminalRows) {
38524
- if (gear === undefined)
38525
- return {
38526
- maxLines: dockLineCap(terminalRows)
38527
- };
38528
38637
  if (terminalRows !== undefined && terminalRows <= COMPOSER_COMPACT_TERMINAL_ROWS) {
38529
38638
  return {
38530
38639
  maxLines: dockLineCap(terminalRows)
38531
38640
  };
38532
38641
  }
38533
- if (gear === "all")
38642
+ const effective = gear ?? DEFAULT_ACTIVITY_PANEL_GEAR;
38643
+ if (effective === "all")
38534
38644
  return {
38535
38645
  maxLines: ACTIVITY_PANEL_ALL_LINES
38536
38646
  };
38537
38647
  return {
38538
- maxLines: Math.min(Number(gear), MERGED_DOCK_TOTAL_LINES)
38648
+ maxLines: Math.min(Number(effective), MERGED_DOCK_TOTAL_LINES)
38539
38649
  };
38540
38650
  }
38541
38651
  function dockHeightEase(t) {
@@ -39655,7 +39765,7 @@ function dockLineNode(line, width, ctx, fgFor, accentFg) {
39655
39765
  return _el$0;
39656
39766
  })();
39657
39767
  }
39658
- 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, activityDockTab, setActivityDockTab, DOCK_TAB_ICON, DOCK_TAB_PADDING_STEPS, dockTabDigit = (label) => label.match(/^\d+/)?.[0] ?? "", todoSetSignature = (todos) => todos.map((todo) => todo.content).sort().join("\x01"), todoSetFirstSeen, subagentBatchStartedAt, prevSubagentRunning = 0, TODO_TOOL_NAMES, AUTO_POLE_LIGHT = "#ffffff", AUTO_POLE_DARK = "#000000", DOCK_ACCENT_STEPS, DOCK_ACCENT_HUES, DOCK_ACCENT_MIN_CONTRAST = 4.5, DOCK_ACCENT_FALLBACK, ACTIVITY_FRAME_DEFER_MS = 60, activityFrameLatch, COMPACT_TREE_MAX_LINES = 8;
39768
+ 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, DEFAULT_ACTIVITY_PANEL_GEAR = "5", 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, activityDockTab, setActivityDockTab, DOCK_TAB_ICON, DOCK_TAB_PADDING_STEPS, dockTabDigit = (label) => label.match(/^\d+/)?.[0] ?? "", todoSetSignature = (todos) => todos.map((todo) => todo.content).sort().join("\x01"), todoSetFirstSeen, subagentBatchStartedAt, prevSubagentRunning = 0, TODO_TOOL_NAMES, AUTO_POLE_LIGHT = "#ffffff", AUTO_POLE_DARK = "#000000", DOCK_ACCENT_STEPS, DOCK_ACCENT_HUES, DOCK_ACCENT_MIN_CONTRAST = 4.5, DOCK_ACCENT_FALLBACK, ACTIVITY_FRAME_DEFER_MS = 60, activityFrameLatch, COMPACT_TREE_MAX_LINES = 8;
39659
39769
  var init_widgets_dock = __esm(() => {
39660
39770
  init_index_bun();
39661
39771
  init_index_bun();
@@ -39729,6 +39839,40 @@ var init_widgets_dock = __esm(() => {
39729
39839
  activityFrameLatch = createFrameLatch();
39730
39840
  });
39731
39841
 
39842
+ // ../tui-base/src/routes/session/transcript-scroll-hints.ts
39843
+ function awayFromBottom(pos) {
39844
+ const { scrollTop, viewportHeight, scrollHeight } = pos;
39845
+ if (!Number.isFinite(scrollTop) || !Number.isFinite(viewportHeight) || !Number.isFinite(scrollHeight) || viewportHeight <= 0 || scrollHeight <= 0)
39846
+ return false;
39847
+ return scrollTop + viewportHeight < scrollHeight;
39848
+ }
39849
+ function newMessageCount(rows, baseline) {
39850
+ return Math.max(0, Math.floor(rows) - Math.floor(baseline));
39851
+ }
39852
+ function shouldPulse(previousCount, nextCount) {
39853
+ return nextCount > previousCount;
39854
+ }
39855
+ function newMessageCopyKey(count) {
39856
+ return count === 1 ? "transcript.scroll.newMessage" : "transcript.scroll.newMessages";
39857
+ }
39858
+ function keybindLabel(value) {
39859
+ if (typeof value === "string")
39860
+ return value.split(",")[0]?.trim() ?? "";
39861
+ if (Array.isArray(value))
39862
+ return keybindLabel(value[0]);
39863
+ if (value && typeof value === "object" && "key" in value)
39864
+ return keybindLabel(value.key);
39865
+ return "";
39866
+ }
39867
+ function pulseLevel(elapsedMs) {
39868
+ if (!Number.isFinite(elapsedMs) || elapsedMs <= 0 || elapsedMs >= HINT_PULSE_TOTAL_MS)
39869
+ return 0;
39870
+ const cycleMs = HINT_PULSE_TOTAL_MS / HINT_PULSE_CYCLES;
39871
+ const within = elapsedMs % cycleMs / cycleMs;
39872
+ return within < 0.5 ? within * 2 : (1 - within) * 2;
39873
+ }
39874
+ var HINT_PULSE_TOTAL_MS = 600, HINT_PULSE_CYCLES = 2;
39875
+
39732
39876
  // ../tui-base/src/routes/session/transcript.tsx
39733
39877
  import { BoxRenderable as BoxRenderable3, SyntaxStyle as SyntaxStyle2, TextAttributes as TextAttributes6 } from "@opentui/core";
39734
39878
  function codeBlockForm(isFinal) {
@@ -39885,6 +40029,88 @@ function Transcript(props) {
39885
40029
  row
39886
40030
  });
39887
40031
  const visibleRows = createMemo(() => projection.rows.filter((row) => row.kind !== "tool" && row.kind !== "reasoning" && row.kind !== "subagents"));
40032
+ const [away, setAway] = createSignal(false);
40033
+ const [newRows, setNewRows] = createSignal(0);
40034
+ const [pulseTick, setPulseTick] = createSignal(0);
40035
+ let transcriptScroll;
40036
+ let rowsAtBottom = 0;
40037
+ let lastCount = 0;
40038
+ let wasAway = false;
40039
+ let pulseStartedAt;
40040
+ const syncAway = () => {
40041
+ const scroll = transcriptScroll;
40042
+ if (!scroll || scroll.isDestroyed)
40043
+ return;
40044
+ const awayNow = awayFromBottom({
40045
+ scrollTop: scroll.scrollTop,
40046
+ viewportHeight: scroll.viewport.height,
40047
+ scrollHeight: scroll.scrollHeight
40048
+ });
40049
+ const rows = visibleRows().length;
40050
+ if (!awayNow) {
40051
+ rowsAtBottom = rows;
40052
+ lastCount = 0;
40053
+ wasAway = false;
40054
+ pulseStartedAt = undefined;
40055
+ setNewRows(0);
40056
+ setAway(false);
40057
+ return;
40058
+ }
40059
+ if (!wasAway) {
40060
+ rowsAtBottom = rows;
40061
+ lastCount = 0;
40062
+ }
40063
+ const count = newMessageCount(rows, rowsAtBottom);
40064
+ setAway(true);
40065
+ setNewRows(count);
40066
+ if (shouldPulse(lastCount, count) && motionDecorationsEnabled()) {
40067
+ pulseStartedAt = Date.now();
40068
+ setPulseTick((t) => t + 1);
40069
+ }
40070
+ lastCount = count;
40071
+ wasAway = true;
40072
+ };
40073
+ createEffect(() => {
40074
+ visibleRows().length;
40075
+ syncAway();
40076
+ });
40077
+ const toBottom = () => {
40078
+ if (!transcriptScroll || transcriptScroll.isDestroyed)
40079
+ return;
40080
+ transcriptScroll.scrollTo(Infinity);
40081
+ rowsAtBottom = visibleRows().length;
40082
+ lastCount = 0;
40083
+ wasAway = false;
40084
+ pulseStartedAt = undefined;
40085
+ setNewRows(0);
40086
+ setAway(false);
40087
+ };
40088
+ const pulsing = () => {
40089
+ pulseTick();
40090
+ return motionDecorationsEnabled() && pulseStartedAt !== undefined && Date.now() - pulseStartedAt < HINT_PULSE_TOTAL_MS;
40091
+ };
40092
+ onAnimationTick(() => pulsing() && motionAnimationRunning() ? motionFrameRate() : undefined, () => setPulseTick((t) => t + 1));
40093
+ const keymap = Keymap2.useOptional();
40094
+ const liveToBottomKeys = keymap ? Keymap2.useShortcut("session.scroll.to_bottom") : undefined;
40095
+ const toBottomKeys = () => liveToBottomKeys?.() ?? keybindLabel(defaultValue("session.scroll.to_bottom"));
40096
+ const hintText = () => {
40097
+ const keys = toBottomKeys();
40098
+ const count = newRows();
40099
+ return count > 0 ? t(newMessageCopyKey(count), {
40100
+ count,
40101
+ keys
40102
+ }) : t("transcript.scroll.toLatest", {
40103
+ keys
40104
+ });
40105
+ };
40106
+ const hintColor = () => {
40107
+ const target = color.loading();
40108
+ pulseTick();
40109
+ if (!motionDecorationsEnabled() || pulseStartedAt === undefined)
40110
+ return target;
40111
+ const level = pulseLevel(Date.now() - pulseStartedAt);
40112
+ return level > 0 ? mixSkinColor2(target, skinFaintColor(target, color.background()), level * SKIN_PULSE_DIM) : target;
40113
+ };
39888
40114
  const rowView = (row) => {
39889
40115
  switch (row.kind) {
39890
40116
  case "user":
@@ -39957,10 +40183,12 @@ function Transcript(props) {
39957
40183
  }
39958
40184
  };
39959
40185
  onCleanup(() => {
40186
+ if (transcriptScroll && !transcriptScroll.isDestroyed)
40187
+ transcriptScroll.verticalScrollBar.off("change", syncAway);
39960
40188
  props.scrollRef?.(undefined);
39961
40189
  });
39962
40190
  return (() => {
39963
- var _el$8 = createElement("box"), _el$9 = createElement("box"), _el$0 = createElement("box"), _el$1 = createElement("scrollbox");
40191
+ var _el$8 = createElement("box"), _el$9 = createElement("box"), _el$0 = createElement("box"), _el$1 = createElement("scrollbox"), _el$12 = createElement("box");
39964
40192
  insertNode(_el$8, _el$9);
39965
40193
  setProp(_el$8, "flexDirection", "column");
39966
40194
  setProp(_el$8, "flexGrow", 1);
@@ -39971,12 +40199,15 @@ function Transcript(props) {
39971
40199
  setProp(_el$9, "flexGrow", 1);
39972
40200
  setProp(_el$9, "minHeight", 0);
39973
40201
  insertNode(_el$0, _el$1);
40202
+ insertNode(_el$0, _el$12);
39974
40203
  setProp(_el$0, "flexGrow", 1);
39975
40204
  setProp(_el$0, "minHeight", 0);
39976
- setProp(_el$0, "position", "relative");
39977
- setProp(_el$0, "paddingBottom", 1);
40205
+ setProp(_el$0, "flexDirection", "column");
39978
40206
  use((value) => {
40207
+ transcriptScroll = value;
39979
40208
  props.scrollRef?.(value);
40209
+ value.verticalScrollBar.off("change", syncAway);
40210
+ value.verticalScrollBar.on("change", syncAway);
39980
40211
  }, _el$1);
39981
40212
  setProp(_el$1, "flexGrow", 1);
39982
40213
  setProp(_el$1, "overflow", "hidden");
@@ -39987,12 +40218,12 @@ function Transcript(props) {
39987
40218
  return visibleRows();
39988
40219
  },
39989
40220
  children: (row) => (() => {
39990
- var _el$13 = createElement("box");
39991
- setProp(_el$13, "marginTop", 1);
39992
- setProp(_el$13, "flexShrink", 0);
39993
- insert(_el$13, () => rowView(row));
39994
- effect((_$p) => setProp(_el$13, "id", `seam-row-${row.key}`, _$p));
39995
- return _el$13;
40221
+ var _el$15 = createElement("box");
40222
+ setProp(_el$15, "marginTop", 1);
40223
+ setProp(_el$15, "flexShrink", 0);
40224
+ insert(_el$15, () => rowView(row));
40225
+ effect((_$p) => setProp(_el$15, "id", `seam-row-${row.key}`, _$p));
40226
+ return _el$15;
39996
40227
  })()
39997
40228
  }), null);
39998
40229
  insert(_el$1, createComponent2(Show, {
@@ -40013,15 +40244,15 @@ function Transcript(props) {
40013
40244
  return props.pending?.() ?? [];
40014
40245
  },
40015
40246
  children: (row) => (() => {
40016
- var _el$14 = createElement("box");
40017
- setProp(_el$14, "marginTop", 1);
40018
- setProp(_el$14, "flexShrink", 0);
40019
- insert(_el$14, (() => {
40247
+ var _el$16 = createElement("box");
40248
+ setProp(_el$16, "marginTop", 1);
40249
+ setProp(_el$16, "flexShrink", 0);
40250
+ insert(_el$16, (() => {
40020
40251
  var _c$ = memo2(() => row.kind === "queue");
40021
40252
  return () => _c$() ? (() => {
40022
- var _el$15 = createElement("text");
40023
- setProp(_el$15, "wrapMode", "word");
40024
- insert(_el$15, (() => {
40253
+ var _el$17 = createElement("text");
40254
+ setProp(_el$17, "wrapMode", "word");
40255
+ insert(_el$17, (() => {
40025
40256
  var _c$2 = memo2(() => row.state === "paused");
40026
40257
  return () => _c$2() ? t("transcript.pending.queue.paused", {
40027
40258
  order: row.order ?? 1,
@@ -40033,18 +40264,18 @@ function Transcript(props) {
40033
40264
  })());
40034
40265
  effect((_p$) => {
40035
40266
  var _v$14 = color.pendingQueue(), _v$15 = TextAttributes6.ITALIC;
40036
- _v$14 !== _p$.e && (_p$.e = setProp(_el$15, "fg", _v$14, _p$.e));
40037
- _v$15 !== _p$.t && (_p$.t = setProp(_el$15, "attributes", _v$15, _p$.t));
40267
+ _v$14 !== _p$.e && (_p$.e = setProp(_el$17, "fg", _v$14, _p$.e));
40268
+ _v$15 !== _p$.t && (_p$.t = setProp(_el$17, "attributes", _v$15, _p$.t));
40038
40269
  return _p$;
40039
40270
  }, {
40040
40271
  e: undefined,
40041
40272
  t: undefined
40042
40273
  });
40043
- return _el$15;
40274
+ return _el$17;
40044
40275
  })() : (() => {
40045
- var _el$16 = createElement("text");
40046
- setProp(_el$16, "wrapMode", "word");
40047
- insert(_el$16, (() => {
40276
+ var _el$18 = createElement("text");
40277
+ setProp(_el$18, "wrapMode", "word");
40278
+ insert(_el$18, (() => {
40048
40279
  var _c$3 = memo2(() => row.state === "delivered");
40049
40280
  return () => _c$3() ? t("transcript.pending.steer.delivered", {
40050
40281
  text: row.text
@@ -40052,29 +40283,46 @@ function Transcript(props) {
40052
40283
  text: row.text
40053
40284
  });
40054
40285
  })());
40055
- effect((_$p) => setProp(_el$16, "fg", color.pendingSteer(), _$p));
40056
- return _el$16;
40286
+ effect((_$p) => setProp(_el$18, "fg", color.pendingSteer(), _$p));
40287
+ return _el$18;
40057
40288
  })();
40058
40289
  })());
40059
- effect((_$p) => setProp(_el$14, "id", `pending-row-${row.id}`, _$p));
40060
- return _el$14;
40290
+ effect((_$p) => setProp(_el$16, "id", `pending-row-${row.id}`, _$p));
40291
+ return _el$16;
40061
40292
  })()
40062
40293
  }), null);
40294
+ setProp(_el$12, "id", "transcript-scroll-hint");
40295
+ setProp(_el$12, "flexShrink", 0);
40296
+ setProp(_el$12, "height", 1);
40297
+ setProp(_el$12, "flexDirection", "row");
40298
+ setProp(_el$12, "justifyContent", "flex-end");
40299
+ setProp(_el$12, "onMouseUp", toBottom);
40300
+ insert(_el$12, createComponent2(Show, {
40301
+ get when() {
40302
+ return away();
40303
+ },
40304
+ get children() {
40305
+ var _el$13 = createElement("text");
40306
+ insert(_el$13, hintText);
40307
+ effect((_$p) => setProp(_el$13, "fg", hintColor(), _$p));
40308
+ return _el$13;
40309
+ }
40310
+ }));
40063
40311
  insert(_el$8, createComponent2(Show, {
40064
40312
  get when() {
40065
40313
  return props.status || props.widgets || props.children || props.footer || props.notices;
40066
40314
  },
40067
40315
  get children() {
40068
- var _el$12 = createElement("box");
40069
- setProp(_el$12, "width", "100%");
40070
- setProp(_el$12, "flexShrink", 0);
40071
- setProp(_el$12, "flexDirection", "column");
40072
- insert(_el$12, () => props.status, null);
40073
- insert(_el$12, () => props.widgets, null);
40074
- insert(_el$12, () => props.children, null);
40075
- insert(_el$12, () => props.footer, null);
40076
- insert(_el$12, () => props.notices, null);
40077
- return _el$12;
40316
+ var _el$14 = createElement("box");
40317
+ setProp(_el$14, "width", "100%");
40318
+ setProp(_el$14, "flexShrink", 0);
40319
+ setProp(_el$14, "flexDirection", "column");
40320
+ insert(_el$14, () => props.status, null);
40321
+ insert(_el$14, () => props.widgets, null);
40322
+ insert(_el$14, () => props.children, null);
40323
+ insert(_el$14, () => props.footer, null);
40324
+ insert(_el$14, () => props.notices, null);
40325
+ return _el$14;
40078
40326
  }
40079
40327
  }), null);
40080
40328
  effect((_p$) => {
@@ -40117,55 +40365,55 @@ function AskReplayBlock(props) {
40117
40365
  const askAnswerOf = (entry) => entry.selected.map((label) => splitRecommended(label).label).join(", ") || entry.custom || t("transcript.ask.declined");
40118
40366
  const askDeclinedOf = (entry) => entry.declined || entry.selected.length === 0 && !entry.custom;
40119
40367
  return (() => {
40120
- var _el$17 = createElement("box");
40121
- setProp(_el$17, "flexDirection", "column");
40122
- setProp(_el$17, "gap", 1);
40123
- insert(_el$17, createComponent2(For, {
40368
+ var _el$19 = createElement("box");
40369
+ setProp(_el$19, "flexDirection", "column");
40370
+ setProp(_el$19, "gap", 1);
40371
+ insert(_el$19, createComponent2(For, {
40124
40372
  get each() {
40125
40373
  return props.row.entries;
40126
40374
  },
40127
40375
  children: (entry) => (() => {
40128
- var _el$18 = createElement("box"), _el$19 = createElement("text"), _el$20 = createElement("text");
40129
- insertNode(_el$18, _el$19);
40130
- insertNode(_el$18, _el$20);
40131
- setProp(_el$18, "flexDirection", "column");
40132
- insert(_el$18, createComponent2(Show, {
40376
+ var _el$20 = createElement("box"), _el$21 = createElement("text"), _el$22 = createElement("text");
40377
+ insertNode(_el$20, _el$21);
40378
+ insertNode(_el$20, _el$22);
40379
+ setProp(_el$20, "flexDirection", "column");
40380
+ insert(_el$20, createComponent2(Show, {
40133
40381
  get when() {
40134
40382
  return entry.header;
40135
40383
  },
40136
40384
  children: (header) => (() => {
40137
- var _el$21 = createElement("text");
40138
- insert(_el$21, header);
40139
- effect((_$p) => setProp(_el$21, "fg", reasoning(), _$p));
40140
- return _el$21;
40385
+ var _el$23 = createElement("text");
40386
+ insert(_el$23, header);
40387
+ effect((_$p) => setProp(_el$23, "fg", reasoning(), _$p));
40388
+ return _el$23;
40141
40389
  })()
40142
- }), _el$19);
40143
- insert(_el$19, () => `\u2713 ${entry.question}`);
40144
- insert(_el$18, createComponent2(Show, {
40390
+ }), _el$21);
40391
+ insert(_el$21, () => `\u2713 ${entry.question}`);
40392
+ insert(_el$20, createComponent2(Show, {
40145
40393
  get when() {
40146
40394
  return entry.detail;
40147
40395
  },
40148
40396
  children: (detail) => (() => {
40149
- var _el$22 = createElement("text");
40150
- insert(_el$22, detail);
40151
- effect((_$p) => setProp(_el$22, "fg", reasoning(), _$p));
40152
- return _el$22;
40397
+ var _el$24 = createElement("text");
40398
+ insert(_el$24, detail);
40399
+ effect((_$p) => setProp(_el$24, "fg", reasoning(), _$p));
40400
+ return _el$24;
40153
40401
  })()
40154
- }), _el$20);
40155
- insert(_el$20, () => ` \u2192 ${askAnswerOf(entry)}`);
40402
+ }), _el$22);
40403
+ insert(_el$22, () => ` \u2192 ${askAnswerOf(entry)}`);
40156
40404
  effect((_p$) => {
40157
40405
  var _v$16 = reasoning(), _v$17 = askDeclinedOf(entry) ? reasoning() : answer();
40158
- _v$16 !== _p$.e && (_p$.e = setProp(_el$19, "fg", _v$16, _p$.e));
40159
- _v$17 !== _p$.t && (_p$.t = setProp(_el$20, "fg", _v$17, _p$.t));
40406
+ _v$16 !== _p$.e && (_p$.e = setProp(_el$21, "fg", _v$16, _p$.e));
40407
+ _v$17 !== _p$.t && (_p$.t = setProp(_el$22, "fg", _v$17, _p$.t));
40160
40408
  return _p$;
40161
40409
  }, {
40162
40410
  e: undefined,
40163
40411
  t: undefined
40164
40412
  });
40165
- return _el$18;
40413
+ return _el$20;
40166
40414
  })()
40167
40415
  }));
40168
- return _el$17;
40416
+ return _el$19;
40169
40417
  })();
40170
40418
  }
40171
40419
  var SIDES_RULE, SIDES_FRAME, CODE_RENDER_NODE_CACHE_MAX = 256, codeRenderNodeCache;
@@ -40184,7 +40432,9 @@ var init_transcript = __esm(() => {
40184
40432
  init_seam_rows();
40185
40433
  init_ask_options();
40186
40434
  init_theme3();
40435
+ init_keymap();
40187
40436
  init_i18n();
40437
+ init_keybind();
40188
40438
  init_motion();
40189
40439
  init_semantic();
40190
40440
  init_widgets_dock();
@@ -41572,6 +41822,23 @@ function TranscriptScrollKeys(props) {
41572
41822
  }],
41573
41823
  bindings: ["session.first", "session.last"]
41574
41824
  }));
41825
+ const toBottom = () => {
41826
+ const scroll = props.scroll();
41827
+ if (!scroll || scroll.isDestroyed)
41828
+ return;
41829
+ scroll.scrollTo(Infinity);
41830
+ };
41831
+ Keymap2.createLayer(() => ({
41832
+ capture: "main",
41833
+ enabled: props.enabled(),
41834
+ commands: [{
41835
+ id: "session.scroll.to_bottom",
41836
+ title: "Jump to latest",
41837
+ group: "Session",
41838
+ run: toBottom
41839
+ }],
41840
+ bindings: ["session.scroll.to_bottom"]
41841
+ }));
41575
41842
  return createComponent2(Show, {
41576
41843
  when: false,
41577
41844
  children: null
@@ -44215,6 +44482,91 @@ function persistLang(seam, lang) {
44215
44482
  function seamFailureReason(error) {
44216
44483
  return String(error instanceof Error ? error.message : error).slice(0, 150);
44217
44484
  }
44485
+ function pruneReasonLabel(reason) {
44486
+ const key = PRUNE_REASON_KEYS[reason];
44487
+ return key === undefined ? t("command.prune.reason.other", { reason }) : t(key);
44488
+ }
44489
+ function formatPruneBytes(bytes) {
44490
+ if (!Number.isFinite(bytes) || bytes <= 0)
44491
+ return "0 B";
44492
+ const units = ["B", "KB", "MB", "GB", "TB"];
44493
+ let value = bytes;
44494
+ let unit = 0;
44495
+ while (value >= 1024 && unit < units.length - 1) {
44496
+ value /= 1024;
44497
+ unit++;
44498
+ }
44499
+ const shown = unit === 0 || value >= 10 ? String(Math.round(value)) : value.toFixed(1);
44500
+ return `${shown} ${units[unit]}`;
44501
+ }
44502
+ function pruneBytes(plan, sizeById) {
44503
+ let total = 0;
44504
+ for (const entry of plan.entries) {
44505
+ if (entry.decision !== "prune")
44506
+ continue;
44507
+ const size = sizeById.get(entry.sessionId);
44508
+ if (typeof size === "number" && Number.isFinite(size) && size > 0)
44509
+ total += size;
44510
+ }
44511
+ return total;
44512
+ }
44513
+ function formatPrunePlanRows(plan, sizeById = new Map) {
44514
+ const rows = [
44515
+ t("command.prune.summary", {
44516
+ count: String(plan.counts.prune),
44517
+ skipped: String(plan.counts.skip),
44518
+ bytes: formatPruneBytes(pruneBytes(plan, sizeById)),
44519
+ days: String(plan.retentionDays)
44520
+ })
44521
+ ];
44522
+ const candidates = plan.entries.filter((entry) => entry.decision === "prune" && typeof entry.ageDays === "number" && Number.isFinite(entry.ageDays));
44523
+ if (candidates.length > 0) {
44524
+ const oldest = candidates.reduce((a, b) => b.ageDays > a.ageDays ? b : a);
44525
+ const newest = candidates.reduce((a, b) => b.ageDays < a.ageDays ? b : a);
44526
+ rows.push(t("command.prune.oldest", { id: oldest.sessionId, days: oldest.ageDays.toFixed(1) }));
44527
+ rows.push(t("command.prune.newest", { id: newest.sessionId, days: newest.ageDays.toFixed(1) }));
44528
+ }
44529
+ const reasons = Object.entries(plan.counts.byReason).sort((a, b) => b[1] - a[1]).slice(0, 5);
44530
+ if (reasons.length > 0) {
44531
+ rows.push(t("command.prune.skipSummary", {
44532
+ list: reasons.map(([reason, count]) => `${pruneReasonLabel(reason)}:${count}`).join(", ")
44533
+ }));
44534
+ }
44535
+ return rows;
44536
+ }
44537
+ function formatPurgePrepareRows(result) {
44538
+ const rows = [t("command.prunePurge.count", { count: String(result.candidates.length) })];
44539
+ for (const candidate of result.candidates) {
44540
+ rows.push(t("command.prunePurge.entry", {
44541
+ id: candidate.id,
44542
+ days: candidate.ageDays.toFixed(1)
44543
+ }));
44544
+ }
44545
+ if (result.rejected.length > 0) {
44546
+ rows.push(t("command.prunePurge.rejected", {
44547
+ count: String(result.rejected.length),
44548
+ codes: [...new Set(result.rejected.map((row) => row.code))].join(", ")
44549
+ }));
44550
+ }
44551
+ return rows;
44552
+ }
44553
+ function formatRestoreListRows(list) {
44554
+ const rows = [t("command.pruneRestore.count", { count: String(list.entries.length) })];
44555
+ for (const entry of list.entries) {
44556
+ rows.push(t("command.pruneRestore.entry", {
44557
+ id: entry.id,
44558
+ movedAt: new Date(entry.movedAt).toISOString(),
44559
+ size: entry.size === undefined ? t("command.pruneRestore.unknownSize") : formatPruneBytes(entry.size)
44560
+ }));
44561
+ }
44562
+ if (list.rejected.length > 0) {
44563
+ rows.push(t("command.pruneRestore.rejected", {
44564
+ count: String(list.rejected.length),
44565
+ codes: [...new Set(list.rejected.map((row) => row.code))].join(", ")
44566
+ }));
44567
+ }
44568
+ return rows;
44569
+ }
44218
44570
  function presetNextRow(rows, currentId) {
44219
44571
  if (rows.length <= 1)
44220
44572
  return;
@@ -45432,6 +45784,163 @@ function coreCommands() {
45432
45784
  ctx.say(t("command.cwd.failed", { reason: seamFailureReason(error) }));
45433
45785
  }
45434
45786
  }
45787
+ },
45788
+ {
45789
+ name: "/prune",
45790
+ description: t("command.prune.description"),
45791
+ async run(ctx) {
45792
+ if (!ctx.seam.planPrune || !ctx.seam.applyPrune) {
45793
+ ctx.say(t("command.prune.unavailable"));
45794
+ return;
45795
+ }
45796
+ try {
45797
+ const plan = await ctx.seam.planPrune();
45798
+ const sizeById = new Map;
45799
+ try {
45800
+ for (const row of await ctx.seam.listSessions(1e4)) {
45801
+ if (typeof row.sizeBytes === "number" && Number.isFinite(row.sizeBytes)) {
45802
+ sizeById.set(row.id, row.sizeBytes);
45803
+ }
45804
+ }
45805
+ } catch {}
45806
+ for (const line of formatPrunePlanRows(plan, sizeById))
45807
+ ctx.say(line);
45808
+ if (plan.counts.prune === 0) {
45809
+ ctx.say(t("command.prune.nothingToApply"));
45810
+ return;
45811
+ }
45812
+ if (!ctx.promptText) {
45813
+ ctx.say(t("command.prune.promptUnavailable"));
45814
+ return;
45815
+ }
45816
+ if (typeof plan.fingerprint !== "string" || typeof plan.configFingerprint !== "string") {
45817
+ ctx.say(t("command.prune.stalePlan"));
45818
+ return;
45819
+ }
45820
+ const answer = await ctx.promptText(t("command.prune.confirmTitle"), {
45821
+ placeholder: t("command.prune.confirmPlaceholder")
45822
+ });
45823
+ if (answer?.trim() !== "prune") {
45824
+ ctx.say(t("command.prune.cancelled"));
45825
+ return;
45826
+ }
45827
+ const result = await ctx.seam.applyPrune({
45828
+ fingerprint: plan.fingerprint,
45829
+ configFingerprint: plan.configFingerprint,
45830
+ generatedAt: plan.generatedAt
45831
+ });
45832
+ ctx.say(t("command.prune.applied", {
45833
+ count: String(result.applied.length),
45834
+ failed: String(result.failed.length)
45835
+ }));
45836
+ for (const row of result.failed) {
45837
+ ctx.say(t("command.prune.applyFailed", {
45838
+ id: row.id,
45839
+ code: row.code,
45840
+ message: row.message
45841
+ }));
45842
+ }
45843
+ if (result.markedOrphans > 0) {
45844
+ ctx.say(t("command.prune.orphans", { count: String(result.markedOrphans) }));
45845
+ }
45846
+ } catch (error) {
45847
+ ctx.say(t("command.prune.failed", { reason: seamFailureReason(error) }));
45848
+ }
45849
+ }
45850
+ },
45851
+ {
45852
+ name: "/prune-purge",
45853
+ description: t("command.prunePurge.description"),
45854
+ async run(ctx) {
45855
+ if (!ctx.seam.preparePurge || !ctx.seam.commitPurge) {
45856
+ ctx.say(t("command.prunePurge.unavailable"));
45857
+ return;
45858
+ }
45859
+ try {
45860
+ const prepared = await ctx.seam.preparePurge();
45861
+ for (const line of formatPurgePrepareRows(prepared))
45862
+ ctx.say(line);
45863
+ if (prepared.candidates.length === 0) {
45864
+ ctx.say(t("command.prunePurge.empty"));
45865
+ return;
45866
+ }
45867
+ if (!ctx.promptText) {
45868
+ ctx.say(t("command.prunePurge.promptUnavailable"));
45869
+ return;
45870
+ }
45871
+ const answer = await ctx.promptText(t("command.prunePurge.confirmTitle"), {
45872
+ placeholder: t("command.prunePurge.confirmPlaceholder")
45873
+ });
45874
+ if (answer?.trim() !== "purge") {
45875
+ ctx.say(t("command.prunePurge.cancelled"));
45876
+ return;
45877
+ }
45878
+ const result = await ctx.seam.commitPurge({ token: prepared.token });
45879
+ ctx.say(t("command.prunePurge.done", {
45880
+ count: String(result.purged.length),
45881
+ failed: String(result.failed.length)
45882
+ }));
45883
+ for (const row of result.failed) {
45884
+ ctx.say(t("command.prunePurge.failed", {
45885
+ code: row.code,
45886
+ message: row.message
45887
+ }));
45888
+ }
45889
+ } catch (error) {
45890
+ ctx.say(t("command.prunePurge.failed", {
45891
+ code: "INTERNAL",
45892
+ message: seamFailureReason(error)
45893
+ }));
45894
+ }
45895
+ }
45896
+ },
45897
+ {
45898
+ name: "/prune-restore",
45899
+ description: t("command.pruneRestore.description"),
45900
+ async run(ctx, argText) {
45901
+ if (!ctx.seam.listPruneRestore || !ctx.seam.restorePrune) {
45902
+ ctx.say(t("command.pruneRestore.unavailable"));
45903
+ return;
45904
+ }
45905
+ let id = argText.trim();
45906
+ try {
45907
+ if (id === "") {
45908
+ const list = await ctx.seam.listPruneRestore();
45909
+ for (const line of formatRestoreListRows(list))
45910
+ ctx.say(line);
45911
+ if (list.entries.length === 0) {
45912
+ ctx.say(t("command.pruneRestore.empty"));
45913
+ return;
45914
+ }
45915
+ if (!ctx.pickOne) {
45916
+ ctx.say(t("command.pruneRestore.promptUnavailable"));
45917
+ return;
45918
+ }
45919
+ const picked = await ctx.pickOne(t("command.pruneRestore.pickTitle"), list.entries.map((entry) => ({
45920
+ title: entry.id,
45921
+ value: entry.id,
45922
+ description: new Date(entry.movedAt).toISOString()
45923
+ })), t("command.pruneRestore.pickHeader"));
45924
+ if (picked === undefined) {
45925
+ ctx.say(t("command.pruneRestore.cancelled"));
45926
+ return;
45927
+ }
45928
+ id = picked;
45929
+ }
45930
+ const result = await ctx.seam.restorePrune(id);
45931
+ ctx.say(t("command.pruneRestore.done", { id: result.id }));
45932
+ } catch (error) {
45933
+ const rawCode = error?.code;
45934
+ const code = typeof rawCode === "string" && rawCode !== "" ? rawCode : "INTERNAL";
45935
+ if (code === "CONFLICT" || code === "LIVE_AGENT") {
45936
+ ctx.say(t("command.pruneRestore.conflict", { id }));
45937
+ }
45938
+ ctx.say(t("command.pruneRestore.failed", {
45939
+ code,
45940
+ message: seamFailureReason(error)
45941
+ }));
45942
+ }
45943
+ }
45435
45944
  }
45436
45945
  ];
45437
45946
  }
@@ -45455,7 +45964,7 @@ function dispatchLine(commands, line) {
45455
45964
  function unknownCommandRow(name) {
45456
45965
  return `unknown command: ${name} (try /help)`;
45457
45966
  }
45458
- var MODEL_DEFAULT_EFFORT_PICK = "__model_default__";
45967
+ var MODEL_DEFAULT_EFFORT_PICK = "__model_default__", PRUNE_REASON_KEYS;
45459
45968
  var init_commands = __esm(() => {
45460
45969
  init_i18n();
45461
45970
  init_hotkeys();
@@ -45464,6 +45973,28 @@ var init_commands = __esm(() => {
45464
45973
  init_hints_line();
45465
45974
  init_motion();
45466
45975
  init_export();
45976
+ PRUNE_REASON_KEYS = {
45977
+ "retention-disabled": "command.prune.reason.retentionDisabled",
45978
+ "field-anomaly": "command.prune.reason.fieldAnomaly",
45979
+ current: "command.prune.reason.current",
45980
+ staged: "command.prune.reason.staged",
45981
+ "agent-available": "command.prune.reason.agentAvailable",
45982
+ running: "command.prune.reason.running",
45983
+ "missing-time": "command.prune.reason.missingTime",
45984
+ "future-time": "command.prune.reason.futureTime",
45985
+ "subtree-running": "command.prune.reason.subtreeRunning",
45986
+ unknown: "command.prune.reason.unknown",
45987
+ "no-location": "command.prune.reason.noLocation",
45988
+ "header-mismatch": "command.prune.reason.headerMismatch",
45989
+ "basename-mismatch": "command.prune.reason.basenameMismatch",
45990
+ "not-directory": "command.prune.reason.notDirectory",
45991
+ "escaped-root": "command.prune.reason.escapedRoot",
45992
+ "lock-fresh": "command.prune.reason.lockFresh",
45993
+ "lock-held": "command.prune.reason.lockHeld",
45994
+ "fresh-mtime": "command.prune.reason.freshMtime",
45995
+ "blank-grace": "command.prune.reason.blankGrace",
45996
+ "within-retention": "command.prune.reason.withinRetention"
45997
+ };
45467
45998
  });
45468
45999
 
45469
46000
  // ../tui-base/src/routes/session/slash-complete.ts
@@ -50500,9 +51031,49 @@ function narrowCacheHitMode(value) {
50500
51031
  function readCacheHitMode(config) {
50501
51032
  return narrowCacheHitMode(config?.cacheHitMode);
50502
51033
  }
50503
- var DEFAULT_CACHE_HIT_MODE = "lastMessage";
51034
+ function configNonNegativeInt(value) {
51035
+ if (typeof value === "number" && Number.isFinite(value) && value >= 0)
51036
+ return Math.floor(value);
51037
+ if (typeof value === "string" && /^\d+$/.test(value.trim()))
51038
+ return Number(value.trim());
51039
+ return;
51040
+ }
51041
+ function readMaxRounds(config) {
51042
+ return configNonNegativeInt(config?.maxRounds) ?? DEFAULT_MAX_ROUNDS;
51043
+ }
51044
+ function readRetentionDays(config) {
51045
+ return configNonNegativeInt(config?.retentionDays) ?? DEFAULT_RETENTION_DAYS;
51046
+ }
51047
+ function readSessionScrollbar(...configs) {
51048
+ for (const config of configs) {
51049
+ const decoded = decodeScrollbar(config ?? {});
51050
+ if (decoded._tag === "Some" && decoded.value.session?.scrollbar !== undefined) {
51051
+ return decoded.value.session.scrollbar;
51052
+ }
51053
+ }
51054
+ return;
51055
+ }
51056
+ function resolveSessionScrollbar(...configs) {
51057
+ return readSessionScrollbar(...configs) ?? DEFAULT_SESSION_SCROLLBAR;
51058
+ }
51059
+ var DEFAULT_CACHE_HIT_MODE = "lastMessage", DEFAULT_MAX_ROUNDS = 50, DEFAULT_RETENTION_DAYS = 90, SessionScrollbarConfig, decodeScrollbar, DEFAULT_SESSION_SCROLLBAR = true;
51060
+ var init_config2 = __esm(() => {
51061
+ init_dist();
51062
+ SessionScrollbarConfig = Struct({
51063
+ session: optional2(Struct({ scrollbar: Boolean3 }))
51064
+ });
51065
+ decodeScrollbar = decodeUnknownOption2(SessionScrollbarConfig);
51066
+ });
50504
51067
 
50505
51068
  // ../tui-base/src/routes/session/settings-panel.tsx
51069
+ function unsetNumeric(config, key) {
51070
+ const value = config[key];
51071
+ if (typeof value === "number")
51072
+ return !Number.isFinite(value) || value < 0;
51073
+ if (typeof value === "string")
51074
+ return !/^\d+$/.test(value.trim());
51075
+ return true;
51076
+ }
50506
51077
  function str(value) {
50507
51078
  return typeof value === "string" && value !== "" ? value : undefined;
50508
51079
  }
@@ -50530,6 +51101,7 @@ function buildLocalItems(input) {
50530
51101
  zone: "local",
50531
51102
  editable: writable
50532
51103
  };
51104
+ const storedGear = activityPanelHeightFromConfig(merged.session?.activity_panel_height);
50533
51105
  const items = [{
50534
51106
  ...base,
50535
51107
  id: "theme",
@@ -50619,10 +51191,13 @@ function buildLocalItems(input) {
50619
51191
  ...base,
50620
51192
  id: "activityPanelHeight",
50621
51193
  label: t("settings.row.activityPanelHeight"),
50622
- value: activityPanelHeightFromConfig(merged.session?.activity_panel_height) ?? "default",
51194
+ value: storedGear ?? DEFAULT_ACTIVITY_PANEL_GEAR,
50623
51195
  source: "config.json \xB7 session.activity_panel_height",
50624
51196
  kind: "enum",
50625
51197
  options: ["default", "1", "5", "7", "10", "all"],
51198
+ ...storedGear === undefined ? {
51199
+ note: effectiveDefaultNote(DEFAULT_ACTIVITY_PANEL_GEAR)
51200
+ } : {},
50626
51201
  write: {
50627
51202
  via: "config",
50628
51203
  key: "session.activity_panel_height"
@@ -50631,10 +51206,13 @@ function buildLocalItems(input) {
50631
51206
  ...base,
50632
51207
  id: "retentionDays",
50633
51208
  label: "retentionDays",
50634
- value: num(merged.retentionDays)?.toString() ?? unknownValue(),
51209
+ value: readRetentionDays(merged).toString(),
50635
51210
  source: "config.json \xB7 retentionDays",
50636
51211
  kind: "number",
50637
51212
  min: 0,
51213
+ ...unsetNumeric(merged, "retentionDays") ? {
51214
+ note: effectiveDefaultNote(String(readRetentionDays(undefined)))
51215
+ } : {},
50638
51216
  write: {
50639
51217
  via: "config",
50640
51218
  key: "retentionDays"
@@ -50643,10 +51221,13 @@ function buildLocalItems(input) {
50643
51221
  ...base,
50644
51222
  id: "maxRounds",
50645
51223
  label: "maxRounds",
50646
- value: num(merged.maxRounds)?.toString() ?? unknownValue(),
51224
+ value: readMaxRounds(merged).toString(),
50647
51225
  source: "config.json \xB7 maxRounds (subagent round cap)",
50648
51226
  kind: "number",
50649
51227
  min: 0,
51228
+ ...unsetNumeric(merged, "maxRounds") ? {
51229
+ note: effectiveDefaultNote(String(readMaxRounds(undefined)))
51230
+ } : {},
50650
51231
  write: {
50651
51232
  via: "config",
50652
51233
  key: "maxRounds"
@@ -51258,13 +51839,16 @@ function applySettingsLive(item, applied, hints, themes) {
51258
51839
  function setSettingsBridge(value) {
51259
51840
  setBridgeOpen4(value);
51260
51841
  }
51261
- var unknownValue = () => t("settings.value.unset"), naValue = () => t("settings.value.na"), readonlyNote = () => t("settings.zone.readonlyNote"), HOST_SETTINGS_WHITELIST, HIDDEN_NAMESPACES, LOCAL_SETTING_IDS, bridgeOpen4, setBridgeOpen4, panelOpen5, setPanelOpen5, settingsPanelOpen, settingsBridgeOpen;
51842
+ var unknownValue = () => t("settings.value.unset"), naValue = () => t("settings.value.na"), readonlyNote = () => t("settings.zone.readonlyNote"), effectiveDefaultNote = (value) => t("settings.note.effectiveDefault", {
51843
+ value
51844
+ }), HOST_SETTINGS_WHITELIST, HIDDEN_NAMESPACES, LOCAL_SETTING_IDS, bridgeOpen4, setBridgeOpen4, panelOpen5, setPanelOpen5, settingsPanelOpen, settingsBridgeOpen;
51262
51845
  var init_settings_panel = __esm(() => {
51263
51846
  init_server();
51264
51847
  init_i18n();
51265
51848
  init_string_width();
51266
51849
  init_motion();
51267
51850
  init_hints_line();
51851
+ init_config2();
51268
51852
  init_widgets_dock();
51269
51853
  HOST_SETTINGS_WHITELIST = [{
51270
51854
  id: "subagent.maxActiveSubagents",
@@ -54637,6 +55221,21 @@ function SubagentsViewer(props) {
54637
55221
  return [];
54638
55222
  return seam.subagentTranscript(id);
54639
55223
  });
55224
+ const transcriptStatus = createMemo(() => {
55225
+ tick();
55226
+ const id = browsingId();
55227
+ if (id === undefined || props.seam.subagentTranscriptStatus === undefined)
55228
+ return;
55229
+ return props.seam.subagentTranscriptStatus(id);
55230
+ });
55231
+ const emptyTranscriptKey = () => {
55232
+ const state = transcriptStatus();
55233
+ if (state === "read-failed")
55234
+ return "panel.subagents.transcript.readFailed";
55235
+ if (state === "not-running")
55236
+ return "panel.subagents.transcript.ended";
55237
+ return "panel.subagents.transcript.empty";
55238
+ };
54640
55239
  const window = createMemo(() => transcriptWindow(transcript().length, scrollOffset(), TRANSCRIPT_ROWS));
54641
55240
  function startTicking() {
54642
55241
  if (tickTimer !== undefined)
@@ -54956,7 +55555,7 @@ function SubagentsViewer(props) {
54956
55555
  var _el$10 = createElement("text");
54957
55556
  setProp(_el$10, "fg", muted);
54958
55557
  setProp(_el$10, "wrapMode", "none");
54959
- insert(_el$10, () => t("panel.subagents.transcript.empty"));
55558
+ insert(_el$10, () => t(emptyTranscriptKey()));
54960
55559
  return _el$10;
54961
55560
  })();
54962
55561
  },
@@ -55049,7 +55648,7 @@ var init_subagents_viewer = __esm(() => {
55049
55648
  import { TextAttributes as TextAttributes12 } from "@opentui/core";
55050
55649
  function resolveVersion() {
55051
55650
  try {
55052
- return "0.28.2";
55651
+ return "0.29.1";
55053
55652
  } catch {
55054
55653
  return "dev";
55055
55654
  }
@@ -55223,7 +55822,7 @@ function buildOpentuiRows(ctx) {
55223
55822
  writable: ctx.local
55224
55823
  }).filter((item) => item.id !== "lang").map((row) => row.id === "activityPanelHeight" ? {
55225
55824
  ...row,
55226
- note: t("settings.row.activityPanelHeightNote")
55825
+ note: row.note === undefined ? t("settings.row.activityPanelHeightNote") : `${t("settings.row.activityPanelHeightNote")} \xB7 ${row.note}`
55227
55826
  } : row).map(fromItem);
55228
55827
  return settingsRowsForMode(rows, ctx);
55229
55828
  }
@@ -57641,7 +58240,7 @@ function journalToTranscriptRows(entries, skip = 0) {
57641
58240
  if (callId)
57642
58241
  toolCalls.delete(callId);
57643
58242
  const ok = entry.data.isError !== true && message.isError !== true;
57644
- const brief = JSON.stringify(entry.data.output ?? entry.data).slice(0, 300);
58243
+ const brief = toolResultText(entry.data).slice(0, 300);
57645
58244
  items.push({
57646
58245
  kind: "tool",
57647
58246
  name: known?.name ?? "tool",
@@ -57663,6 +58262,31 @@ function sourceKind2(data) {
57663
58262
  function assistantText(data) {
57664
58263
  return blocksText2(asRecord4(data.message).content);
57665
58264
  }
58265
+ function toolResultText(data) {
58266
+ const message = asRecord4(data.message);
58267
+ const output = asRecord4(data.output);
58268
+ const nestedMessage = asRecord4(output.message);
58269
+ const candidates = [
58270
+ message.content,
58271
+ data.content,
58272
+ data.output,
58273
+ data.text,
58274
+ message.text,
58275
+ output.content,
58276
+ output.text,
58277
+ nestedMessage.content
58278
+ ];
58279
+ for (const candidate of candidates) {
58280
+ if (typeof candidate === "string" && candidate !== "")
58281
+ return candidate;
58282
+ if (Array.isArray(candidate)) {
58283
+ const text = blocksText2(candidate);
58284
+ if (text !== "")
58285
+ return text;
58286
+ }
58287
+ }
58288
+ return "";
58289
+ }
57666
58290
  var init_remote_session_ops = __esm(() => {
57667
58291
  init_remote_follow();
57668
58292
  init_remote_stream();
@@ -58823,6 +59447,8 @@ var init_local_config_faces = __esm(() => {
58823
59447
  "stepsDisplay",
58824
59448
  "stepsCollapse",
58825
59449
  "stepsFolded",
59450
+ "maxRounds",
59451
+ "retentionDays",
58826
59452
  "agentPreset",
58827
59453
  "skinMigration",
58828
59454
  "workspaceTheme",
@@ -59379,6 +60005,261 @@ var init_bridge_settings_route = __esm(() => {
59379
60005
  };
59380
60006
  });
59381
60007
 
60008
+ // src/subagent-policy.ts
60009
+ function nonNegativeInt(value) {
60010
+ if (typeof value === "number" && Number.isFinite(value) && value >= 0)
60011
+ return Math.floor(value);
60012
+ if (typeof value === "string" && /^\d+$/.test(value.trim()))
60013
+ return Number(value.trim());
60014
+ return;
60015
+ }
60016
+ function parseSubagentRoundLimits(value) {
60017
+ if (value === null || typeof value !== "object")
60018
+ return { ...DEFAULT_SUBAGENT_ROUND_LIMITS };
60019
+ const record = value;
60020
+ const maxRounds = nonNegativeInt(record.maxRounds);
60021
+ const maxRoundsGrace = nonNegativeInt(record.maxRoundsGrace);
60022
+ return {
60023
+ maxRounds: maxRounds ?? DEFAULT_SUBAGENT_ROUND_LIMITS.maxRounds,
60024
+ maxRoundsGrace: maxRoundsGrace ?? DEFAULT_SUBAGENT_ROUND_LIMITS.maxRoundsGrace
60025
+ };
60026
+ }
60027
+ function earlyFloor(cap) {
60028
+ return Math.max(10, Math.floor(cap / 3));
60029
+ }
60030
+ function spinDecision(input) {
60031
+ if (input.cap <= 0)
60032
+ return "none";
60033
+ if (input.settled)
60034
+ return "none";
60035
+ if (input.streak < EARLY_STOP_SPIN_STREAK)
60036
+ return "none";
60037
+ if (input.now - input.lastStrikeAt >= SPIN_STRIKE_STALE_MS)
60038
+ return "none";
60039
+ if (!input.wrapupDelivered) {
60040
+ return input.count >= earlyFloor(input.cap) && input.count < input.cap ? "wrapup-early" : "none";
60041
+ }
60042
+ if (input.grace <= 0)
60043
+ return "none";
60044
+ if (input.wrapupDeliveredAt === undefined)
60045
+ return "none";
60046
+ if (input.lastStrikeAt <= input.wrapupDeliveredAt)
60047
+ return "none";
60048
+ if ((input.roundsSinceWrapup ?? 0) < 1)
60049
+ return "none";
60050
+ return "force-stop-early";
60051
+ }
60052
+ function ladderDecision(input) {
60053
+ if (input.cap <= 0)
60054
+ return "none";
60055
+ if (input.settled)
60056
+ return "none";
60057
+ if (!input.wrapupDelivered) {
60058
+ return input.count >= input.cap ? "wrapup" : "none";
60059
+ }
60060
+ if (input.grace <= 0)
60061
+ return "none";
60062
+ return input.count >= input.cap + input.grace ? "force-stop" : "none";
60063
+ }
60064
+ function wrapupMessage(maxRounds, grace) {
60065
+ const base = `Round limit reached (${maxRounds} LLM round-trips, set by the dsh-opentui maxRounds policy). ` + "Do NOT call any more tools. Finish this task NOW: summarize what you have accomplished so far, " + "state clearly what remains undone, and return that summary as your final answer.";
60066
+ return grace > 0 ? `${base} You have ${grace} more round${grace === 1 ? "" : "s"} before this run is force-stopped.` : base;
60067
+ }
60068
+ function wrapupMessageEarly() {
60069
+ return "This run appears to be going in circles \u2014 repeating work without forward progress, " + "as judged by the dsh-opentui attention policy. Do NOT call any more tools. Finish NOW with what you have: " + "summarize what was accomplished, state clearly what remains undone, and return that summary as your final answer. " + "If this judgment looks wrong, say so in the summary and stop.";
60070
+ }
60071
+
60072
+ class SubagentRoundPolicy {
60073
+ #options;
60074
+ #injected = new Set;
60075
+ #hardStopped = new Set;
60076
+ #resolvedCaps = new Map;
60077
+ #injectedLabel = new Map;
60078
+ #injectedRound = new Map;
60079
+ #injectedAt = new Map;
60080
+ #spinState = new Map;
60081
+ #disposed = false;
60082
+ constructor(options) {
60083
+ this.#options = options;
60084
+ }
60085
+ noteSpinVerdict(childId, score, now = Date.now()) {
60086
+ if (this.#disposed || !childId)
60087
+ return;
60088
+ if (typeof score !== "number" || !Number.isFinite(score))
60089
+ return;
60090
+ const previous = this.#spinState.get(childId) ?? { streak: 0, lastStrikeAt: 0 };
60091
+ if (score >= SPIN_HIGH_SEGMENT_AT) {
60092
+ this.#spinState.set(childId, { streak: previous.streak + 1, lastStrikeAt: now });
60093
+ } else {
60094
+ this.#spinState.set(childId, { streak: 0, lastStrikeAt: 0 });
60095
+ }
60096
+ }
60097
+ getSpinState(childId) {
60098
+ return this.#spinState.get(childId) ?? { streak: 0, lastStrikeAt: 0 };
60099
+ }
60100
+ onRoundCount(childId, count, label) {
60101
+ if (this.#disposed || !childId)
60102
+ return;
60103
+ if (this.#hardStopped.has(childId))
60104
+ return;
60105
+ const caps = this.#resolveCaps(childId, label ?? this.#injectedLabel.get(childId));
60106
+ if (caps === undefined)
60107
+ return;
60108
+ const settled = this.#options.isSettled?.(childId) ?? false;
60109
+ const spin = this.#spinState.get(childId) ?? { streak: 0, lastStrikeAt: 0 };
60110
+ const injectedRound = this.#injectedRound.get(childId);
60111
+ const spinAction = spinDecision({
60112
+ streak: spin.streak,
60113
+ lastStrikeAt: spin.lastStrikeAt,
60114
+ now: Date.now(),
60115
+ count,
60116
+ cap: caps.cap,
60117
+ grace: caps.grace,
60118
+ wrapupDelivered: this.#injected.has(childId),
60119
+ wrapupDeliveredAt: this.#injectedAt.get(childId),
60120
+ roundsSinceWrapup: injectedRound !== undefined ? count - injectedRound : undefined,
60121
+ settled
60122
+ });
60123
+ if (spinAction === "force-stop-early") {
60124
+ this.#hardStopped.add(childId);
60125
+ const reportEarlyStop = (stopped) => {
60126
+ if (!stopped)
60127
+ return;
60128
+ try {
60129
+ this.#options.onHardStop?.({ childId, round: count, cap: caps.cap, grace: caps.grace, early: true });
60130
+ } catch {}
60131
+ try {
60132
+ this.#options.onSpinStop?.(childId, count);
60133
+ } catch {}
60134
+ };
60135
+ let stoppedEarly = false;
60136
+ try {
60137
+ stoppedEarly = this.#options.forceStop(childId);
60138
+ } catch {
60139
+ stoppedEarly = false;
60140
+ }
60141
+ if (stoppedEarly instanceof Promise) {
60142
+ stoppedEarly.then(reportEarlyStop, () => {});
60143
+ } else {
60144
+ reportEarlyStop(stoppedEarly);
60145
+ }
60146
+ return;
60147
+ }
60148
+ const action = ladderDecision({
60149
+ count,
60150
+ cap: caps.cap,
60151
+ grace: caps.grace,
60152
+ wrapupDelivered: this.#injected.has(childId),
60153
+ settled
60154
+ });
60155
+ if (action === "none" && spinAction !== "wrapup-early")
60156
+ return;
60157
+ if (action === "wrapup" || spinAction === "wrapup-early") {
60158
+ if (this.#injected.has(childId))
60159
+ return;
60160
+ const rememberedLabel = label ?? this.#injectedLabel.get(childId);
60161
+ const early = spinAction === "wrapup-early";
60162
+ queueMicrotask(() => {
60163
+ if (this.#disposed || this.#injected.has(childId))
60164
+ return;
60165
+ if (this.#options.isSettled?.(childId) === true)
60166
+ return;
60167
+ let delivered = false;
60168
+ try {
60169
+ delivered = this.#options.wrapup(childId, early ? wrapupMessageEarly() : wrapupMessage(caps.cap, caps.grace), rememberedLabel);
60170
+ } catch {
60171
+ delivered = false;
60172
+ }
60173
+ const latch = (ok) => {
60174
+ if (this.#disposed || this.#injected.has(childId) || this.#hardStopped.has(childId))
60175
+ return;
60176
+ if (!ok)
60177
+ return;
60178
+ this.#injected.add(childId);
60179
+ if (rememberedLabel !== undefined)
60180
+ this.#injectedLabel.set(childId, rememberedLabel);
60181
+ this.#injectedRound.set(childId, count);
60182
+ this.#injectedAt.set(childId, Date.now());
60183
+ try {
60184
+ this.#options.onWrapUp?.(childId, count);
60185
+ } catch {}
60186
+ };
60187
+ if (delivered instanceof Promise) {
60188
+ delivered.then(latch, () => {});
60189
+ return;
60190
+ }
60191
+ latch(delivered);
60192
+ });
60193
+ return;
60194
+ }
60195
+ this.#hardStopped.add(childId);
60196
+ const reportStop = (stopped) => {
60197
+ if (!stopped)
60198
+ return;
60199
+ try {
60200
+ this.#options.onHardStop?.({ childId, round: count, cap: caps.cap, grace: caps.grace });
60201
+ } catch {}
60202
+ try {
60203
+ this.#options.onForceStop?.(childId, count);
60204
+ } catch {}
60205
+ };
60206
+ let stopped = false;
60207
+ try {
60208
+ stopped = this.#options.forceStop(childId);
60209
+ } catch {
60210
+ stopped = false;
60211
+ }
60212
+ if (stopped instanceof Promise) {
60213
+ stopped.then(reportStop, () => {});
60214
+ } else {
60215
+ reportStop(stopped);
60216
+ }
60217
+ }
60218
+ #resolveCaps(childId, label) {
60219
+ const cached = this.#resolvedCaps.get(childId);
60220
+ if (cached !== undefined)
60221
+ return cached;
60222
+ const limits = this.#options.limits();
60223
+ const globalCap = limits.maxRounds;
60224
+ if (globalCap <= 0)
60225
+ return;
60226
+ let cap = globalCap;
60227
+ if (label !== undefined && this.#options.resolveAgentCap !== undefined) {
60228
+ try {
60229
+ const perAgent = this.#options.resolveAgentCap(label);
60230
+ if (perAgent !== undefined && perAgent > 0)
60231
+ cap = perAgent;
60232
+ } catch {}
60233
+ }
60234
+ const caps = { cap, grace: limits.maxRoundsGrace };
60235
+ this.#resolvedCaps.set(childId, caps);
60236
+ return caps;
60237
+ }
60238
+ forgetChild(childId) {
60239
+ this.#injected.delete(childId);
60240
+ this.#hardStopped.delete(childId);
60241
+ this.#resolvedCaps.delete(childId);
60242
+ this.#injectedLabel.delete(childId);
60243
+ this.#injectedRound.delete(childId);
60244
+ this.#injectedAt.delete(childId);
60245
+ this.#spinState.delete(childId);
60246
+ }
60247
+ dispose() {
60248
+ this.#disposed = true;
60249
+ this.#injected.clear();
60250
+ this.#hardStopped.clear();
60251
+ this.#resolvedCaps.clear();
60252
+ this.#injectedLabel.clear();
60253
+ this.#injectedRound.clear();
60254
+ this.#injectedAt.clear();
60255
+ this.#spinState.clear();
60256
+ }
60257
+ }
60258
+ var DEFAULT_MAX_ROUNDS2 = 50, DEFAULT_SUBAGENT_ROUND_LIMITS, SPIN_HIGH_SEGMENT_AT = 0.75, SPIN_STRIKE_STALE_MS = 90000, EARLY_STOP_SPIN_STREAK = 2;
60259
+ var init_subagent_policy = __esm(() => {
60260
+ DEFAULT_SUBAGENT_ROUND_LIMITS = { maxRounds: DEFAULT_MAX_ROUNDS2, maxRoundsGrace: 0 };
60261
+ });
60262
+
59382
60263
  // src/client/bridge-session-seam.ts
59383
60264
  import { existsSync as existsSync8, readFileSync as readFileSync9, readdirSync as readdirSync4 } from "fs";
59384
60265
  import { join as join10 } from "path";
@@ -59515,6 +60396,177 @@ function accountClientMeta() {
59515
60396
  timezoneOffsetSeconds: -new Date().getTimezoneOffset() * 60
59516
60397
  };
59517
60398
  }
60399
+ function projectBridgePrunePlan(value) {
60400
+ const record = asRecord12(value);
60401
+ if (!Array.isArray(record.entries)) {
60402
+ throw new BridgeProtocolError("INTERNAL", "session.prune.plan returned no entries array");
60403
+ }
60404
+ const entries = [];
60405
+ for (const raw of record.entries) {
60406
+ const row = asRecord12(raw);
60407
+ if (typeof row.sessionId !== "string" || row.decision !== "prune" && row.decision !== "skip")
60408
+ continue;
60409
+ const entry = { sessionId: row.sessionId, decision: row.decision };
60410
+ if (typeof row.reason === "string")
60411
+ entry.reason = row.reason;
60412
+ if (typeof row.location === "string")
60413
+ entry.location = row.location;
60414
+ if (typeof row.ageDays === "number" && Number.isFinite(row.ageDays))
60415
+ entry.ageDays = row.ageDays;
60416
+ entries.push(entry);
60417
+ }
60418
+ if (typeof record.generatedAt !== "number" || !Number.isFinite(record.generatedAt)) {
60419
+ throw new BridgeProtocolError("INTERNAL", "session.prune.plan returned no valid generatedAt");
60420
+ }
60421
+ if (typeof record.retentionDays !== "number" || !Number.isFinite(record.retentionDays)) {
60422
+ throw new BridgeProtocolError("INTERNAL", "session.prune.plan returned no valid retentionDays");
60423
+ }
60424
+ const countsRaw = record.counts;
60425
+ if (countsRaw === null || typeof countsRaw !== "object" || Array.isArray(countsRaw) || typeof countsRaw.prune !== "number" || typeof countsRaw.skip !== "number" || countsRaw.byReason === null || typeof countsRaw.byReason !== "object" || Array.isArray(countsRaw.byReason)) {
60426
+ throw new BridgeProtocolError("INTERNAL", "session.prune.plan returned no valid counts");
60427
+ }
60428
+ const byReason = {};
60429
+ let prune = 0;
60430
+ let skip = 0;
60431
+ for (const entry of entries) {
60432
+ if (entry.decision === "prune") {
60433
+ prune += 1;
60434
+ } else {
60435
+ skip += 1;
60436
+ const reason = entry.reason ?? "unknown";
60437
+ byReason[reason] = (byReason[reason] ?? 0) + 1;
60438
+ }
60439
+ }
60440
+ return {
60441
+ generatedAt: record.generatedAt,
60442
+ retentionDays: record.retentionDays,
60443
+ entries,
60444
+ counts: { prune, skip, byReason },
60445
+ ...typeof record.fingerprint === "string" ? { fingerprint: record.fingerprint } : {},
60446
+ ...typeof record.configFingerprint === "string" ? { configFingerprint: record.configFingerprint } : {}
60447
+ };
60448
+ }
60449
+ function projectBridgePruneApply(value) {
60450
+ const record = asRecord12(value);
60451
+ if (typeof record.opId !== "string" || record.opId === "") {
60452
+ throw new BridgeProtocolError("INTERNAL", "session.prune.apply returned no valid opId");
60453
+ }
60454
+ if (!Array.isArray(record.applied) || !Array.isArray(record.failed)) {
60455
+ throw new BridgeProtocolError("INTERNAL", "session.prune.apply returned no applied/failed arrays");
60456
+ }
60457
+ const applied = [];
60458
+ for (const raw of record.applied) {
60459
+ const row = asRecord12(raw);
60460
+ if (typeof row.id === "string" && row.id !== "")
60461
+ applied.push({ id: row.id });
60462
+ }
60463
+ const failed = [];
60464
+ for (const raw of record.failed) {
60465
+ const row = asRecord12(raw);
60466
+ if (typeof row.id !== "string" || typeof row.code !== "string" || typeof row.message !== "string")
60467
+ continue;
60468
+ failed.push({ id: row.id, code: row.code, message: row.message.slice(0, 300) });
60469
+ }
60470
+ return {
60471
+ opId: record.opId,
60472
+ applied,
60473
+ failed,
60474
+ markedOrphans: Array.isArray(record.markedOrphans) ? record.markedOrphans.length : 0
60475
+ };
60476
+ }
60477
+ function projectBridgePurgePrepare(value) {
60478
+ const record = asRecord12(value);
60479
+ if (typeof record.opId !== "string" || typeof record.token !== "string" || record.token === "") {
60480
+ throw new BridgeProtocolError("INTERNAL", "session.prune.purge prepare returned no opId/token");
60481
+ }
60482
+ if (!Array.isArray(record.candidates) || !Array.isArray(record.rejected)) {
60483
+ throw new BridgeProtocolError("INTERNAL", "session.prune.purge prepare returned no candidates/rejected arrays");
60484
+ }
60485
+ const candidates = [];
60486
+ for (const raw of record.candidates) {
60487
+ const row = asRecord12(raw);
60488
+ if (typeof row.id !== "string" || row.id === "")
60489
+ continue;
60490
+ if (typeof row.ageDays !== "number" || !Number.isFinite(row.ageDays))
60491
+ continue;
60492
+ if (typeof row.appliedAt !== "number" || !Number.isFinite(row.appliedAt))
60493
+ continue;
60494
+ candidates.push({ id: row.id, ageDays: row.ageDays, appliedAt: row.appliedAt });
60495
+ }
60496
+ const rejected = [];
60497
+ for (const raw of record.rejected) {
60498
+ const row = asRecord12(raw);
60499
+ if (typeof row.code !== "string" || typeof row.message !== "string")
60500
+ continue;
60501
+ rejected.push({
60502
+ ...typeof row.id === "string" ? { id: row.id } : {},
60503
+ code: row.code,
60504
+ message: row.message.slice(0, 300)
60505
+ });
60506
+ }
60507
+ return { opId: record.opId, token: record.token, candidates, rejected };
60508
+ }
60509
+ function projectBridgePurgeCommit(value) {
60510
+ const record = asRecord12(value);
60511
+ if (typeof record.opId !== "string" || record.opId === "") {
60512
+ throw new BridgeProtocolError("INTERNAL", "session.prune.purge commit returned no valid opId");
60513
+ }
60514
+ if (!Array.isArray(record.purged) || !Array.isArray(record.failed)) {
60515
+ throw new BridgeProtocolError("INTERNAL", "session.prune.purge commit returned no purged/failed arrays");
60516
+ }
60517
+ const purged = [];
60518
+ for (const raw of record.purged) {
60519
+ const row = asRecord12(raw);
60520
+ if (typeof row.id === "string" && row.id !== "")
60521
+ purged.push({ id: row.id });
60522
+ }
60523
+ const failed = [];
60524
+ for (const raw of record.failed) {
60525
+ const row = asRecord12(raw);
60526
+ if (typeof row.code !== "string" || typeof row.message !== "string")
60527
+ continue;
60528
+ failed.push({
60529
+ ...typeof row.id === "string" ? { id: row.id } : {},
60530
+ code: row.code,
60531
+ message: row.message.slice(0, 300)
60532
+ });
60533
+ }
60534
+ return { opId: record.opId, purged, failed };
60535
+ }
60536
+ function projectBridgePruneRestoreList(value) {
60537
+ const record = asRecord12(value);
60538
+ if (!Array.isArray(record.entries) || !Array.isArray(record.rejected)) {
60539
+ throw new BridgeProtocolError("INTERNAL", "session.prune.restore list returned no entries/rejected arrays");
60540
+ }
60541
+ const entries = [];
60542
+ for (const raw of record.entries) {
60543
+ const row = asRecord12(raw);
60544
+ if (typeof row.id !== "string" || row.id === "")
60545
+ continue;
60546
+ if (typeof row.movedAt !== "number" || !Number.isFinite(row.movedAt))
60547
+ continue;
60548
+ entries.push({
60549
+ id: row.id,
60550
+ movedAt: row.movedAt,
60551
+ ...typeof row.size === "number" && Number.isFinite(row.size) && row.size > 0 ? { size: row.size } : {}
60552
+ });
60553
+ }
60554
+ const rejected = [];
60555
+ for (const raw of record.rejected) {
60556
+ const row = asRecord12(raw);
60557
+ if (typeof row.code !== "string" || typeof row.message !== "string")
60558
+ continue;
60559
+ rejected.push({ code: row.code, message: row.message.slice(0, 300) });
60560
+ }
60561
+ return { entries, rejected };
60562
+ }
60563
+ function projectBridgePruneRestore(value) {
60564
+ const record = asRecord12(value);
60565
+ if (typeof record.id !== "string" || record.id === "" || record.restored !== true || typeof record.opId !== "string" || record.opId === "") {
60566
+ throw new BridgeProtocolError("INTERNAL", "session.prune.restore returned no valid id/restored/opId");
60567
+ }
60568
+ return { id: record.id, restored: true, opId: record.opId };
60569
+ }
59518
60570
  function unsupported(capability) {
59519
60571
  throw new BridgeProtocolError("UNSUPPORTED", `${capability} is not backed by the in-process bridge`, { capability });
59520
60572
  }
@@ -60116,6 +61168,52 @@ function bridgeReplayRowsToChildLog(rows) {
60116
61168
  return row.text;
60117
61169
  }).filter((line) => line !== "");
60118
61170
  }
61171
+ function childTranscriptBytes(line) {
61172
+ return childTextEncoder.encode(line).length;
61173
+ }
61174
+ function childTranscriptTruncate(line) {
61175
+ const bytes = childTextEncoder.encode(line);
61176
+ if (bytes.length <= CHILD_TRANSCRIPT_LINE_BUDGET)
61177
+ return line;
61178
+ const cutBudget = CHILD_TRANSCRIPT_LINE_BUDGET - CHILD_TRANSCRIPT_TRUNCATION_MARKER_BYTES;
61179
+ for (let end = cutBudget;end > 0; end -= 1) {
61180
+ try {
61181
+ return childStrictTextDecoder.decode(bytes.slice(0, end)) + CHILD_TRANSCRIPT_TRUNCATION_MARKER;
61182
+ } catch {}
61183
+ }
61184
+ return CHILD_TRANSCRIPT_TRUNCATION_MARKER;
61185
+ }
61186
+ function capChildLog(lines) {
61187
+ const out = lines.map((line) => childTranscriptTruncate(line));
61188
+ let bytes = out.reduce((total, line) => total + childTranscriptBytes(line) + 1, 0);
61189
+ while (out.length > CHILD_TRANSCRIPT_MAX_LINES || out.length > 0 && bytes > CHILD_TRANSCRIPT_MAX_BYTES) {
61190
+ const dropped = out.shift();
61191
+ bytes -= childTranscriptBytes(dropped) + 1;
61192
+ }
61193
+ return out;
61194
+ }
61195
+ function childTranscriptRowToLine(row) {
61196
+ const r = asRecord12(row);
61197
+ if (r.kind !== "assistant" && r.kind !== "tool")
61198
+ return "";
61199
+ const text = typeof r.text === "string" ? r.text : "";
61200
+ const output = typeof r.output === "string" ? r.output : "";
61201
+ if (r.kind === "tool")
61202
+ return output !== "" ? `\u25B6 ${text}
61203
+ \u23BF ${output}` : `\u25B6 ${text}`;
61204
+ return text;
61205
+ }
61206
+ function splitChildLogLines(lines) {
61207
+ const out = [];
61208
+ for (const line of lines) {
61209
+ for (const part of line.split(`
61210
+ `)) {
61211
+ if (part !== "")
61212
+ out.push(part);
61213
+ }
61214
+ }
61215
+ return out;
61216
+ }
60119
61217
  function bridgeChildStopReason(rows) {
60120
61218
  for (let i = rows.length - 1;i >= 0; i -= 1) {
60121
61219
  const row = rows[i];
@@ -60625,10 +61723,14 @@ class BridgeSessionSeam {
60625
61723
  #subagentLiveStarts = new Set;
60626
61724
  #subagentListeners = new Set;
60627
61725
  #subagentProgress = new Map;
61726
+ #roundPolicy;
60628
61727
  #subagentSessionId;
60629
61728
  #subagentJournalLoaded = new Set;
60630
61729
  #subagentJournalMeta = new Map;
60631
61730
  #subagentTranscripts = new Map;
61731
+ #subagentTranscriptRuns = new Map;
61732
+ #subagentTranscriptSettled = new Set;
61733
+ #subagentTranscriptReadFailed = new Set;
60632
61734
  #sweepSettledRuns = new Map;
60633
61735
  #subagentSettleSnapshots = new Map;
60634
61736
  #interruptInFlight = new Map;
@@ -60760,7 +61862,7 @@ class BridgeSessionSeam {
60760
61862
  this.#currentSessionId = undefined;
60761
61863
  this.#resetModelRoute();
60762
61864
  this.#pendingOpen = { mode: "new" };
60763
- this.#settleSuspendedTurn();
61865
+ this.#settleSuspendedTurn({ code: "SESSION_CLOSED", reason: "session changed" });
60764
61866
  this.#deadInFlight = undefined;
60765
61867
  this.#inFlightPartial = "";
60766
61868
  }
@@ -60904,7 +62006,7 @@ class BridgeSessionSeam {
60904
62006
  source: "journal"
60905
62007
  }
60906
62008
  });
60907
- this.#settleSuspendedTurn();
62009
+ this.#settleSuspendedTurn({ terminalEmitted: true });
60908
62010
  } else {
60909
62011
  emit({
60910
62012
  type: "bridge.turn.interrupted",
@@ -60918,7 +62020,7 @@ class BridgeSessionSeam {
60918
62020
  source: "local"
60919
62021
  }
60920
62022
  });
60921
- this.#settleSuspendedTurn();
62023
+ this.#settleSuspendedTurn({ terminalEmitted: true });
60922
62024
  }
60923
62025
  }
60924
62026
  await new Promise((resolve) => setTimeout(resolve, 0));
@@ -61266,6 +62368,17 @@ class BridgeSessionSeam {
61266
62368
  subagentTranscript(id) {
61267
62369
  return [...this.#subagentTranscripts.get(id) ?? []];
61268
62370
  }
62371
+ subagentTranscriptStatus(id) {
62372
+ const lines = this.#subagentTranscripts.get(id);
62373
+ if (lines !== undefined && lines.length > 0)
62374
+ return "ready";
62375
+ if (this.#subagentTranscriptReadFailed.has(id))
62376
+ return "read-failed";
62377
+ const view = this.#subagentViews.get(id);
62378
+ if (view === undefined || view.status !== "running")
62379
+ return "not-running";
62380
+ return "pending";
62381
+ }
61269
62382
  steerChild(id, text) {
61270
62383
  const view = this.#subagentViews.get(id);
61271
62384
  if (view === undefined || view.status !== "running")
@@ -61388,6 +62501,7 @@ class BridgeSessionSeam {
61388
62501
  const view = this.#subagentViews.get(childId);
61389
62502
  if (view === undefined || view.status === "running")
61390
62503
  continue;
62504
+ this.#roundPolicy?.forgetChild(childId);
61391
62505
  if (view.elapsedSec === undefined || view.endedAt === undefined)
61392
62506
  continue;
61393
62507
  const runKey = `${childId}@${startedAt ?? ""}`;
@@ -61468,13 +62582,17 @@ class BridgeSessionSeam {
61468
62582
  try {
61469
62583
  const value = asRecord12(await this.#transport.request("journal.replay", { sessionId: childId }));
61470
62584
  const rows = value.rows;
61471
- if (!Array.isArray(rows))
62585
+ if (!Array.isArray(rows)) {
62586
+ this.#subagentTranscriptReadFailed.add(childId);
61472
62587
  return;
62588
+ }
61473
62589
  const cleanRows = rows.filter((row) => row !== null && typeof row === "object" && !Array.isArray(row));
61474
62590
  const meta = bridgeChildJournalMeta(cleanRows);
61475
62591
  if (this.#subagentSessionId !== sessionAtStart || this.#disposed)
61476
62592
  return;
61477
- this.#subagentTranscripts.set(childId, bridgeReplayRowsToChildLog(cleanRows));
62593
+ this.#subagentTranscripts.set(childId, capChildLog(splitChildLogLines(bridgeReplayRowsToChildLog(cleanRows))));
62594
+ this.#subagentTranscriptReadFailed.delete(childId);
62595
+ this.#subagentTranscriptRuns.delete(childId);
61478
62596
  this.#subagentJournalMeta.set(key, meta);
61479
62597
  const existing = this.#subagentViews.get(childId);
61480
62598
  if (existing === undefined || bridgeChildJournalKey(existing) !== key)
@@ -61486,7 +62604,9 @@ class BridgeSessionSeam {
61486
62604
  ...meta.model !== undefined ? { model: meta.model } : {}
61487
62605
  });
61488
62606
  this.#emitSubagentViews();
61489
- } catch {}
62607
+ } catch {
62608
+ this.#subagentTranscriptReadFailed.add(childId);
62609
+ }
61490
62610
  }
61491
62611
  #syncSubagentMeta(emit = true) {
61492
62612
  let changed = false;
@@ -61587,10 +62707,21 @@ class BridgeSessionSeam {
61587
62707
  if (frame.type === "agent.spawn") {
61588
62708
  const runId = typeof payload.runId === "string" ? payload.runId : "";
61589
62709
  const childId = typeof payload.childId === "string" ? payload.childId : "";
62710
+ if (childId !== "") {
62711
+ this.#subagentTranscriptRuns.delete(childId);
62712
+ this.#subagentTranscriptSettled.delete(childId);
62713
+ this.#subagentTranscriptReadFailed.delete(childId);
62714
+ }
62715
+ if (this.#subagentSessionId === undefined && frameSession !== "") {
62716
+ this.#subagentSessionId = frameSession;
62717
+ }
61590
62718
  changed = runId === `${BRIDGE_CATALOG_RUN_PREFIX}${childId}` ? this.#foldWithFrozenSettle(BRIDGE_SUBAGENT_CATALOG, payload, now, true) : this.#foldWithFrozenSettle(BRIDGE_AGENT_START, payload, now, true);
61591
62719
  } else if (frame.type === "agent.settle") {
61592
62720
  const childId = typeof payload.childId === "string" ? payload.childId : "";
61593
62721
  const existing = childId !== "" ? this.#subagentViews.get(childId) : undefined;
62722
+ const lockedChild = childId !== "" ? childId : this.#subagentRunSeq.get(bridgeAgentRunKey(typeof payload.runId === "string" ? payload.runId : "", typeof payload.seq === "number" ? payload.seq : -1));
62723
+ if (lockedChild !== undefined)
62724
+ this.#subagentTranscriptSettled.add(lockedChild);
61594
62725
  if (existing !== undefined && existing.status === "running") {
61595
62726
  if (this.#subagentSessionId === undefined && frameSession !== "") {
61596
62727
  this.#subagentSessionId = frameSession;
@@ -61604,6 +62735,41 @@ class BridgeSessionSeam {
61604
62735
  this.#emitSubagentViews();
61605
62736
  }
61606
62737
  }
62738
+ #ensureRoundPolicy() {
62739
+ if (this.#roundPolicy === undefined) {
62740
+ this.#roundPolicy = new SubagentRoundPolicy({
62741
+ limits: () => parseSubagentRoundLimits(this.configLoad()),
62742
+ isSettled: (childId) => {
62743
+ const view = this.#subagentViews.get(childId);
62744
+ return view === undefined || view.status !== "running";
62745
+ },
62746
+ wrapup: (childId, message) => this.steerChild(childId, message),
62747
+ forceStop: (childId) => this.interruptChild(childId).then(() => true, () => false),
62748
+ onWrapUp: (childId, round) => this.#markRoundPolicy(childId, "injectedRound", round),
62749
+ onForceStop: (childId, round) => this.#markRoundPolicy(childId, "hardStopRound", round),
62750
+ onSpinStop: (childId, round) => this.#markRoundPolicy(childId, "spinStopRound", round)
62751
+ });
62752
+ }
62753
+ return this.#roundPolicy;
62754
+ }
62755
+ #resetRoundPolicy() {
62756
+ this.#roundPolicy?.dispose();
62757
+ this.#roundPolicy = undefined;
62758
+ }
62759
+ #markRoundPolicy(childId, field, round) {
62760
+ const view = this.#subagentViews.get(childId);
62761
+ if (view === undefined || view[field] !== undefined)
62762
+ return;
62763
+ const next = { ...view };
62764
+ if (field === "injectedRound")
62765
+ next.injectedRound = round;
62766
+ else if (field === "hardStopRound")
62767
+ next.hardStopRound = round;
62768
+ else
62769
+ next.spinStopRound = round;
62770
+ this.#subagentViews.set(childId, next);
62771
+ this.#emitSubagentViews();
62772
+ }
61607
62773
  #foldAgentProgress(frame) {
61608
62774
  const payload = asRecord12(frame.payload);
61609
62775
  const frameSession = typeof payload.sessionId === "string" ? payload.sessionId : "";
@@ -61619,14 +62785,56 @@ class BridgeSessionSeam {
61619
62785
  const lastLine = typeof payload.lastLine === "string" ? payload.lastLine : undefined;
61620
62786
  const elapsedSec = typeof payload.elapsedSec === "number" && Number.isFinite(payload.elapsedSec) ? payload.elapsedSec : undefined;
61621
62787
  const prev = this.#subagentProgress.get(childId);
61622
- this.#subagentProgress.set(childId, {
62788
+ const merged = {
61623
62789
  rounds: Math.max(prev?.rounds ?? 0, rounds),
61624
62790
  ...lastLine !== undefined ? { lastLine } : prev?.lastLine !== undefined ? { lastLine: prev.lastLine } : {},
61625
62791
  ...elapsedSec !== undefined ? { elapsedSec } : prev?.elapsedSec !== undefined ? { elapsedSec: prev.elapsedSec } : {}
61626
- });
62792
+ };
62793
+ this.#subagentProgress.set(childId, merged);
62794
+ if (merged.rounds > (prev?.rounds ?? 0)) {
62795
+ this.#ensureRoundPolicy().onRoundCount(childId, merged.rounds, view.label);
62796
+ }
61627
62797
  this.#syncSubagentMeta(false);
61628
62798
  this.#emitSubagentViews();
61629
62799
  }
62800
+ #foldAgentTranscript(frame) {
62801
+ const payload = asRecord12(frame.payload);
62802
+ const frameSession = typeof payload.sessionId === "string" ? payload.sessionId : "";
62803
+ const childId = typeof payload.childId === "string" ? payload.childId : "";
62804
+ const turnId = typeof payload.turnId === "string" ? payload.turnId : "";
62805
+ const runId = typeof payload.runId === "string" && payload.runId !== "" ? payload.runId : turnId;
62806
+ const seq = typeof payload.seq === "number" && Number.isFinite(payload.seq) ? payload.seq : -1;
62807
+ const rows = payload.rows;
62808
+ if (childId === "" || turnId === "" || seq < 0 || !Array.isArray(rows))
62809
+ return;
62810
+ if (this.#subagentTranscriptSettled.has(childId))
62811
+ return;
62812
+ const view = this.#subagentViews.get(childId);
62813
+ if (view === undefined || view.status !== "running")
62814
+ return;
62815
+ if (this.#subagentSessionId === undefined) {
62816
+ if (frameSession !== "")
62817
+ this.#subagentSessionId = frameSession;
62818
+ } else if (frameSession !== "" && frameSession !== this.#subagentSessionId)
62819
+ return;
62820
+ let run = this.#subagentTranscriptRuns.get(childId);
62821
+ if (run === undefined || run.runId !== runId) {
62822
+ run = { runId, seen: new Set };
62823
+ this.#subagentTranscriptRuns.set(childId, run);
62824
+ }
62825
+ if (run.seen.has(seq))
62826
+ return;
62827
+ run.seen.add(seq);
62828
+ const lines = [...this.#subagentTranscripts.get(childId) ?? []];
62829
+ for (const row of rows) {
62830
+ const line = childTranscriptRowToLine(row);
62831
+ if (line !== "")
62832
+ lines.push(line);
62833
+ }
62834
+ this.#subagentTranscripts.set(childId, capChildLog(splitChildLogLines(lines)));
62835
+ this.#subagentTranscriptReadFailed.delete(childId);
62836
+ this.#emitSubagentViews();
62837
+ }
61630
62838
  #foldAgentReplayRows(rows, sessionId) {
61631
62839
  let rosterReset = false;
61632
62840
  if (sessionId !== this.#subagentSessionId) {
@@ -61634,9 +62842,13 @@ class BridgeSessionSeam {
61634
62842
  this.#subagentRunSeq.clear();
61635
62843
  this.#subagentLiveStarts.clear();
61636
62844
  this.#subagentProgress.clear();
62845
+ this.#resetRoundPolicy();
61637
62846
  this.#subagentJournalLoaded.clear();
61638
62847
  this.#subagentJournalMeta.clear();
61639
62848
  this.#subagentTranscripts.clear();
62849
+ this.#subagentTranscriptRuns.clear();
62850
+ this.#subagentTranscriptSettled.clear();
62851
+ this.#subagentTranscriptReadFailed.clear();
61640
62852
  this.#sweepSettledRuns.clear();
61641
62853
  this.#subagentSettleSnapshots.clear();
61642
62854
  this.#interruptInFlight.clear();
@@ -61684,6 +62896,44 @@ class BridgeSessionSeam {
61684
62896
  const value = await this.#transport.request("session.list");
61685
62897
  return projectBridgeSessionList(asRecord12(value).items, limit);
61686
62898
  }
62899
+ async planPrune(params) {
62900
+ const staged = this.stagedSessionId();
62901
+ const ids = new Set(params?.stagedIds ?? []);
62902
+ if (staged !== undefined && staged !== "")
62903
+ ids.add(staged);
62904
+ const wireParams = ids.size > 0 ? { ...params ?? {}, stagedIds: [...ids] } : { ...params ?? {} };
62905
+ const value = await this.#transport.request("session.prune.plan", wireParams);
62906
+ return projectBridgePrunePlan(value);
62907
+ }
62908
+ async applyPrune(params) {
62909
+ const staged = this.stagedSessionId();
62910
+ const ids = new Set(params.stagedIds ?? []);
62911
+ if (staged !== undefined && staged !== "")
62912
+ ids.add(staged);
62913
+ const value = await this.#transport.request("session.prune.apply", {
62914
+ fingerprint: params.fingerprint,
62915
+ configFingerprint: params.configFingerprint,
62916
+ generatedAt: params.generatedAt,
62917
+ ...ids.size > 0 ? { stagedIds: [...ids] } : {}
62918
+ });
62919
+ return projectBridgePruneApply(value);
62920
+ }
62921
+ async preparePurge() {
62922
+ const value = await this.#transport.request("session.prune.purge", { phase: "prepare" });
62923
+ return projectBridgePurgePrepare(value);
62924
+ }
62925
+ async commitPurge(params) {
62926
+ const value = await this.#transport.request("session.prune.purge", { phase: "commit", token: params.token });
62927
+ return projectBridgePurgeCommit(value);
62928
+ }
62929
+ async listPruneRestore() {
62930
+ const value = await this.#transport.request("session.prune.restore", { phase: "list" });
62931
+ return projectBridgePruneRestoreList(value);
62932
+ }
62933
+ async restorePrune(id) {
62934
+ const value = await this.#transport.request("session.prune.restore", { phase: "restore", id });
62935
+ return projectBridgePruneRestore(value);
62936
+ }
61687
62937
  async cwd() {
61688
62938
  const sessionId = this.currentSessionId();
61689
62939
  if (sessionId === undefined || sessionId === "")
@@ -61836,9 +63086,23 @@ class BridgeSessionSeam {
61836
63086
  const fallback = await this.#defaultModelRoute();
61837
63087
  return fallback !== undefined ? { providerID: fallback.providerID, modelID: fallback.modelID } : undefined;
61838
63088
  }
61839
- #settleSuspendedTurn() {
63089
+ #settleSuspendedTurn(options) {
61840
63090
  const done = this.#turnDone;
61841
63091
  const endedTurnId = this.#inFlightTurnId;
63092
+ if (!(options?.terminalEmitted ?? false) && done !== undefined) {
63093
+ this.#emitEvent({
63094
+ type: "bridge.turn.interrupted",
63095
+ details: {
63096
+ sessionID: this.#currentSessionId ?? "",
63097
+ turnId: endedTurnId,
63098
+ partial: this.#inFlightPartial,
63099
+ reason: options?.reason ?? "turn interrupted before a terminal event",
63100
+ code: options?.code ?? "INTERRUPTED",
63101
+ seq: null,
63102
+ source: "local"
63103
+ }
63104
+ });
63105
+ }
61842
63106
  this.#turnDone = undefined;
61843
63107
  this.#activeCallbacks = undefined;
61844
63108
  this.#inFlightTurnId = undefined;
@@ -61935,8 +63199,13 @@ class BridgeSessionSeam {
61935
63199
  this.#subagentRunSeq.clear();
61936
63200
  this.#subagentLiveStarts.clear();
61937
63201
  this.#subagentProgress.clear();
63202
+ this.#resetRoundPolicy();
61938
63203
  this.#subagentJournalLoaded.clear();
61939
63204
  this.#subagentJournalMeta.clear();
63205
+ this.#subagentTranscripts.clear();
63206
+ this.#subagentTranscriptRuns.clear();
63207
+ this.#subagentTranscriptSettled.clear();
63208
+ this.#subagentTranscriptReadFailed.clear();
61940
63209
  this.#sweepSettledRuns.clear();
61941
63210
  this.#subagentSettleSnapshots.clear();
61942
63211
  this.#interruptInFlight.clear();
@@ -62006,8 +63275,29 @@ class BridgeSessionSeam {
62006
63275
  async renameSession(_title) {
62007
63276
  return unsupported("renameSession");
62008
63277
  }
62009
- steer(_text) {
62010
- this.#degrade("steer", "no session.steer frame; steer is a no-op");
63278
+ async steer(text) {
63279
+ if (!this.hasBridgeCapability("session.steer")) {
63280
+ return { accepted: false, reason: "UNSUPPORTED" };
63281
+ }
63282
+ let reply;
63283
+ try {
63284
+ reply = await this.#transport.request("session.steer", { text });
63285
+ } catch (err) {
63286
+ if (err instanceof BridgeProtocolError && STEER_REJECTION_CODES.has(err.code)) {
63287
+ const detail = asRecord12(err.detail);
63288
+ return {
63289
+ accepted: false,
63290
+ reason: err.code,
63291
+ ...typeof detail.turnId === "string" ? { turnId: detail.turnId } : {}
63292
+ };
63293
+ }
63294
+ throw err;
63295
+ }
63296
+ const result = asRecord12(reply);
63297
+ if (result.accepted !== true || typeof result.turnId !== "string") {
63298
+ throw new BridgeProtocolError("INTERNAL", "session.steer reply has no accepted:true turnId");
63299
+ }
63300
+ return { accepted: true, turnId: result.turnId };
62011
63301
  }
62012
63302
  registerAskProvider(onAsk) {
62013
63303
  this.#askProvider = onAsk;
@@ -62331,6 +63621,10 @@ class BridgeSessionSeam {
62331
63621
  this.#foldAgentProgress(frame);
62332
63622
  return;
62333
63623
  }
63624
+ if (frame.type === "agent.transcript") {
63625
+ this.#foldAgentTranscript(frame);
63626
+ return;
63627
+ }
62334
63628
  if (frame.type === "bridge.dead") {
62335
63629
  const cause = asDeadCause(frame.payload);
62336
63630
  if (this.#inFlightGeneration !== 0 && this.#inFlightTurnId !== undefined && this.#inFlightTurnId !== "") {
@@ -62431,7 +63725,7 @@ class BridgeSessionSeam {
62431
63725
  }
62432
63726
  }
62433
63727
  }
62434
- var CONFIRM_REQUIRED = (method) => new BridgeProtocolError("CONFIRM_REQUIRED", `${method}: write requires a confirmed TUI modal token`), BridgeProtocolError, ACCOUNT_STATUSES, ACCOUNT_PHASES, ROUTE_ROW_TYPES, BRIDGE_AGENT_START = "tool-workflow/agent-start", BRIDGE_AGENT_END = "tool-workflow/agent-end", BRIDGE_SUBAGENT_CATALOG = "subagent/catalog", BRIDGE_SUBAGENT_SETTLED = "subagent-settled", BRIDGE_CATALOG_RUN_PREFIX = "catalog:", CONFIRM_POLL_INITIAL_MS = 250, CONFIRM_POLL_MAX_MS = 1000, CONFIRM_TIMEOUT_MS = 45000, fmtTokens = (n) => n >= 1000 ? `${(n / 1000).toFixed(1)}k` : `${n}`;
63728
+ var CONFIRM_REQUIRED = (method) => new BridgeProtocolError("CONFIRM_REQUIRED", `${method}: write requires a confirmed TUI modal token`), BridgeProtocolError, ACCOUNT_STATUSES, ACCOUNT_PHASES, STEER_REJECTION_CODES, ROUTE_ROW_TYPES, 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:", CHILD_TRANSCRIPT_MAX_LINES = 500, CHILD_TRANSCRIPT_MAX_BYTES, childTextEncoder, childStrictTextDecoder, CHILD_TRANSCRIPT_LINE_BUDGET, CHILD_TRANSCRIPT_TRUNCATION_MARKER = "\u2026", CHILD_TRANSCRIPT_TRUNCATION_MARKER_BYTES, CONFIRM_POLL_INITIAL_MS = 250, CONFIRM_POLL_MAX_MS = 1000, CONFIRM_TIMEOUT_MS = 45000, fmtTokens = (n) => n >= 1000 ? `${(n / 1000).toFixed(1)}k` : `${n}`;
62435
63729
  var init_bridge_session_seam = __esm(() => {
62436
63730
  init_remote_session_ops();
62437
63731
  init_journal_projection();
@@ -62443,6 +63737,7 @@ var init_bridge_session_seam = __esm(() => {
62443
63737
  init_profile_constants();
62444
63738
  init_bridge_goals();
62445
63739
  init_bridge_settings_route();
63740
+ init_subagent_policy();
62446
63741
  BridgeProtocolError = class BridgeProtocolError extends Error {
62447
63742
  code;
62448
63743
  detail;
@@ -62465,7 +63760,20 @@ var init_bridge_session_seam = __esm(() => {
62465
63760
  "expired",
62466
63761
  "failed"
62467
63762
  ]);
63763
+ STEER_REJECTION_CODES = new Set([
63764
+ "STEER_IDLE",
63765
+ "STEER_ENDED",
63766
+ "STEER_ABORTING",
63767
+ "SESSION_NOT_OPEN",
63768
+ "BAD_PARAMS",
63769
+ "UNSUPPORTED"
63770
+ ]);
62468
63771
  ROUTE_ROW_TYPES = new Set(["model/selection", "request/header", "request/context"]);
63772
+ CHILD_TRANSCRIPT_MAX_BYTES = 64 * 1024;
63773
+ childTextEncoder = new TextEncoder;
63774
+ childStrictTextDecoder = new TextDecoder("utf-8", { fatal: true });
63775
+ CHILD_TRANSCRIPT_LINE_BUDGET = CHILD_TRANSCRIPT_MAX_BYTES - 1;
63776
+ CHILD_TRANSCRIPT_TRUNCATION_MARKER_BYTES = childTextEncoder.encode(CHILD_TRANSCRIPT_TRUNCATION_MARKER).length;
62469
63777
  });
62470
63778
 
62471
63779
  // scripts/lib/bridge-failfast-text.mjs
@@ -62763,7 +64071,9 @@ function V2SessionPageBody(props) {
62763
64071
  "bridge.recovery.locked",
62764
64072
  "bridge.recovery.failed"
62765
64073
  ]);
64074
+ const turnTracker = new TurnOutcomeTracker;
62766
64075
  onCleanup(seam.onSessionEvent?.((event) => {
64076
+ turnTracker.onEvent(event);
62767
64077
  if (!recoveryEvents.has(event?.type))
62768
64078
  return;
62769
64079
  recovery.handleEvent(event);
@@ -62828,16 +64138,31 @@ function V2SessionPageBody(props) {
62828
64138
  showNotice(pendingAgentsHomeNotice);
62829
64139
  pendingAgentsHomeNotice = undefined;
62830
64140
  }
64141
+ let pruneNoticeDisposed = false;
64142
+ onCleanup(() => {
64143
+ pruneNoticeDisposed = true;
64144
+ });
64145
+ if (seam.planPrune) {
64146
+ seam.planPrune().then((plan) => {
64147
+ if (pruneNoticeDisposed || plan.counts.prune <= 0)
64148
+ return;
64149
+ showNotice(t("notice.prune.available", { n: String(plan.counts.prune) }));
64150
+ }).catch(() => {});
64151
+ }
62831
64152
  const timer = setInterval(() => setNow(new Date), 1000);
62832
64153
  onCleanup(() => clearInterval(timer));
62833
64154
  });
62834
64155
  const [lastRequest, setLastRequest] = createSignal();
62835
64156
  const [composerPending, setComposerPending] = createSignal([]);
62836
64157
  let turnAborted = false;
62837
- const send = (text) => {
64158
+ const send = (text, source) => {
62838
64159
  turnAborted = false;
64160
+ turnTracker.beginTurn();
62839
64161
  setTurnBusy(true);
62840
64162
  setLastRequest(text);
64163
+ if (source !== "queue") {
64164
+ transcriptScroll?.scrollTo(Infinity);
64165
+ }
62841
64166
  const done = projection.send(text);
62842
64167
  done.finally(() => setTurnBusy(false));
62843
64168
  return done;
@@ -63308,6 +64633,9 @@ function V2SessionPageBody(props) {
63308
64633
  createComponent2(Transcript, {
63309
64634
  seam,
63310
64635
  projection,
64636
+ get scrollbar() {
64637
+ return resolveSessionScrollbar(seam.workspaceConfig?.(), seam.configRaw?.(), seam.configLoad?.());
64638
+ },
63311
64639
  focused: paneFocus.transcriptFocused,
63312
64640
  scrollRef: (value) => transcriptScroll = value,
63313
64641
  widgets: createComponent2(WidgetsDock, {
@@ -63341,7 +64669,8 @@ function V2SessionPageBody(props) {
63341
64669
  chooseDelivery: (text) => openDeliveryChoice(dialog, text),
63342
64670
  onPendingChange: (rows) => setComposerPending(rows),
63343
64671
  onQueuePaused: (info) => showNotice(`\u961F\u5217\u5DF2\u4FDD\u7559 ${info.remaining} \u6761:\u672C\u56DE\u5408${info.reason === "failed" ? "\u5931\u8D25" : "\u5DF2\u4E2D\u6B62"},\u4E0B\u56DE\u5408\u7ED3\u675F\u540E\u7EE7\u7EED\u53D1\u9001`, 8000),
63344
- isTurnAborted: () => turnAborted,
64672
+ isTurnAborted: () => turnAborted || turnTracker.isAborted(),
64673
+ isTurnFailed: () => turnTracker.isFailed(),
63345
64674
  slashKeyFilter: slash.slashKeyFilter,
63346
64675
  slashSync: (buffer) => slash.controller.sync(buffer, slash.commands),
63347
64676
  interceptSubmit: slash.interceptSubmit,
@@ -63643,6 +64972,7 @@ var init_v2_entry = __esm(() => {
63643
64972
  init_subagents_viewer();
63644
64973
  init_settings_modal();
63645
64974
  init_btw_overlay();
64975
+ init_config2();
63646
64976
  init_dialog_select();
63647
64977
  init_dialog_prompt();
63648
64978
  init_dialog_confirm();
@@ -63977,5 +65307,5 @@ if (import.meta.main) {
63977
65307
  main();
63978
65308
  }
63979
65309
 
63980
- //# debugId=DAD2522A36CE287C64756E2164756E21
65310
+ //# debugId=39BBC5E19A7B4E5264756E2164756E21
63981
65311
  //# sourceMappingURL=index.js.map