blun-king-cli 9.1.647 → 9.1.648

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/blun.mjs CHANGED
@@ -15643,6 +15643,7 @@ function peekTable(key, table, meta, type) {
15643
15643
  ];
15644
15644
  }
15645
15645
  function parse$7(toml, { maxDepth = 1e3, integersAsBigInt } = {}) {
15646
+ toml = toml.replace(/^\uFEFF/u, '');
15646
15647
  let res = {};
15647
15648
  let meta = {};
15648
15649
  let tbl = res;
@@ -21193,7 +21194,7 @@ var init_types$20 = __esmMin((() => {}));
21193
21194
  var FLAG_DEFINITIONS;
21194
21195
  var InputControl, controls, CHANNEL_QUEUE_DEADLINE_MS, QueueDeadlineWatchdog, StoppedInputScopes, SEARCH_LIMITS, SearchStop, active, inside, sessionSearchRequests, ActiveInputDelivery;
21195
21196
  var init_registry$4 = __esmMin((() => {
21196
- FLAG_DEFINITIONS = [
21197
+ FLAG_DEFINITIONS = [{ id: "original_history", title: "Original history", description: "Read a captured conversation independently of model context.", env: "BLUN_EXPERIMENTAL_ORIGINAL_HISTORY", default: false, surface: "both" },
21197
21198
  {
21198
21199
  id: "local_auth",
21199
21200
  title: "Local authentication",
@@ -265669,7 +265670,75 @@ function greetingHistory(history, anchor) {
265669
265670
  while (recent.length > 0 && recent[0].role !== "user") recent.shift();
265670
265671
  return [...recent, ...history.slice(start)];
265671
265672
  }
265672
- function blunToolsForOrigin(tools, origin) {
265673
+ const blunUserReplyAuthorities = new WeakMap();
265674
+ class UserReplyToolAuthority {
265675
+ #agent;
265676
+ #signal;
265677
+ #turnId;
265678
+ #goalId;
265679
+ #granted = false;
265680
+ #closed = false;
265681
+
265682
+ constructor(agent, signal) {
265683
+ if (!agent || typeof signal?.throwIfAborted !== 'function') throw new TypeError('INVALID_REPLY_TOOL_OWNER');
265684
+ this.#agent = agent;
265685
+ this.#signal = signal;
265686
+ }
265687
+
265688
+ #owns(flow, turnId) {
265689
+ return !this.#closed && !this.#signal.aborted && flow.agent === this.#agent &&
265690
+ Number.isSafeInteger(turnId) && turnId >= 0 && flow.currentId === turnId &&
265691
+ flow.activeTurn?.controller?.signal === this.#signal;
265692
+ }
265693
+
265694
+ #checkGoal(flow) {
265695
+ const goal = flow.agent.goal.getGoal().goal;
265696
+ const id = typeof goal?.goalId === 'string' ? goal.goalId : undefined;
265697
+ // A final answer may follow goal completion in the same turn. A different
265698
+ // goal must receive fresh user authority; the first created goal may adopt
265699
+ // authority already granted to its creating user turn.
265700
+ if (id !== undefined) {
265701
+ if (this.#goalId !== undefined && id !== this.#goalId) this.#granted = false;
265702
+ this.#goalId = id;
265703
+ }
265704
+ }
265705
+
265706
+ enter(flow, turnId, origin) {
265707
+ if (!this.#owns(flow, turnId)) return false;
265708
+ this.#checkGoal(flow);
265709
+ const firstEntry = this.#turnId !== turnId;
265710
+ this.#turnId = turnId;
265711
+ if (firstEntry && origin?.kind === 'user') this.#granted = true;
265712
+ return true;
265713
+ }
265714
+
265715
+ permits(flow, turnId, snapshot) {
265716
+ if (!this.#owns(flow, turnId) || this.#turnId !== turnId) return false;
265717
+ this.#checkGoal(flow);
265718
+ if (this.#granted) return true;
265719
+ const through = snapshot?.throughSequence;
265720
+ if (!Number.isSafeInteger(through) || through < 0) return false;
265721
+ return flow.matchingSteers(turnId).some(steer => Number.isSafeInteger(steer.sequence) &&
265722
+ steer.sequence >= 0 && steer.sequence <= through && steer.origin?.kind === 'user' &&
265723
+ (steer.targetTurnId === undefined || steer.targetTurnId === turnId));
265724
+ }
265725
+
265726
+ consumed(flow, turnId, steer) {
265727
+ if (!this.#owns(flow, turnId) || this.#turnId !== turnId) return;
265728
+ this.#checkGoal(flow);
265729
+ if (steer.origin?.kind === 'user' && (steer.targetTurnId === undefined || steer.targetTurnId === turnId)) {
265730
+ this.#granted = true;
265731
+ }
265732
+ }
265733
+
265734
+ dispose() {
265735
+ this.#closed = true;
265736
+ this.#granted = false;
265737
+ this.#agent = this.#signal = undefined;
265738
+ }
265739
+ }
265740
+ function blunToolsForOrigin(tools, origin, userReplyAllowed = false) {
265741
+ if (userReplyAllowed === true) return tools;
265673
265742
  if (origin.kind !== "system_trigger" && origin.kind !== "injection") return tools;
265674
265743
  return tools.filter((tool) => !BLUN_TELEGRAM_OUTBOUND_TOOL_RE.test(tool.name));
265675
265744
  }
@@ -266333,6 +266402,7 @@ cancel(turnId, reason) {
266333
266402
  continue;
266334
266403
  }
266335
266404
  this.agent.context.appendUserMessage(steer.input, steer.origin);
266405
+ blunUserReplyAuthorities.get(this)?.consumed(this, turnId, steer);
266336
266406
  this.agent.cron?.observeSteerConsumed(steer.origin, turnId);
266337
266407
  incorporated.push(steer);
266338
266408
  flushed = true;
@@ -266400,6 +266470,9 @@ cancel(turnId, reason) {
266400
266470
  * launch signal, so a superseding turn is never clobbered).
266401
266471
  */
266402
266472
  async turnWorker(firstTurnId, input, origin, signal, reportExecutionEnd = false) {
266473
+ const replyAuthority = new UserReplyToolAuthority(this.agent, signal);
266474
+ blunUserReplyAuthorities.get(this)?.dispose();
266475
+ blunUserReplyAuthorities.set(this, replyAuthority);
266403
266476
  let terminal;
266404
266477
  const finish = (result) => {
266405
266478
  terminal = result.event;
@@ -266425,6 +266498,8 @@ cancel(turnId, reason) {
266425
266498
  this.agent.cron?.observeWorkerFailed(origin);
266426
266499
  throw error;
266427
266500
  } finally {
266501
+ replyAuthority.dispose();
266502
+ if (blunUserReplyAuthorities.get(this) === replyAuthority) blunUserReplyAuthorities.delete(this);
266428
266503
  if (ownsActiveTurn()) this.activeTurn = null;
266429
266504
  if (reportExecutionEnd && terminal !== void 0) this.agent.emitEvent({
266430
266505
  ...terminal,
@@ -266745,6 +266820,7 @@ cancel(turnId, reason) {
266745
266820
  const personalMemoryRecall = await this.agent.injection.injectPersonalMemoryForTurn(turnId, input, origin, signal);
266746
266821
  await this.agent.injection.injectGoal();
266747
266822
  this.setActiveSteerAcceptance(turnId, true);
266823
+ blunUserReplyAuthorities.get(this)?.enter(this, turnId, origin);
266748
266824
  const turnNeedsThinking = blunTurnNeedsTools(blunThinkingIntentInput(input), origin);
266749
266825
  let toolInput = input;
266750
266826
  let taskToolsNeeded = turnNeedsThinking || blunTurnHasAttachment(input);
@@ -266767,7 +266843,7 @@ cancel(turnId, reason) {
266767
266843
  const selectedTools = [];
266768
266844
  this.refreshSelectedTools = (snapshot) => {
266769
266845
  if (snapshot.messages.length > 0) toolInput = snapshot.messages.flatMap((message) => message.content);
266770
- const eligibleTools = blunToolsForOrigin(this.agent.injection.filterPersonalMemoryToolsForTurn(turnId, input, origin, turnTools()), origin);
266846
+ const eligibleTools = blunToolsForOrigin(this.agent.injection.filterPersonalMemoryToolsForTurn(turnId, input, origin, turnTools()), origin, blunUserReplyAuthorities.get(this)?.permits(this, turnId, snapshot) === true);
266771
266847
  const intent = blunThinkingIntentInput(toolInput);
266772
266848
  taskToolsNeeded ||= blunTurnNeedsTools(intent, origin) || blunTurnHasAttachment(toolInput);
266773
266849
  const required = (0, import_turn_tool_performance_policy.mediaToolNamesForTurnText)(blunExtractText(toolInput));
@@ -270907,37 +270983,49 @@ var init_agent = __esmMin((() => {
270907
270983
  const selectedAlias = this.config.model;
270908
270984
  const modelProvider = this.modelProvider;
270909
270985
  if (modelProvider === void 0) throw new BlunError(ErrorCodes.MODEL_NOT_CONFIGURED, "Provider not set");
270986
+ const turnId = this.turn.currentId;
270910
270987
  return new FallbackLLM(resolveModelFallbackCandidates(selectedAlias, modelProvider, (alias) => this.createKosongLLM(alias, thinkingEffort), this.allowModelFallback && !PINNED_MODEL_ALIASES.has(selectedAlias)), (alias) => {
270911
270988
  this.setActiveResponderModel(alias);
270912
270989
  }, async (_candidate, params, rebuildMessages) => {
270913
- const steers = this.turn.snapshotPendingSteers();
270914
- const requestTools = this.turn.refreshRequestTools(steers) ?? params.tools;
270915
- params = {
270916
- ...params,
270917
- tools: requestTools,
270918
- messages: await rebuildMessages()
270919
- };
270920
- let systemPrompt = this.effectiveSystemPrompt;
270921
- const compacted = await this.fullCompaction.beforeStep(params.boundarySignal ?? params.signal, {
270922
- messages: params.messages,
270923
- additionalMessages: steers.messages,
270924
- rebuildMessages,
270925
- systemPrompt,
270926
- rebuildSystemPrompt: () => systemPrompt = this.effectiveSystemPrompt,
270927
- tools: params.tools
270928
- });
270929
- const tools = params.tools.some((tool) => tool.name === "CompactConversation") && !this.fullCompaction.proactiveCompactionStatus({
270930
- messages: compacted ? await rebuildMessages() : params.messages,
270931
- additionalMessages: steers.messages,
270932
- systemPrompt,
270933
- tools: params.tools
270934
- }).eligible ? params.tools.filter((tool) => tool.name !== "CompactConversation") : params.tools;
270935
- this.turn.commitPendingSteers(steers);
270936
- return {
270937
- ...params,
270938
- systemPrompt,
270939
- tools
270940
- };
270990
+ for (;;) {
270991
+ params.signal.throwIfAborted();
270992
+ if (this.turn.currentId !== turnId) throw new Error("REQUEST_BOUNDARY_TURN_CHANGED");
270993
+ const steers = this.turn.snapshotPendingSteers(turnId);
270994
+ const requestTools = this.turn.refreshRequestTools(steers) ?? params.tools;
270995
+ params = {
270996
+ ...params,
270997
+ tools: requestTools,
270998
+ messages: await rebuildMessages()
270999
+ };
271000
+ let systemPrompt = this.effectiveSystemPrompt;
271001
+ const compacted = await this.fullCompaction.beforeStep(params.boundarySignal ?? params.signal, {
271002
+ messages: params.messages,
271003
+ additionalMessages: steers.messages,
271004
+ rebuildMessages,
271005
+ systemPrompt,
271006
+ rebuildSystemPrompt: () => systemPrompt = this.effectiveSystemPrompt,
271007
+ tools: params.tools
271008
+ });
271009
+ const messages = compacted ? await rebuildMessages() : params.messages;
271010
+ params.signal.throwIfAborted();
271011
+ if (this.turn.currentId !== turnId) throw new Error("REQUEST_BOUNDARY_TURN_CHANGED");
271012
+ if (this.turn.snapshotPendingSteers(turnId).throughSequence !== steers.throughSequence) {
271013
+ await new Promise(resolve => setImmediate(resolve));
271014
+ continue;
271015
+ }
271016
+ const tools = params.tools.some((tool) => tool.name === "CompactConversation") && !this.fullCompaction.proactiveCompactionStatus({
271017
+ messages,
271018
+ additionalMessages: steers.messages,
271019
+ systemPrompt,
271020
+ tools: params.tools
271021
+ }).eligible ? params.tools.filter((tool) => tool.name !== "CompactConversation") : params.tools;
271022
+ this.turn.commitPendingSteers(steers, turnId);
271023
+ return {
271024
+ ...params,
271025
+ systemPrompt,
271026
+ tools
271027
+ };
271028
+ }
270941
271029
  }, (candidate, _params, error) => {
270942
271030
  this.fullCompaction.observeContextOverflow(error, candidate.alias);
270943
271031
  });
@@ -301851,7 +301939,7 @@ async function readMcpJson(filePath, options = {}) {
301851
301939
  if (text.trim().length === 0) return {};
301852
301940
  let data;
301853
301941
  try {
301854
- data = JSON.parse(text);
301942
+ data = JSON.parse(text.replace(/^\uFEFF/u, ''));
301855
301943
  } catch (error) {
301856
301944
  throw new BlunError(ErrorCodes.CONFIG_INVALID, `Invalid JSON in ${filePath}: ${describeError$1(error)}`, { cause: error });
301857
301945
  }
@@ -304411,7 +304499,7 @@ async function readInstalled(blunHomeDir) {
304411
304499
  throw error;
304412
304500
  }
304413
304501
  try {
304414
- const parsed = JSON.parse(text);
304502
+ const parsed = JSON.parse(text.replace(/^\uFEFF/u, ''));
304415
304503
  if (typeof parsed !== "object" || parsed === null || !Array.isArray(parsed.plugins)) throw new Error("installed.json is not a valid InstalledFile object");
304416
304504
  return parsed;
304417
304505
  } catch (error) {
@@ -381804,6 +381892,77 @@ var init_scrollback_buffer = __esmMin((() => {
381804
381892
  init_i18n();
381805
381893
  init_scrollback_buffer_copy();
381806
381894
  ScrollbackBuffer = class {
381895
+ originalView;
381896
+ originalEpoch = 0;
381897
+ originalTransition = false;
381898
+
381899
+ beginOriginalView(source, owner) {
381900
+ if (this.originalTransition) throw new Error('ORIGINAL_HISTORY_TRANSITION');
381901
+ if (!source || !Number.isSafeInteger(source.totalLines) || source.totalLines < 0 ||
381902
+ typeof source.readRange !== 'function' || !owner || typeof owner.throwIfAborted !== 'function') {
381903
+ throw new Error('INVALID_ORIGINAL_HISTORY_SOURCE');
381904
+ }
381905
+ owner.throwIfAborted();
381906
+ if (this.originalView?.source === source) {
381907
+ if (this.originalView.owner !== owner) throw new Error('ORIGINAL_HISTORY_SOURCE_ALREADY_BOUND');
381908
+ return;
381909
+ }
381910
+ const epoch = ++this.originalEpoch;
381911
+ this.closeOriginalView(true);
381912
+ owner.throwIfAborted();
381913
+ if (epoch !== this.originalEpoch) throw new Error('ORIGINAL_HISTORY_SUPERSEDED');
381914
+ const binding = {
381915
+ source, owner, windowRevision: source.windowRevision ?? 0, windowTotal: source.totalLines,
381916
+ live: { lines: this.lines, archive: this.archive,
381917
+ snapshotLineCount: this.snapshotLineCount, prependedLines: this.prependedLines },
381918
+ dispose: () => { if (this.originalView === binding) this.deactivate(); },
381919
+ };
381920
+ this.originalView = binding;
381921
+ owner.addEventListener('abort', binding.dispose, { once: true });
381922
+ this.archive = source;
381923
+ this.lines = [];
381924
+ this.snapshotLineCount = source.totalLines;
381925
+ this.prependedLines = 0;
381926
+ this.activate();
381927
+ }
381928
+
381929
+ applyOriginalWindowChange(source, change) {
381930
+ const binding = this.originalView;
381931
+ if (!binding || binding.source !== source) return false;
381932
+ binding.owner.throwIfAborted();
381933
+ for (const key of ['previousTotal', 'totalLines', 'previousRevision', 'windowRevision',
381934
+ 'addedBefore', 'removedBefore', 'removedAfter']) {
381935
+ if (!Number.isSafeInteger(change[key]) || change[key] < 0) throw new Error('INVALID_ORIGINAL_HISTORY_WINDOW_CHANGE');
381936
+ }
381937
+ if (binding.windowRevision !== change.previousRevision || binding.windowTotal !== change.previousTotal ||
381938
+ source.windowRevision !== change.windowRevision || source.totalLines !== change.totalLines ||
381939
+ change.windowRevision <= change.previousRevision) return false;
381940
+ const previousEnd = change.previousTotal - this.scrollOffset;
381941
+ const nextEnd = previousEnd + change.addedBefore - change.removedBefore;
381942
+ this.scrollOffset = Math.max(0, Math.min(change.totalLines - nextEnd, this.maximumScrollOffset));
381943
+ this.snapshotLineCount = change.totalLines;
381944
+ binding.windowTotal = change.totalLines;
381945
+ binding.windowRevision = change.windowRevision;
381946
+ return true;
381947
+ }
381948
+
381949
+ closeOriginalView(restore) {
381950
+ const binding = this.originalView;
381951
+ if (!binding) return;
381952
+ this.originalView = undefined;
381953
+ binding.owner.removeEventListener('abort', binding.dispose);
381954
+ this.lines = restore ? binding.live.lines : [];
381955
+ this.archive = restore ? binding.live.archive : undefined;
381956
+ this.snapshotLineCount = (this.archive?.totalLines ?? 0) + this.lines.length;
381957
+ this.prependedLines = restore ? binding.live.prependedLines : 0;
381958
+ this.active = false;
381959
+ this.scrollOffset = 0;
381960
+ this.originalTransition = true;
381961
+ try { binding.source.dispose?.(); } catch (error) {
381962
+ try { binding.source.onError?.(error); } catch { /* Cleanup must not strand the live view. */ }
381963
+ } finally { this.originalTransition = false; }
381964
+ }
381965
+
381807
381966
  lines = [];
381808
381967
  archive;
381809
381968
  scrollOffset = 0;
@@ -381827,6 +381986,7 @@ var init_scrollback_buffer = __esmMin((() => {
381827
381986
  return (this.archive?.totalLines ?? 0) + this.lines.length;
381828
381987
  }
381829
381988
  useArchive(archive) {
381989
+ if (this.originalView) { this.originalView.live.archive = archive; return; }
381830
381990
  this.archive = archive;
381831
381991
  }
381832
381992
  activate() {
@@ -381834,10 +381994,14 @@ var init_scrollback_buffer = __esmMin((() => {
381834
381994
  this.scrollOffset = 0;
381835
381995
  }
381836
381996
  deactivate() {
381997
+ this.originalEpoch++;
381998
+ this.closeOriginalView(true);
381837
381999
  this.active = false;
381838
382000
  this.scrollOffset = 0;
381839
382001
  }
381840
382002
  clear() {
382003
+ this.originalEpoch++;
382004
+ this.closeOriginalView(false);
381841
382005
  this.lines = [];
381842
382006
  this.archive = void 0;
381843
382007
  this.snapshotLineCount = 0;
@@ -381847,6 +382011,12 @@ var init_scrollback_buffer = __esmMin((() => {
381847
382011
  /** Replace the clipped-frame snapshot and record its actual visible height. */
381848
382012
  updateSnapshot(clipped, viewportRows) {
381849
382013
  this.viewportRows = Math.max(1, Math.floor(viewportRows));
382014
+ if (this.originalView) {
382015
+ this.originalView.live.lines = [...clipped];
382016
+ this.originalView.live.prependedLines = 0;
382017
+ this.scrollOffset = Math.min(this.scrollOffset, this.maximumScrollOffset);
382018
+ return;
382019
+ }
381850
382020
  const nextLineCount = (this.archive?.totalLines ?? 0) + clipped.length;
381851
382021
  const lineCountDelta = nextLineCount - this.snapshotLineCount;
381852
382022
  const prepended = Math.min(this.prependedLines, Math.max(0, lineCountDelta));
@@ -381863,6 +382033,7 @@ var init_scrollback_buffer = __esmMin((() => {
381863
382033
  /** Unlike new output at the bottom, prepended history must not move the reading anchor. */
381864
382034
  notePrependedLines(count) {
381865
382035
  if (!Number.isSafeInteger(count) || count < 0) throw new RangeError("INVALID_PREPENDED_LINE_COUNT");
382036
+ if (this.originalView) { this.originalView.live.prependedLines += count; return; }
381866
382037
  this.prependedLines += count;
381867
382038
  }
381868
382039
  scrollUp(amount) {
@@ -442168,6 +442339,28 @@ var init_scrollback = __esmMin((() => {
442168
442339
  init_scrollback_buffer();
442169
442340
  init_session_scrollback_archive();
442170
442341
  ScrollbackController = class {
442342
+ originalInput;
442343
+ originalHistoryTransition = false;
442344
+ originalHistoryEpoch = 0;
442345
+ get originalHistoryInput() { return this.originalInput; }
442346
+ set originalHistoryInput(input) {
442347
+ if (this.originalHistoryTransition) throw new Error("ORIGINAL_HISTORY_TRANSITION");
442348
+ if (input === this.originalInput) return;
442349
+ const epoch = this.originalHistoryEpoch + 1;
442350
+ const failure = this.invalidateOriginalHistory();
442351
+ if (failure) throw failure.error;
442352
+ if (epoch !== this.originalHistoryEpoch) throw new Error("ORIGINAL_HISTORY_SUPERSEDED");
442353
+ this.originalInput = input;
442354
+ }
442355
+ invalidateOriginalHistory() {
442356
+ this.originalHistoryEpoch++;
442357
+ const input = this.originalInput, previous = this.originalHistoryTransition;
442358
+ this.originalInput = undefined;
442359
+ this.originalHistoryTransition = true;
442360
+ try { input?.dispose(); } catch (error) { return { error }; }
442361
+ finally { this.originalHistoryTransition = previous; }
442362
+ }
442363
+
442171
442364
  state;
442172
442365
  currentSession;
442173
442366
  buffer;
@@ -442180,14 +442373,28 @@ var init_scrollback = __esmMin((() => {
442180
442373
  this.currentSession = currentSession;
442181
442374
  }
442182
442375
  install() {
442376
+ if (this.originalHistoryTransition) throw new Error("ORIGINAL_HISTORY_TRANSITION");
442377
+ const previous = this.originalHistoryTransition;
442378
+ this.originalHistoryTransition = true;
442379
+ const failure = this.invalidateOriginalHistory();
442380
+ let failed = false;
442381
+ try {
442183
442382
  const ui = this.state.ui;
442184
442383
  if (!(ui instanceof BottomPinnedTUI)) return;
442185
442384
  const buffer = new ScrollbackBuffer();
442186
442385
  ui.scrollbackBuffer = buffer;
442187
442386
  this.buffer = buffer;
442188
442387
  this.disposeListener = ui.addInputListener((data) => this.handleKey(data));
442388
+ } catch (error) { failed = true; throw error; }
442389
+ finally { this.originalHistoryTransition = previous; if (failure && !failed) throw failure.error; }
442189
442390
  }
442190
442391
  dispose() {
442392
+ if (this.originalHistoryTransition) throw new Error("ORIGINAL_HISTORY_TRANSITION");
442393
+ const previous = this.originalHistoryTransition;
442394
+ this.originalHistoryTransition = true;
442395
+ const failure = this.invalidateOriginalHistory();
442396
+ let failed = false;
442397
+ try {
442191
442398
  this.historyBinding?.dispose();
442192
442399
  this.archive?.dispose();
442193
442400
  this.archive = void 0;
@@ -442196,13 +442403,23 @@ var init_scrollback = __esmMin((() => {
442196
442403
  this.disposeListener = void 0;
442197
442404
  if (this.state.ui instanceof BottomPinnedTUI) this.state.ui.scrollbackBuffer = void 0;
442198
442405
  this.buffer = void 0;
442406
+ } catch (error) { failed = true; throw error; }
442407
+ finally { this.originalHistoryTransition = previous; if (failure && !failed) throw failure.error; }
442199
442408
  }
442200
442409
  reset() {
442410
+ if (this.originalHistoryTransition) throw new Error("ORIGINAL_HISTORY_TRANSITION");
442411
+ const previous = this.originalHistoryTransition;
442412
+ this.originalHistoryTransition = true;
442413
+ const failure = this.invalidateOriginalHistory();
442414
+ let failed = false;
442415
+ try {
442201
442416
  this.historyBinding?.dispose();
442202
442417
  this.archive?.dispose();
442203
442418
  this.archive = void 0;
442204
442419
  this.archiveSession = void 0;
442205
442420
  this.buffer?.clear();
442421
+ } catch (error) { failed = true; throw error; }
442422
+ finally { this.originalHistoryTransition = previous; if (failure && !failed) throw failure.error; }
442206
442423
  }
442207
442424
  notePrependedLines(count) {
442208
442425
  this.buffer?.notePrependedLines(count);
@@ -442285,6 +442502,8 @@ var init_scrollback = __esmMin((() => {
442285
442502
  } catch {}
442286
442503
  }
442287
442504
  handleKey(data) {
442505
+ const original = this.originalHistoryInput?.handleKey(data);
442506
+ if (original !== undefined) return original ?? undefined;
442288
442507
  const buffer = this.buffer;
442289
442508
  if (buffer === void 0) return void 0;
442290
442509
  if (isKeyRelease(data)) return void 0;
@@ -500293,7 +500512,7 @@ function managedTelegramPluginEnabled() {
500293
500512
  function managedTelegramPluginRoot() {
500294
500513
  const blunHome = process.env["BLUN_HOME"] || join(homedir(), ".blun");
500295
500514
  try {
500296
- const plugin = JSON.parse(readFileSync(join(blunHome, "plugins", "installed.json"), "utf8")).plugins?.find((item) => item.id === "telegram");
500515
+ const plugin = JSON.parse(readFileSync(join(blunHome, "plugins", "installed.json"), "utf8").replace(/^\uFEFF/u, '')).plugins?.find((item) => item.id === "telegram");
500297
500516
  if (plugin?.enabled !== true || typeof plugin.root !== "string" || !plugin.root) return void 0;
500298
500517
  if (!existsSync(join(plugin.root, "dist", "mcp-server.mjs"))) return void 0;
500299
500518
  return plugin.root;
@@ -524841,6 +525060,7 @@ async function undoByCount(host, count) {
524841
525060
  showUndoLimitStatus(host, uiText("undo.status.nothing"));
524842
525061
  return false;
524843
525062
  }
525063
+ host.scrollbackController?.invalidateOriginalHistory?.();
524844
525064
  try {
524845
525065
  await session.undoHistory(count);
524846
525066
  } catch (error) {
@@ -534536,6 +534756,865 @@ function replayBackgroundProjection(background) {
534536
534756
  }
534537
534757
  return { backgroundAgentMetadata };
534538
534758
  }
534759
+ function cloneReplayRenderContext(context) {
534760
+ return {
534761
+ ...context,
534762
+ assistant: { thinking: [...context.assistant.thinking], text: [...context.assistant.text] },
534763
+ toolCalls: new Map([...context.toolCalls].map(([id, call]) => [id, { ...call }])),
534764
+ completedToolCallIds: new Set(context.completedToolCallIds),
534765
+ skillActivationIds: new Set(context.skillActivationIds),
534766
+ pluginCommandActivationIds: new Set(context.pluginCommandActivationIds),
534767
+ };
534768
+ }
534769
+ function originalReplaySeenSet(seenBefore) {
534770
+ const local = new Set();
534771
+ return { has: (id) => local.has(id) || seenBefore(id), add: (id) => { local.add(id); } };
534772
+ }
534773
+ function originalReplayIndexRenderer(position, firstSkills, firstCommands, turnPrefix) {
534774
+ const noop = () => {};
534775
+ const seen = (first) => ({ has: (id) => first.has(id), add: (id) => {
534776
+ if (!first.has(id)) first.set(id, position.value);
534777
+ } });
534778
+ const renderer = new SessionReplayRenderer({
534779
+ streamingUI: { setTurnId: noop, setStep: noop, setActiveToolCall: noop, onToolCallStart: noop },
534780
+ sessionEventHandler: { renderedSkillActivationIds: seen(firstSkills),
534781
+ renderedPluginCommandActivationIds: seen(firstCommands) },
534782
+ appendTranscriptEntry: noop,
534783
+ }, turnPrefix);
534784
+ renderer.materializeImages = () => ({ ids: [], unavailable: 0 });
534785
+ renderer.flushAssistant = (context) => { context.assistant = { thinking: [], text: [] }; };
534786
+ renderer.renderToolResult = (context, message) => {
534787
+ if (message.toolCallId !== undefined) context.toolCalls.delete(message.toolCallId);
534788
+ };
534789
+ renderer.removeToolCall = noop;
534790
+ renderer.renderBackgroundTaskNotification = noop;
534791
+ renderer.renderHookResult = noop;
534792
+ renderer.renderCronJob = noop;
534793
+ renderer.renderCronMissed = noop;
534794
+ renderer.renderGoalReplayRecord = noop;
534795
+ renderer.renderPermissionUpdate = noop;
534796
+ renderer.renderCompaction = noop;
534797
+ return renderer;
534798
+ }
534799
+ async function createOriginalReplayCursorIndex(records, boundaries, owner, turnPrefix, source) {
534800
+ owner.throwIfAborted();
534801
+ if (typeof turnPrefix !== 'string' || turnPrefix.length === 0) throw new Error('INVALID_ORIGINAL_HISTORY_PREFIX');
534802
+ if (!source || typeof source.assertCurrent !== 'function') throw new Error('ORIGINAL_HISTORY_SOURCE_FENCE_REQUIRED');
534803
+ const length = records.length;
534804
+ const assertCurrent = () => {
534805
+ owner.throwIfAborted();
534806
+ source.assertCurrent();
534807
+ owner.throwIfAborted();
534808
+ if (records.length !== length) throw new Error('ORIGINAL_HISTORY_SOURCE_CHANGED');
534809
+ };
534810
+ assertCurrent();
534811
+ const required = new Set(boundaries);
534812
+ for (const boundary of required) if (!Number.isSafeInteger(boundary) || boundary < 0 || boundary > length) {
534813
+ throw new Error('INVALID_ORIGINAL_HISTORY_BOUNDARY');
534814
+ }
534815
+ const position = { value: 0 }, firstSkills = new Map(), firstCommands = new Map(), points = new Map();
534816
+ const renderer = originalReplayIndexRenderer(position, firstSkills, firstCommands, turnPrefix);
534817
+ const context = createReplayRenderContext();
534818
+ const capture = (ordinal) => {
534819
+ if (!required.has(ordinal)) return;
534820
+ if (ordinal < length && context.toolCalls.size > 0) throw new Error('ORIGINAL_HISTORY_BOUNDARY_INSIDE_TOOL_BATCH');
534821
+ points.set(ordinal, Object.freeze({ turnIndex: context.turnIndex, stepIndex: context.stepIndex,
534822
+ currentTurnId: context.currentTurnId, suppressNextPlanModeOffNotice: context.suppressNextPlanModeOffNotice,
534823
+ incompleteToolBatch: context.toolCalls.size > 0 }));
534824
+ };
534825
+ for (let ordinal = 0; ordinal < length; ordinal++) {
534826
+ capture(ordinal);
534827
+ position.value = ordinal;
534828
+ renderer.renderRecord(context, records[ordinal]);
534829
+ if ((ordinal + 1) % 128 === 0) {
534830
+ await new Promise((resolve) => { setTimeout(resolve, 0); });
534831
+ assertCurrent();
534832
+ }
534833
+ }
534834
+ assertCurrent();
534835
+ capture(length);
534836
+ const seenBefore = (first, id, ordinal) => {
534837
+ assertCurrent();
534838
+ if (!Number.isSafeInteger(ordinal) || ordinal < 0 || ordinal > length) throw new Error('INVALID_ORIGINAL_HISTORY_BOUNDARY');
534839
+ return first.has(id) && first.get(id) < ordinal;
534840
+ };
534841
+ return Object.freeze({
534842
+ at(ordinal) {
534843
+ assertCurrent();
534844
+ const point = points.get(ordinal);
534845
+ if (!point) throw new Error('ORIGINAL_HISTORY_BOUNDARY_NOT_INDEXED');
534846
+ if (point.incompleteToolBatch) throw new Error('ORIGINAL_HISTORY_INCOMPLETE_TOOL_BATCH');
534847
+ return { ...createReplayRenderContext(), ...point, originalTurnPrefix: turnPrefix,
534848
+ originalSeenSkill: (id) => seenBefore(firstSkills, id, ordinal),
534849
+ originalSeenCommand: (id) => seenBefore(firstCommands, id, ordinal) };
534850
+ },
534851
+ seenSkillBefore: (id, ordinal) => seenBefore(firstSkills, id, ordinal),
534852
+ seenCommandBefore: (id, ordinal) => seenBefore(firstCommands, id, ordinal),
534853
+ });
534854
+ }
534855
+ function readOriginalHistoryLines(components, width, limits, owner) {
534856
+ owner.throwIfAborted();
534857
+ if (!Number.isSafeInteger(width) || width < 1 || !limits ||
534858
+ !Number.isSafeInteger(limits.maxRows) || limits.maxRows < 1 ||
534859
+ !Number.isSafeInteger(limits.maxBytes) || limits.maxBytes < 1) throw new Error('INVALID_ORIGINAL_HISTORY_RENDER_LIMIT');
534860
+ const rows = [];
534861
+ let bytes = 0;
534862
+ for (const component of components) {
534863
+ owner.throwIfAborted();
534864
+ const rendered = component.render(width);
534865
+ if (!Array.isArray(rendered) || rendered.length > limits.maxRows - rows.length) throw new Error('ORIGINAL_HISTORY_PAGE_LIMIT');
534866
+ for (const row of rendered) {
534867
+ if (typeof row !== 'string') throw new Error('INVALID_ORIGINAL_HISTORY_ROW');
534868
+ bytes += Buffer.byteLength(row, 'utf8');
534869
+ if (bytes > limits.maxBytes) throw new Error('ORIGINAL_HISTORY_PAGE_LIMIT');
534870
+ rows.push(row);
534871
+ }
534872
+ }
534873
+ owner.throwIfAborted();
534874
+ return Object.freeze(rows);
534875
+ }
534876
+ class OriginalHistoryWindow {
534877
+ cache = new Map();
534878
+ controller = new AbortController();
534879
+ closed = false;
534880
+ pending = false;
534881
+ revision = 0;
534882
+
534883
+ constructor(options) {
534884
+ for (const key of ['pageCount', 'maxPages', 'maxRows', 'maxBytes']) {
534885
+ if (!Number.isSafeInteger(options[key]) || options[key] < (key === 'pageCount' ? 0 : 1)) {
534886
+ throw new Error('INVALID_ORIGINAL_HISTORY_WINDOW');
534887
+ }
534888
+ }
534889
+ if (typeof options.load !== 'function' || typeof options.assertCurrent !== 'function') {
534890
+ throw new TypeError('INVALID_ORIGINAL_HISTORY_WINDOW');
534891
+ }
534892
+ this.pageCount = options.pageCount;
534893
+ this.maxPages = options.maxPages;
534894
+ this.maxRows = options.maxRows;
534895
+ this.maxBytes = options.maxBytes;
534896
+ this.owner = options.owner;
534897
+ this.assertCurrent = options.assertCurrent;
534898
+ this.load = options.load;
534899
+ this.abort = () => { this.dispose(); };
534900
+ this.owner.throwIfAborted();
534901
+ this.owner.addEventListener('abort', this.abort, { once: true });
534902
+ }
534903
+
534904
+ assert() {
534905
+ if (this.closed) throw new Error('ORIGINAL_HISTORY_WINDOW_CLOSED');
534906
+ this.owner.throwIfAborted();
534907
+ this.controller.signal.throwIfAborted();
534908
+ this.assertCurrent();
534909
+ this.owner.throwIfAborted();
534910
+ if (this.closed) throw new Error('ORIGINAL_HISTORY_WINDOW_CLOSED');
534911
+ }
534912
+
534913
+ get totalLines() {
534914
+ this.assert();
534915
+ return [...this.cache.values()].reduce((sum, page) => sum + page.rows.length, 0);
534916
+ }
534917
+
534918
+ get windowRevision() { this.assert(); return this.revision; }
534919
+
534920
+ get hasEarlier() { this.assert(); return this.cache.size > 0 && Math.min(...this.cache.keys()) > 0; }
534921
+ get hasLater() { this.assert(); return this.cache.size > 0 && Math.max(...this.cache.keys()) < this.pageCount - 1; }
534922
+
534923
+ readRange(start, end) {
534924
+ this.assert();
534925
+ if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) || start < 0 || end < start || end > this.totalLines) {
534926
+ throw new Error('INVALID_ORIGINAL_HISTORY_RANGE');
534927
+ }
534928
+ const result = [];
534929
+ let offset = 0;
534930
+ for (const [, page] of [...this.cache].toSorted(([a], [b]) => a - b)) {
534931
+ if (offset < end && offset + page.rows.length > start) {
534932
+ result.push(...page.rows.slice(Math.max(0, start - offset), end - offset));
534933
+ }
534934
+ offset += page.rows.length;
534935
+ }
534936
+ this.assert();
534937
+ return result;
534938
+ }
534939
+
534940
+ openLatest() { return this.#loadPage(this.pageCount - 1, 'open'); }
534941
+ loadEarlier(onCommit) { return this.#loadPage(this.cache.size > 0 ? Math.min(...this.cache.keys()) - 1 : this.pageCount - 1, 'earlier', onCommit); }
534942
+ loadLater(onCommit) { return this.#loadPage(this.cache.size > 0 ? Math.max(...this.cache.keys()) + 1 : this.pageCount - 1, 'later', onCommit); }
534943
+
534944
+ async #loadPage(index, direction, onCommit) {
534945
+ this.assert();
534946
+ if (onCommit !== undefined && typeof onCommit !== 'function') throw new TypeError('INVALID_ORIGINAL_HISTORY_COMMIT');
534947
+ if (this.pending) throw new Error('ORIGINAL_HISTORY_LOAD_BUSY');
534948
+ const previousTotal = this.totalLines;
534949
+ const previousRevision = this.revision;
534950
+ if (index < 0 || index >= this.pageCount) return { previousTotal, totalLines: previousTotal,
534951
+ previousRevision, windowRevision: previousRevision, addedBefore: 0, removedBefore: 0, removedAfter: 0 };
534952
+ this.pending = true;
534953
+ try {
534954
+ const loaded = await this.load(index, this.controller.signal);
534955
+ this.assert();
534956
+ if (!Array.isArray(loaded) || loaded.length > this.maxRows) throw new Error('ORIGINAL_HISTORY_PAGE_LIMIT');
534957
+ let bytes = 0;
534958
+ for (const row of loaded) {
534959
+ if (typeof row !== 'string') throw new Error('INVALID_ORIGINAL_HISTORY_ROW');
534960
+ bytes += Buffer.byteLength(row, 'utf8');
534961
+ if (bytes > this.maxBytes) throw new Error('ORIGINAL_HISTORY_PAGE_LIMIT');
534962
+ }
534963
+ const candidate = direction === 'open' ? new Map() : new Map(this.cache);
534964
+ candidate.set(index, { rows: Object.freeze([...loaded]), bytes });
534965
+ const overBudget = () => candidate.size > this.maxPages ||
534966
+ [...candidate.values()].reduce((sum, page) => sum + page.rows.length, 0) > this.maxRows ||
534967
+ [...candidate.values()].reduce((sum, page) => sum + page.bytes, 0) > this.maxBytes;
534968
+ while (overBudget()) candidate.delete(direction === 'earlier' ? Math.max(...candidate.keys()) : Math.min(...candidate.keys()));
534969
+ const first = Math.min(...candidate.keys()), last = Math.max(...candidate.keys());
534970
+ let removedBefore = 0, removedAfter = 0, addedBefore = 0;
534971
+ const oldFirst = this.cache.size > 0 ? Math.min(...this.cache.keys()) : first;
534972
+ for (const [key, page] of this.cache) {
534973
+ if (key < first) removedBefore += page.rows.length;
534974
+ if (key > last) removedAfter += page.rows.length;
534975
+ }
534976
+ for (const [key, page] of candidate) if (key < oldFirst && !this.cache.has(key)) addedBefore += page.rows.length;
534977
+ this.assert();
534978
+ this.cache = candidate;
534979
+ this.revision++;
534980
+ const change = { previousTotal, totalLines: this.totalLines, previousRevision, windowRevision: this.revision,
534981
+ addedBefore, removedBefore, removedAfter };
534982
+ const result = onCommit?.(change);
534983
+ if (result && typeof result.then === 'function') {
534984
+ void Promise.resolve(result).catch(() => {});
534985
+ throw new TypeError('ASYNC_ORIGINAL_HISTORY_COMMIT');
534986
+ }
534987
+ this.assert();
534988
+ return change;
534989
+ } finally { this.pending = false; }
534990
+ }
534991
+
534992
+ dispose() {
534993
+ if (this.closed) return;
534994
+ this.closed = true;
534995
+ this.owner.removeEventListener('abort', this.abort);
534996
+ this.controller.abort();
534997
+ this.cache.clear();
534998
+ }
534999
+ }
535000
+ async function createSnapshotOriginalHistorySource(renderer, session, records, options, owner) {
535001
+ owner.throwIfAborted();
535002
+ if (!options || typeof options.assertCurrent !== 'function' ||
535003
+ typeof options.turnPrefix !== 'string' || options.turnPrefix.length === 0 ||
535004
+ !Number.isSafeInteger(options.width) || options.width < 1 ||
535005
+ !Number.isSafeInteger(options.maxRecords) || options.maxRecords < 1) {
535006
+ throw new TypeError('INVALID_ORIGINAL_HISTORY_SOURCE_OPTIONS');
535007
+ }
535008
+ options = Object.freeze({ ...options });
535009
+ options.assertCurrent();
535010
+ const replay = Object.freeze([...records]);
535011
+ const index = createEmbeddedHistoryPageIndex(replay);
535012
+ const pages = [];
535013
+ let end = replay.length;
535014
+ while (end > 0) {
535015
+ const start = embeddedPageStart(replay, end, options.maxRecords, index);
535016
+ pages.push({ start, end });
535017
+ end = start;
535018
+ }
535019
+ pages.reverse();
535020
+ let cursors;
535021
+ const source = new OriginalHistoryWindow({
535022
+ pageCount: pages.length, maxPages: options.maxPages, maxRows: options.maxRows, maxBytes: options.maxBytes,
535023
+ owner, assertCurrent: () => { options.assertCurrent(); },
535024
+ load: (pageIndex, signal) => {
535025
+ source.assert();
535026
+ signal.throwIfAborted();
535027
+ const { start, end: pageEnd } = pages[pageIndex];
535028
+ if (pageEnd - start > options.maxRecords) throw new Error('ORIGINAL_HISTORY_ATOMIC_PAGE_LIMIT');
535029
+ const page = renderer.prepareEmbeddedHistory(session, replay.slice(start, pageEnd), signal, cursors.at(start));
535030
+ try {
535031
+ const rows = page.readOriginalLines(options.width, { maxRows: options.maxRows, maxBytes: options.maxBytes });
535032
+ source.assert();
535033
+ signal.throwIfAborted();
535034
+ return rows;
535035
+ } finally { page.dispose(); }
535036
+ },
535037
+ });
535038
+ try {
535039
+ cursors = await createOriginalReplayCursorIndex(replay, [...pages.map((page) => page.start), replay.length],
535040
+ source.controller.signal, options.turnPrefix, { assertCurrent: () => { source.assert(); } });
535041
+ await source.openLatest();
535042
+ source.assert();
535043
+ return source;
535044
+ } catch (error) {
535045
+ source.dispose();
535046
+ throw error;
535047
+ }
535048
+ }
535049
+ class OriginalHistoryController {
535050
+ binding;
535051
+ activation;
535052
+ generation = 0;
535053
+
535054
+ constructor(buffer, callbacks = {}) {
535055
+ this.buffer = buffer;
535056
+ this.onChange = callbacks.onChange ?? (() => {});
535057
+ this.onError = callbacks.onError ?? (() => {});
535058
+ }
535059
+
535060
+ get isActive() { return this.activation !== undefined; }
535061
+
535062
+ bind(createSource, owner, assertCurrent) {
535063
+ if (typeof createSource !== 'function' || typeof assertCurrent !== 'function' ||
535064
+ !owner || typeof owner.throwIfAborted !== 'function') throw new TypeError('INVALID_ORIGINAL_HISTORY_BINDING');
535065
+ owner.throwIfAborted();
535066
+ const generation = this.generation + 1;
535067
+ this.invalidate();
535068
+ owner.throwIfAborted();
535069
+ assertCurrent();
535070
+ owner.throwIfAborted();
535071
+ if (generation !== this.generation || this.binding) throw new Error('ORIGINAL_HISTORY_SUPERSEDED');
535072
+ const binding = { createSource, owner, assertCurrent, generation,
535073
+ abort: () => { if (this.binding === binding) this.invalidate(); } };
535074
+ this.binding = binding;
535075
+ owner.addEventListener('abort', binding.abort, { once: true });
535076
+ owner.throwIfAborted();
535077
+ }
535078
+
535079
+ invalidate() {
535080
+ const binding = this.binding;
535081
+ this.binding = undefined;
535082
+ this.generation++;
535083
+ binding?.owner.removeEventListener('abort', binding.abort);
535084
+ this.close();
535085
+ }
535086
+
535087
+ close() { if (this.activation) this.#close(this.activation); }
535088
+
535089
+ #close(active) {
535090
+ if (this.activation !== active) return;
535091
+ this.activation = undefined;
535092
+ active.intents.length = 0;
535093
+ active.controller.abort();
535094
+ if (this.buffer.originalView?.source === active.source && active.source) this.buffer.deactivate();
535095
+ if (active.source && !active.source.closed) active.source.dispose();
535096
+ this.onChange();
535097
+ }
535098
+
535099
+ #assert(active) {
535100
+ active.controller.signal.throwIfAborted();
535101
+ if (this.activation !== active || this.binding !== active.binding ||
535102
+ this.generation !== active.binding.generation) throw new Error('ORIGINAL_HISTORY_SUPERSEDED');
535103
+ active.binding.owner.throwIfAborted();
535104
+ active.binding.assertCurrent();
535105
+ active.controller.signal.throwIfAborted();
535106
+ if (this.activation !== active || this.binding !== active.binding) throw new Error('ORIGINAL_HISTORY_SUPERSEDED');
535107
+ }
535108
+
535109
+ activate() { return this.#enqueue(); }
535110
+ home() { return this.#enqueue({ type: 'home' }); }
535111
+ navigate(rows) {
535112
+ if (!Number.isSafeInteger(rows)) throw new RangeError('INVALID_ORIGINAL_HISTORY_NAVIGATION');
535113
+ return this.#enqueue(rows === 0 ? undefined : { type: 'move', rows });
535114
+ }
535115
+
535116
+ #enqueue(intent) {
535117
+ const binding = this.binding;
535118
+ if (!binding) throw new Error('ORIGINAL_HISTORY_UNBOUND');
535119
+ binding.owner.throwIfAborted();
535120
+ binding.assertCurrent();
535121
+ if (binding !== this.binding) throw new Error('ORIGINAL_HISTORY_SUPERSEDED');
535122
+ let active = this.activation;
535123
+ if (!active) {
535124
+ active = { binding, controller: new AbortController(), intents: [], source: undefined, worker: undefined };
535125
+ this.activation = active;
535126
+ }
535127
+ if (intent) {
535128
+ const previous = active.intents.at(-1);
535129
+ if (previous?.type === 'move' && intent.type === 'move' && Math.sign(previous.rows) === Math.sign(intent.rows)) {
535130
+ const total = previous.rows + intent.rows;
535131
+ if (!Number.isSafeInteger(total)) throw new RangeError('INVALID_ORIGINAL_HISTORY_NAVIGATION');
535132
+ previous.rows = total;
535133
+ } else {
535134
+ if (active.intents.length >= 256) throw new Error('ORIGINAL_HISTORY_NAVIGATION_LIMIT');
535135
+ active.intents.push(intent);
535136
+ }
535137
+ }
535138
+ if (active.worker) return active.worker;
535139
+ const work = Promise.resolve().then(() => this.#drain(active)).catch((error) => {
535140
+ if (this.activation !== active || active.controller.signal.aborted) return false;
535141
+ this.#close(active);
535142
+ if (this.binding === active.binding && this.generation === active.binding.generation && !this.activation) this.onError(error);
535143
+ throw error;
535144
+ }).finally(() => { if (active.worker === work) active.worker = undefined; });
535145
+ active.worker = work;
535146
+ return work;
535147
+ }
535148
+
535149
+ async #drain(active) {
535150
+ this.#assert(active);
535151
+ if (!active.source) {
535152
+ const source = await active.binding.createSource(active.controller.signal, () => { this.#assert(active); });
535153
+ try {
535154
+ this.#assert(active);
535155
+ this.buffer.beginOriginalView(source, active.controller.signal);
535156
+ active.source = source;
535157
+ this.#assert(active);
535158
+ this.onChange();
535159
+ } catch (error) { if (!source.closed) source.dispose(); throw error; }
535160
+ }
535161
+ for (;;) {
535162
+ this.#assert(active);
535163
+ const intent = active.intents.shift();
535164
+ if (!intent) { active.worker = undefined; return true; }
535165
+ if (intent.type === 'home') {
535166
+ this.buffer.goToTop();
535167
+ while (active.source.hasEarlier) {
535168
+ await this.#load(active, 'loadEarlier');
535169
+ this.buffer.goToTop();
535170
+ }
535171
+ } else await this.#move(active, intent.rows);
535172
+ this.#assert(active);
535173
+ this.onChange();
535174
+ }
535175
+ }
535176
+
535177
+ async #load(active, method) {
535178
+ this.#assert(active);
535179
+ const source = active.source;
535180
+ let anchorDrift = 0;
535181
+ const change = await source[method]((delta) => {
535182
+ this.#assert(active);
535183
+ const expectedEnd = delta.previousTotal - this.buffer.scrollOffset + delta.addedBefore - delta.removedBefore;
535184
+ if (!this.buffer.applyOriginalWindowChange(source, delta)) throw new Error('ORIGINAL_HISTORY_WINDOW_CHANGED');
535185
+ anchorDrift = expectedEnd - (delta.totalLines - this.buffer.scrollOffset);
535186
+ this.#assert(active);
535187
+ this.onChange();
535188
+ });
535189
+ this.#assert(active);
535190
+ if (change.windowRevision <= change.previousRevision) throw new Error('ORIGINAL_HISTORY_NO_PROGRESS');
535191
+ await new Promise((resolve) => { setTimeout(resolve, 0); });
535192
+ this.#assert(active);
535193
+ return anchorDrift;
535194
+ }
535195
+
535196
+ async #move(active, rows) {
535197
+ let remaining = Math.abs(rows);
535198
+ while (remaining > 0) {
535199
+ this.#assert(active);
535200
+ const older = rows > 0;
535201
+ const available = older ? this.buffer.maximumScrollOffset - this.buffer.scrollOffset : this.buffer.scrollOffset;
535202
+ const step = Math.min(available, remaining);
535203
+ if (older) this.buffer.scrollUp(step); else this.buffer.scrollDown(step);
535204
+ remaining -= step;
535205
+ if (remaining === 0) break;
535206
+ if (older ? active.source.hasEarlier : active.source.hasLater) {
535207
+ const wasEmpty = active.source.totalLines === 0;
535208
+ const drift = await this.#load(active, older ? 'loadEarlier' : 'loadLater');
535209
+ const moved = wasEmpty ? Number(active.source.totalLines > 0) : Math.max(0, older ? drift : -drift);
535210
+ if (moved > remaining) throw new Error('ORIGINAL_HISTORY_ANCHOR_LIMIT');
535211
+ remaining -= moved;
535212
+ } else {
535213
+ if (!older) this.#close(active);
535214
+ return;
535215
+ }
535216
+ }
535217
+ if (rows < 0 && this.buffer.isAtBottom() && !active.source.hasLater) this.#close(active);
535218
+ }
535219
+ }
535220
+ class OriginalHistoryKeyboard {
535221
+ onToolOutput;
535222
+ onExit;
535223
+ constructor(controller, state) {
535224
+ this.controller = controller;
535225
+ this.state = state;
535226
+ }
535227
+
535228
+ dispose() { this.controller.invalidate(); }
535229
+
535230
+ handleKey(data) {
535231
+ const controller = this.controller;
535232
+ if (!controller.binding || isKeyRelease(data)) return undefined;
535233
+ if (!this.state.editor.focused) { controller.close(); this.onExit?.(); return null; }
535234
+ const active = controller.isActive;
535235
+ const mouse = parseSgrMouseButton(data);
535236
+ const wheel = mouse !== undefined && (mouse & 64) !== 0 && (mouse & 3) <= 1;
535237
+ if (mouse !== undefined && !wheel) return undefined;
535238
+ if (wheel && data.endsWith('m')) return { consume: true };
535239
+ if (wheel) {
535240
+ if (!active && (mouse & 1) !== 0) return undefined;
535241
+ this.#dispatch(() => controller.navigate((mouse & 1) === 0 ? 3 : -3));
535242
+ } else if (matchesKey(data, Key.pageUp)) {
535243
+ this.#dispatch(() => controller.navigate(controller.buffer.viewportRows));
535244
+ } else if (matchesKey(data, Key.shift('up')) || matchesKey(data, Key.ctrl('up')) || active && matchesKey(data, Key.up)) {
535245
+ this.#dispatch(() => controller.navigate(1));
535246
+ } else if (!active) {
535247
+ return undefined;
535248
+ } else if (matchesKey(data, Key.pageDown)) {
535249
+ this.#dispatch(() => controller.navigate(-controller.buffer.viewportRows));
535250
+ } else if (matchesKey(data, Key.down) || matchesKey(data, Key.shift('down')) || matchesKey(data, Key.ctrl('down'))) {
535251
+ this.#dispatch(() => controller.navigate(-1));
535252
+ } else if (matchesKey(data, Key.home)) {
535253
+ this.#dispatch(() => controller.home());
535254
+ } else if (matchesKey(data, 't') && this.onToolOutput) {
535255
+ try { this.onToolOutput(); } catch (error) { controller.onError(error); }
535256
+ } else if (matchesKey(data, Key.end) || matchesKey(data, Key.escape) || matchesKey(data, 'q')) {
535257
+ controller.close();
535258
+ this.onExit?.();
535259
+ } else {
535260
+ controller.close();
535261
+ this.onExit?.();
535262
+ return null;
535263
+ }
535264
+ return { consume: true };
535265
+ }
535266
+
535267
+ #dispatch(operation) {
535268
+ const controller = this.controller, binding = controller.binding, generation = controller.generation;
535269
+ const after = () => {
535270
+ if (controller.binding === binding && controller.generation === generation && !controller.isActive) this.onExit?.();
535271
+ };
535272
+ try { void operation().then(after, after).catch(() => {}); } catch (error) {
535273
+ if (controller.binding !== binding || controller.generation !== generation) return;
535274
+ controller.close();
535275
+ if (controller.binding === binding && controller.generation === generation && !controller.isActive) controller.onError(error);
535276
+ after();
535277
+ }
535278
+ }
535279
+ }
535280
+ const originalHistoryResetScopes = new WeakMap();
535281
+ function observeOriginalHistoryReset(host, session, event) {
535282
+ if (!session || host.session !== session || !event || event.type !== 'agent.context.reset' ||
535283
+ event.sessionId !== session.id || typeof event.agentId !== 'string' || event.agentId.length === 0 ||
535284
+ typeof event.revision !== 'string' || !/^(0|[1-9][0-9]{0,127})$/.test(event.revision)) return;
535285
+ const cursor = event.deliveryCursor;
535286
+ if (!cursor || typeof cursor.scope !== 'string' || !/^[A-Za-z0-9._:-]{1,128}$/.test(cursor.scope) ||
535287
+ typeof cursor.sequence !== 'string' || !/^(0|[1-9][0-9]{0,127})$/.test(cursor.sequence)) return;
535288
+ let sessions = originalHistoryResetScopes.get(host);
535289
+ if (!sessions) { sessions = new WeakMap(); originalHistoryResetScopes.set(host, sessions); }
535290
+ let agents = sessions.get(session);
535291
+ if (!agents) { agents = new Map(); sessions.set(session, agents); }
535292
+ const previous = agents.get(event.agentId);
535293
+ if (previous?.scope === cursor.scope && BigInt(cursor.sequence) <= BigInt(previous.sequence)) return;
535294
+ agents.set(event.agentId, { scope: cursor.scope, sequence: cursor.sequence });
535295
+ if (event.agentId === host.interactiveAgentId) host.scrollbackController?.invalidateOriginalHistory?.();
535296
+ }
535297
+ function bindOriginalHistorySnapshot(renderer, session, agent, options, enabled) {
535298
+ const host = renderer.host, scrollback = host.scrollbackController;
535299
+ if (!enabled || !scrollback?.buffer || typeof options?.isCurrent !== 'function') return false;
535300
+ const records = structuredClone(agent.replay);
535301
+ const width = Math.max(1, host.state.terminal.columns), agentId = host.interactiveAgentId;
535302
+ const owner = new AbortController();
535303
+ const assertCurrent = () => {
535304
+ owner.signal.throwIfAborted();
535305
+ if (renderer.originalHistoryOwner !== owner || host.session !== session || host.aborted || host.isShuttingDown ||
535306
+ host.interactiveAgentId !== agentId || host.state.terminal.columns !== width || !options.isCurrent()) {
535307
+ throw new Error('ORIGINAL_HISTORY_SCOPE_CHANGED');
535308
+ }
535309
+ };
535310
+ let renderQueued = false;
535311
+ const controller = new OriginalHistoryController(scrollback.buffer, {
535312
+ onChange: () => {
535313
+ if (renderQueued) return;
535314
+ renderQueued = true;
535315
+ queueMicrotask(() => {
535316
+ renderQueued = false;
535317
+ if (!owner.signal.aborted && renderer.originalHistoryOwner === owner) host.state.ui.requestRender();
535318
+ });
535319
+ },
535320
+ onError: error => { host.showError(formatErrorMessage$2(error)); },
535321
+ });
535322
+ const previousOwner = renderer.originalHistoryOwner;
535323
+ renderer.originalHistoryOwner = owner;
535324
+ try {
535325
+ previousOwner?.abort();
535326
+ assertCurrent();
535327
+ controller.bind((signal, assertActive) => createSnapshotOriginalHistorySource(renderer, session, records, {
535328
+ assertCurrent: () => { assertCurrent(); assertActive(); },
535329
+ turnPrefix: `original:${session.id}:${agentId}`, width,
535330
+ maxRecords: 200, maxPages: 3, maxRows: 4096, maxBytes: 8 * 1024 * 1024,
535331
+ }, signal), owner.signal, assertCurrent);
535332
+ const input = new OriginalHistoryKeyboard(controller, host.state);
535333
+ registerOriginalOutputCopy();
535334
+ installOriginalOutputSelection(input, renderer, records, owner.signal, assertCurrent, width);
535335
+ const dispose = input.dispose.bind(input);
535336
+ input.dispose = () => { owner.abort(); dispose(); };
535337
+ scrollback.originalHistoryInput = input;
535338
+ return true;
535339
+ } catch (error) {
535340
+ owner.abort();
535341
+ controller.invalidate();
535342
+ if (renderer.originalHistoryOwner === owner) renderer.originalHistoryOwner = undefined;
535343
+ throw error;
535344
+ }
535345
+ }
535346
+ class OriginalOutputPager {
535347
+ #text;
535348
+ #cursors = new WeakMap();
535349
+ #closed = false;
535350
+ #segmenter = new Intl.Segmenter(undefined, { granularity: 'grapheme' });
535351
+
535352
+ constructor(displayText, { widthOf, owner, assertCurrent }) {
535353
+ if (typeof displayText !== 'string' || typeof widthOf !== 'function' || typeof assertCurrent !== 'function' ||
535354
+ typeof owner?.throwIfAborted !== 'function') throw new TypeError('INVALID_ORIGINAL_OUTPUT_SOURCE');
535355
+ if (/[\u0000-\u0009\u000B\u000C\u000E-\u001F\u007F-\u009F]/u.test(displayText)) {
535356
+ throw new Error('ORIGINAL_OUTPUT_CONTROL');
535357
+ }
535358
+ this.#text = displayText;
535359
+ this.widthOf = widthOf;
535360
+ this.owner = owner;
535361
+ this.assertCurrent = assertCurrent;
535362
+ this.abort = () => { this.dispose(); };
535363
+ try {
535364
+ this.#assert();
535365
+ owner.addEventListener('abort', this.abort, { once: true });
535366
+ this.#assert();
535367
+ } catch (error) { this.dispose(); throw error; }
535368
+ }
535369
+
535370
+ #assert() {
535371
+ if (this.#closed) throw new Error('ORIGINAL_OUTPUT_CLOSED');
535372
+ this.owner.throwIfAborted();
535373
+ this.assertCurrent();
535374
+ this.owner.throwIfAborted();
535375
+ if (this.#closed) throw new Error('ORIGINAL_OUTPUT_CLOSED');
535376
+ }
535377
+
535378
+ #cursor(offset) {
535379
+ const cursor = Object.freeze({});
535380
+ this.#cursors.set(cursor, offset);
535381
+ return cursor;
535382
+ }
535383
+
535384
+ read(cursor, { columns, maxRows, maxBytes }) {
535385
+ this.#assert();
535386
+ for (const [value, maximum] of [[columns, 16384], [maxRows, 4096], [maxBytes, 8 * 1024 * 1024]]) {
535387
+ if (!Number.isSafeInteger(value) || value < 1 || value > maximum) throw new Error('ORIGINAL_OUTPUT_LIMIT');
535388
+ }
535389
+ const from = cursor === undefined ? 0 : this.#cursors.get(cursor);
535390
+ if (from === undefined) throw new Error('ORIGINAL_OUTPUT_CURSOR');
535391
+ const rows = [];
535392
+ let position = from, row = '', rowColumns = 0, rowBytes = 0, bytes = 0;
535393
+ const flush = () => {
535394
+ rows.push(row);
535395
+ bytes += rowBytes;
535396
+ row = '';
535397
+ rowColumns = rowBytes = 0;
535398
+ };
535399
+ const result = () => {
535400
+ this.#assert();
535401
+ const complete = position === this.#text.length;
535402
+ return Object.freeze({ rows: Object.freeze(rows), from, through: position,
535403
+ complete, next: complete ? undefined : this.#cursor(position) });
535404
+ };
535405
+ for (const { segment } of this.#segmenter.segment(this.#text.slice(from))) {
535406
+ this.#assert();
535407
+ if (segment === '\n' || segment === '\r' || segment === '\r\n') {
535408
+ position += segment.length;
535409
+ flush();
535410
+ if (rows.length === maxRows) return result();
535411
+ continue;
535412
+ }
535413
+ const width = this.widthOf(segment);
535414
+ this.#assert();
535415
+ if (!Number.isSafeInteger(width) || width < 0 || width > columns) throw new Error('ORIGINAL_OUTPUT_COLUMN_LIMIT');
535416
+ if (rowColumns + width > columns) {
535417
+ flush();
535418
+ if (rows.length === maxRows) return result();
535419
+ }
535420
+ const count = Buffer.byteLength(segment, 'utf8');
535421
+ if (bytes + rowBytes + count > maxBytes) {
535422
+ if (row.length > 0) flush();
535423
+ if (rows.length === 0) throw new Error('ORIGINAL_OUTPUT_BYTE_LIMIT');
535424
+ return result();
535425
+ }
535426
+ row += segment;
535427
+ rowColumns += width;
535428
+ rowBytes += count;
535429
+ position += segment.length;
535430
+ }
535431
+ if (row.length > 0) flush();
535432
+ return result();
535433
+ }
535434
+
535435
+ dispose() {
535436
+ if (this.#closed) return;
535437
+ this.#closed = true;
535438
+ this.#text = '';
535439
+ this.#cursors = new WeakMap();
535440
+ this.owner.removeEventListener('abort', this.abort);
535441
+ }
535442
+ }
535443
+ async function createOriginalOutputSource(output, options, owner) {
535444
+ owner.throwIfAborted();
535445
+ options = Object.freeze({ ...options });
535446
+ for (const [name, maximum] of [['width', 16384], ['pageRows', 4096], ['maxPages', 64],
535447
+ ['maxRows', 4096], ['maxBytes', 8 * 1024 * 1024]]) {
535448
+ if (!Number.isSafeInteger(options[name]) || options[name] < 1 || options[name] > maximum) {
535449
+ throw new Error('ORIGINAL_OUTPUT_SOURCE_LIMIT');
535450
+ }
535451
+ }
535452
+ if (options.pageRows > options.maxRows || typeof options.assertCurrent !== 'function' || typeof output !== 'string') {
535453
+ throw new Error('ORIGINAL_OUTPUT_SOURCE_OPTIONS');
535454
+ }
535455
+ const cursors = [undefined];
535456
+ let pager;
535457
+ const source = new OriginalHistoryWindow({
535458
+ pageCount: 1, maxPages: options.maxPages, maxRows: options.maxRows, maxBytes: options.maxBytes,
535459
+ owner, assertCurrent: options.assertCurrent,
535460
+ load: (index, signal) => {
535461
+ signal.throwIfAborted();
535462
+ source.assert();
535463
+ if (!Object.hasOwn(cursors, index)) throw new Error('ORIGINAL_OUTPUT_PAGE_CURSOR');
535464
+ const page = pager.read(cursors[index], {
535465
+ columns: options.width, maxRows: options.pageRows, maxBytes: options.maxBytes,
535466
+ });
535467
+ if (!page.complete) {
535468
+ cursors[index + 1] ??= page.next;
535469
+ source.pageCount = Math.max(source.pageCount, index + 2);
535470
+ }
535471
+ return page.rows;
535472
+ },
535473
+ });
535474
+ const dispose = source.dispose.bind(source);
535475
+ source.dispose = () => { dispose(); pager?.dispose(); cursors.length = 0; };
535476
+ try {
535477
+ source.assert();
535478
+ const projected = projectSerializedToolImages(output, false, uiText('toolCall.output.truncated')).output;
535479
+ const display = sanitizeMcpDisplayText(projected);
535480
+ source.assert();
535481
+ pager = new OriginalOutputPager(display, { widthOf: visibleWidth,
535482
+ owner: source.controller.signal, assertCurrent: () => { source.assert(); } });
535483
+ await source.openLatest();
535484
+ source.assert();
535485
+ return source;
535486
+ } catch (error) { source.dispose(); throw error; }
535487
+ }
535488
+ function originalOutputChoices(records) {
535489
+ const calls = new Map(), outputs = [];
535490
+ for (let index = 0; index < records.length; index++) {
535491
+ const record = records[index];
535492
+ if (record.type !== 'message') continue;
535493
+ const message = record.message;
535494
+ if (message.role === 'assistant') {
535495
+ for (const call of message.toolCalls) calls.set(call.id, call.name);
535496
+ } else if (message.role === 'tool') {
535497
+ const name = calls.get(message.toolCallId) ?? '[tool]';
535498
+ outputs.push(Object.freeze({ value: String(index), recordIndex: index, toolCallId: message.toolCallId,
535499
+ label: `${outputs.length + 1} · ${sanitizeMcpDisplayText(name).slice(0, 80)}`, message }));
535500
+ calls.delete(message.toolCallId);
535501
+ }
535502
+ }
535503
+ return Object.freeze(outputs);
535504
+ }
535505
+ function chooseOriginalOutput(host, choices, owner, assertCurrent, open) {
535506
+ assertCurrent();
535507
+ owner.throwIfAborted();
535508
+ if (host.editorReplacementActive) return false;
535509
+ const byValue = new Map(choices.map(choice => [choice.value, choice]));
535510
+ let done = false, picker, generation;
535511
+ const owns = () => host.editorReplacement === picker && host.editorReplacementGeneration === generation;
535512
+ const current = () => {
535513
+ try { owner.throwIfAborted(); assertCurrent(); return true; } catch { return false; }
535514
+ };
535515
+ const release = () => { done = true; owner.removeEventListener('abort', abort); };
535516
+ const abort = () => {
535517
+ if (done) return;
535518
+ release();
535519
+ if (owns()) host.restoreEditor();
535520
+ };
535521
+ const finish = (value) => {
535522
+ if (done || !owns()) return false;
535523
+ if (!current()) { abort(); return false; }
535524
+ const chosen = value === undefined ? undefined : byValue.get(value);
535525
+ if (value !== undefined && !chosen) return false;
535526
+ release();
535527
+ if (!chosen) host.restoreEditor();
535528
+ else {
535529
+ const openingGeneration = host.editorReplacementGeneration + 1;
535530
+ host.restoreEditorAfter(async () => {
535531
+ const active = () => current() && host.editorReplacementGeneration === openingGeneration &&
535532
+ host.editorReplacement === undefined;
535533
+ if (!active()) return;
535534
+ try { await open(chosen, active); } catch (error) { if (active()) throw error; }
535535
+ });
535536
+ }
535537
+ return true;
535538
+ };
535539
+ picker = new ChoicePickerComponent({ title: uiText('originalOutput.choose'), searchable: true, pageSize: 5,
535540
+ options: choices.map(({ value, label }) => ({ value, label })),
535541
+ onSelect: value => { finish(value); }, onCancel: () => { finish(); },
535542
+ onCtrlS: () => { if (finish()) host.state.editor.onCtrlS?.(); },
535543
+ });
535544
+ const dispose = picker.dispose?.bind(picker);
535545
+ picker.dispose = () => { release(); dispose?.(); };
535546
+ try {
535547
+ owner.addEventListener('abort', abort, { once: true });
535548
+ assertCurrent();
535549
+ host.mountEditorReplacement(picker);
535550
+ generation = host.editorReplacementGeneration;
535551
+ if (done || !current()) {
535552
+ release();
535553
+ if (owns()) host.restoreEditor();
535554
+ return false;
535555
+ }
535556
+ return true;
535557
+ } catch (error) {
535558
+ release();
535559
+ if (host.editorReplacement === picker) generation = host.editorReplacementGeneration;
535560
+ if (owns()) host.restoreEditor();
535561
+ throw error;
535562
+ }
535563
+ }
535564
+ function installOriginalOutputSelection(input, renderer, records, owner, assertCurrent, width) {
535565
+ const host = renderer.host, controller = input.controller, historyFactory = controller.binding.createSource;
535566
+ const historyError = controller.onError;
535567
+ let detail = false, detailCurrent = () => true;
535568
+ const restoreHistory = () => {
535569
+ if (!detail) return;
535570
+ detail = false;
535571
+ controller.onError = historyError;
535572
+ try { assertCurrent(); controller.bind(historyFactory, owner, assertCurrent); } catch { /* A new owner takes over. */ }
535573
+ };
535574
+ input.onExit = restoreHistory;
535575
+ input.onToolOutput = () => {
535576
+ assertCurrent();
535577
+ const choices = originalOutputChoices(records);
535578
+ if (choices.length === 0) { host.showStatus(uiText('originalOutput.empty'), 'warning'); return; }
535579
+ if (host.editorReplacementActive) return;
535580
+ controller.close();
535581
+ restoreHistory();
535582
+ chooseOriginalOutput(host, choices, owner, assertCurrent, async (choice, active) => {
535583
+ assertCurrent();
535584
+ if (!active()) return;
535585
+ detail = true;
535586
+ detailCurrent = active;
535587
+ let reported = false;
535588
+ controller.onError = error => {
535589
+ reported = true;
535590
+ if (detailCurrent()) historyError(error);
535591
+ restoreHistory();
535592
+ };
535593
+ const assertDetail = () => {
535594
+ assertCurrent();
535595
+ if (!active()) throw new Error('ORIGINAL_OUTPUT_VIEW_CHANGED');
535596
+ };
535597
+ try {
535598
+ controller.bind((signal, assertActive) => createOriginalOutputSource(toolResultOutput(choice.message.content), {
535599
+ width, pageRows: 128, maxPages: 3, maxRows: 4096, maxBytes: 8 * 1024 * 1024,
535600
+ assertCurrent: () => { assertDetail(); assertActive(); },
535601
+ }, signal), owner, assertDetail);
535602
+ await controller.home();
535603
+ } catch (error) {
535604
+ restoreHistory();
535605
+ if (!reported) throw error;
535606
+ }
535607
+ });
535608
+ };
535609
+ }
535610
+ function registerOriginalOutputCopy() {
535611
+ registerUiCatalogFragment({
535612
+ en: { 'originalOutput.choose': 'Choose a saved tool output',
535613
+ 'originalOutput.empty': 'No tool outputs are saved in this snapshot.' },
535614
+ de: { 'originalOutput.choose': 'Gespeicherte Werkzeugausgabe wählen',
535615
+ 'originalOutput.empty': 'In diesem gespeicherten Verlauf gibt es keine Werkzeugausgaben.' },
535616
+ });
535617
+ }
534539
535618
  function createReplayRenderContext() {
534540
535619
  return {
534541
535620
  turnIndex: 0,
@@ -539752,25 +540831,37 @@ function extractBashTag(text, tag) {
539752
540831
  function unescapeBashXml(text) {
539753
540832
  return text.replaceAll("&lt;", "<").replaceAll("&gt;", ">").replaceAll("&quot;", "\"").replaceAll("&amp;", "&");
539754
540833
  }
539755
- function embeddedPageStart(records, end, limit) {
539756
- if (end === 0) return 0;
539757
- const boundaries = [0];
539758
- const pending = /* @__PURE__ */ new Set();
539759
- let messages = 0;
539760
- let cutoff = 0;
539761
- for (let i = end - 1; i >= 0; i--) if (records[i].type === "message" && ++messages >= limit) {
539762
- cutoff = i;
539763
- break;
539764
- }
539765
- for (let i = 0; i <= cutoff; i++) {
539766
- const record = records[i];
539767
- if (record.type !== "message") continue;
539768
- const message = record.message;
539769
- if (message.role === "user" && pending.size === 0) boundaries.push(i);
539770
- for (const tool of message.toolCalls) pending.add(tool.id);
539771
- if (message.role === "tool" && message.toolCallId) pending.delete(message.toolCallId);
539772
- }
539773
- return boundaries.at(-1);
540834
+ function createEmbeddedHistoryPageIndex(records) {
540835
+ const pending = new Set();
540836
+ const starts = [0];
540837
+ for (let index = 0; index < records.length; index++) {
540838
+ const record = records[index];
540839
+ if (index > 0 && pending.size === 0 && (record.type !== 'message' || record.message.role !== 'tool')) starts.push(index);
540840
+ if (record.type !== 'message') continue;
540841
+ const message = record.message;
540842
+ for (const tool of message.role === 'assistant' ? message.toolCalls : []) {
540843
+ if (typeof tool.id === 'string' && tool.id.length > 0 && typeof tool.name === 'string' && tool.name.length > 0) {
540844
+ pending.add(tool.id);
540845
+ }
540846
+ }
540847
+ if (message.role === 'tool' && message.toolCallId) pending.delete(message.toolCallId);
540848
+ }
540849
+ return Object.freeze({ records, length: records.length, starts: Object.freeze(starts) });
540850
+ }
540851
+ function embeddedPageStart(records, end, limit, index) {
540852
+ if (!Number.isSafeInteger(end) || end < 0 || end > records.length ||
540853
+ !Number.isSafeInteger(limit) || limit < 1) throw new Error('INVALID_HISTORY_PAGE_RANGE');
540854
+ if (end === 0) return 0;
540855
+ const pages = index ?? createEmbeddedHistoryPageIndex(records);
540856
+ if (pages.records !== records || pages.length !== records.length) throw new Error('HISTORY_PAGE_SOURCE_CHANGED');
540857
+ const cutoff = Math.max(0, end - limit);
540858
+ let left = 0, right = pages.starts.length;
540859
+ while (left + 1 < right) {
540860
+ const middle = Math.floor((left + right) / 2);
540861
+ if (pages.starts[middle] <= cutoff) left = middle;
540862
+ else right = middle;
540863
+ }
540864
+ return pages.starts[left];
539774
540865
  }
539775
540866
  function isResumeNormalizationGoalPause(change) {
539776
540867
  return change.status === "paused" && change.reason !== void 0 && RESUME_NORMALIZATION_GOAL_PAUSE_REASONS.has(change.reason);
@@ -539868,12 +540959,16 @@ var init_session_replay = __esmMin((() => {
539868
540959
  renderer.cleanupRuntime(context);
539869
540960
  });
539870
540961
  }
539871
- prepareEmbeddedHistory(session, records, owner) {
539872
- return this.prepareHistory(session, owner, (renderer) => {
539873
- const context = createReplayRenderContext();
540962
+ prepareEmbeddedHistory(session, records, owner, cursor = createReplayRenderContext()) {
540963
+ const context = cloneReplayRenderContext(cursor);
540964
+ const page = this.prepareHistory(session, owner, (renderer) => {
540965
+ if (cursor.originalTurnPrefix !== undefined) renderer.turnPrefix = cursor.originalTurnPrefix;
540966
+ if (cursor.originalSeenSkill) renderer.host.sessionEventHandler.renderedSkillActivationIds = originalReplaySeenSet(cursor.originalSeenSkill);
540967
+ if (cursor.originalSeenCommand) renderer.host.sessionEventHandler.renderedPluginCommandActivationIds = originalReplaySeenSet(cursor.originalSeenCommand);
539874
540968
  for (const record of records) renderer.renderRecord(context, record);
539875
540969
  renderer.cleanupRuntime(context);
539876
540970
  });
540971
+ return { ...page, continuationContext: context };
539877
540972
  }
539878
540973
  prepareHistory(session, owner, render) {
539879
540974
  owner.throwIfAborted();
@@ -539968,6 +541063,12 @@ var init_session_replay = __esmMin((() => {
539968
541063
  owner.addEventListener("abort", dispose, { once: true });
539969
541064
  return {
539970
541065
  dispose,
541066
+ readOriginalLines: (width, limits) => {
541067
+ if (disposed || transferred) throw new Error("ORIGINAL_HISTORY_PAGE_CLOSED");
541068
+ const rows = readOriginalHistoryLines(container.children, width, limits, owner);
541069
+ if (disposed || transferred) throw new Error("ORIGINAL_HISTORY_PAGE_CLOSED");
541070
+ return rows;
541071
+ },
539971
541072
  commit: () => {
539972
541073
  owner.throwIfAborted();
539973
541074
  if (disposed || transferred) throw new Error("GATEWAY_HISTORY_PAGE_CLOSED");
@@ -540096,12 +541197,14 @@ var init_session_replay = __esmMin((() => {
540096
541197
  }
540097
541198
  }
540098
541199
  renderAgentSnapshot(session, agent) {
541200
+ this.host.scrollbackController?.invalidateOriginalHistory?.();
540099
541201
  this.embeddedHistoryOwner?.abort();
540100
541202
  this.host.scrollbackController.prepareSessionReplay(session, agent);
540101
541203
  this.hydrateSnapshot(agent);
540102
541204
  const options = this.host.getReplayHistoryOptions?.(session);
540103
541205
  const replay = [...agent.replay];
540104
- let start = options ? embeddedPageStart(replay, replay.length, options.limit) : 0;
541206
+ const pages = options ? createEmbeddedHistoryPageIndex(replay) : undefined;
541207
+ let start = options ? embeddedPageStart(replay, replay.length, options.limit, pages) : 0;
540105
541208
  this.renderRecords(agent, replay.slice(start));
540106
541209
  this.applyTerminalBackgroundAgentStatuses(agent);
540107
541210
  this.host.mergeAllTurnSteps();
@@ -540111,7 +541214,7 @@ var init_session_replay = __esmMin((() => {
540111
541214
  this.host.scrollbackController.bindHistoryPaging(session, async () => {
540112
541215
  if (owner.signal.aborted || !options.isCurrent()) return "superseded";
540113
541216
  if (start === 0) return "complete";
540114
- const next = embeddedPageStart(replay, start, options.limit);
541217
+ const next = embeddedPageStart(replay, start, options.limit, pages);
540115
541218
  const page = this.prepareEmbeddedHistory(session, replay.slice(next, start), owner.signal);
540116
541219
  try {
540117
541220
  if (owner.signal.aborted || !options.isCurrent()) return "superseded";
@@ -540128,6 +541231,7 @@ var init_session_replay = __esmMin((() => {
540128
541231
  }
540129
541232
  }, owner.signal, (error) => this.host.showError(formatErrorMessage$2(error)));
540130
541233
  }
541234
+ bindOriginalHistorySnapshot(this, session, agent, options, isExperimentalFlagEnabled("original_history"));
540131
541235
  }
540132
541236
  hydrateSnapshot(agent) {
540133
541237
  this.host.setAppState(appStateFromResumeAgent(agent));
@@ -540183,8 +541287,7 @@ var init_session_replay = __esmMin((() => {
540183
541287
  state.footer.setBackgroundCounts(countActiveBackgroundTasks(sessionEventHandler.backgroundTasks));
540184
541288
  state.ui.requestRender();
540185
541289
  }
540186
- renderRecords(agent, records = agent.replay) {
540187
- const context = createReplayRenderContext();
541290
+ renderRecords(agent, records = agent.replay, context = createReplayRenderContext()) {
540188
541291
  for (const record of records) this.renderRecord(context, record);
540189
541292
  this.flushAssistant(context);
540190
541293
  this.cleanupRuntime(context);
@@ -541029,6 +542132,7 @@ var init_gateway_session = __esmMin((() => {
541029
542132
  this.unbindHistory?.();
541030
542133
  this.unbindHistory = void 0;
541031
542134
  if (this.session && this.session !== session) throw new Error("GATEWAY_VIEW_SCOPE_CHANGED");
542135
+ this.host.invalidateOriginalHistory?.(session);
541032
542136
  this.session = session;
541033
542137
  this.history = {
541034
542138
  revision: snapshot.messages.history_revision,
@@ -541056,6 +542160,7 @@ var init_gateway_session = __esmMin((() => {
541056
542160
  if (event.volatile !== true || !isPresentationDelta(event.type)) this.historyOwner?.abort();
541057
542161
  if (event.type === "agent.context.reset") {
541058
542162
  const reset = decodeGatewayAgentEvent(event);
542163
+ this.host.invalidateOriginalHistory?.(this.session, reset.agentId);
541059
542164
  this.resetPending ||= reset.agentId === "main";
541060
542165
  return true;
541061
542166
  }
@@ -541107,6 +542212,7 @@ var init_gateway_session = __esmMin((() => {
541107
542212
  this.owner.signal.throwIfAborted();
541108
542213
  if (!this.ready || this.session !== session || snapshot.session.id !== session.id || snapshot.in_flight_turn !== null) throw new Error("GATEWAY_VIEW_SCOPE_CHANGED");
541109
542214
  this.host.assertSessionOwner(session, this.owner.signal);
542215
+ this.host.invalidateOriginalHistory?.(session);
541110
542216
  this.historyOwner?.abort();
541111
542217
  try {
541112
542218
  applyGatewaySessionReceipt(apply);
@@ -546852,6 +547958,7 @@ releaseChannelQueueAtSafePoint() {
546852
547958
  this.scheduleQueueDrain();
546853
547959
  }
546854
547960
  acceptSessionReplayEvent(session, event) {
547961
+ observeOriginalHistoryReset(this, session, event);
546855
547962
  if (!isExperimentalFlagEnabled("queue_policies") && !(session.connectionKind === "gateway" && isSlashCommandEnabled({
546856
547963
  name: "reset",
546857
547964
  experimentalFlag: "queue_policies"
@@ -547878,6 +548985,7 @@ releaseChannelQueueAtSafePoint() {
547878
548985
  if (phase !== "idle" && expectedScope === void 0) throw new Error("RESET_CONTEXT_SCOPE_UNAVAILABLE");
547879
548986
  const cancellation = {};
547880
548987
  this.queueInterruptCancellations.add(cancellation);
548988
+ this.scrollbackController?.invalidateOriginalHistory?.();
547881
548989
  try {
547882
548990
  await this.withInteractiveAgent(agentId, () => shell !== void 0 ? session.resetContext({
547883
548991
  expectedShellCommandId: shell.commandId,
@@ -548669,6 +549777,7 @@ releaseChannelQueueAtSafePoint() {
548669
549777
  this.state.terminal.setTitle(label);
548670
549778
  }
548671
549779
  resetSessionRuntime() {
549780
+ this.scrollbackController?.invalidateOriginalHistory?.();
548672
549781
  this.shellOutputStreams.clear();
548673
549782
  this.sessionBindingRequest = void 0;
548674
549783
  this.sessionListRequest = void 0;
@@ -549112,6 +550221,9 @@ releaseChannelQueueAtSafePoint() {
549112
550221
  };
549113
550222
  return {
549114
550223
  ...handlers,
550224
+ invalidateOriginalHistory: (session, agentId) => {
550225
+ if (this.session === session && (agentId === undefined || agentId === this.interactiveAgentId)) this.scrollbackController?.invalidateOriginalHistory?.();
550226
+ },
549115
550227
  approvalController: this.approvalController,
549116
550228
  questionController: this.questionController,
549117
550229
  onQuestionSettled: (kind) => this.showStatus(kind === "answered" ? "/question ✓" : "/question ×"),
@@ -549287,6 +550399,7 @@ releaseChannelQueueAtSafePoint() {
549287
550399
  for (const child of this.state.transcriptContainer.children) if (hasDispose(child)) child.dispose();
549288
550400
  }
549289
550401
  clearTranscriptAndRedraw() {
550402
+ this.scrollbackController?.invalidateOriginalHistory?.();
549290
550403
  this.streamingUI.discardPending();
549291
550404
  this.scrollbackController.reset();
549292
550405
  this.state.transcriptEntries = [];
@@ -549305,6 +550418,7 @@ releaseChannelQueueAtSafePoint() {
549305
550418
  this.state.ui.requestRender(true);
549306
550419
  }
549307
550420
  prepareReplayTranscript() {
550421
+ this.scrollbackController?.invalidateOriginalHistory?.();
549308
550422
  this.disposeTranscriptChildren();
549309
550423
  this.state.transcriptEntries = [];
549310
550424
  this.state.transcriptContainer.clear();
@@ -563331,7 +564445,7 @@ function readInstalledStore(filePath) {
563331
564445
  };
563332
564446
  let parsed;
563333
564447
  try {
563334
- parsed = JSON.parse(readFileSync(filePath, "utf8"));
564448
+ parsed = JSON.parse(readFileSync(filePath, "utf8").replace(/^\uFEFF/u, ''));
563335
564449
  } catch (error) {
563336
564450
  throw new Error(`Failed to parse ${filePath}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
563337
564451
  }
@@ -563905,60 +565019,68 @@ async function t3458WithConfigLock(filePath, action, learning = false) {
563905
565019
  }
563906
565020
  }
563907
565021
  }
565022
+ function t3458KnownEndpoint(endpoint) {
565023
+ return endpoint === 'https://api.blun.ai/v1' || endpoint === 'https://api.blun.ai/coding/v1';
565024
+ }
565025
+ function t3458LimitEntry(value, endpoint, now = Date.now()) {
565026
+ if (value !== null && typeof value === 'object') {
565027
+ if (value.version !== 1 || t3458Learned(value.limit) === undefined ||
565028
+ !Number.isSafeInteger(value.observedAt) || value.observedAt <= 0 || value.observedAt > now ||
565029
+ now - value.observedAt >= 15 * 60 * 1000) return undefined;
565030
+ return { version: 1, limit: value.limit, observedAt: value.observedAt };
565031
+ }
565032
+ const limit = t3458Learned(value);
565033
+ if (limit === undefined || t3458KnownEndpoint(endpoint) && limit === 500000) return undefined;
565034
+ return { version: 0, limit, observedAt: 0 };
565035
+ }
565036
+ function t3458LatestEntry(left, right) {
565037
+ if (left === undefined) return right;
565038
+ if (right === undefined) return left;
565039
+ if (left.observedAt !== right.observedAt) return left.observedAt > right.observedAt ? left : right;
565040
+ return left.limit <= right.limit ? left : right;
565041
+ }
563908
565042
  function t3458Store(filePath, parseToml, stringifyToml, atomicWrite) {
563909
- return {
563910
- async load(key) {
563911
- try {
563912
- return t3458Learned(parseToml(await t3458Fs.readFile(filePath, 'utf8')).request_body_byte_limits?.[key]);
563913
- }
563914
- catch (error) {
563915
- if (error.code === 'ENOENT')
563916
- return undefined;
563917
- throw error;
563918
- }
563919
- },
563920
- async save(key, value) {
563921
- if (!/^[a-f0-9]{64}$/.test(key) || t3458Learned(value) === undefined)
563922
- return;
563923
- await t3458WithConfigLock(filePath, async () => {
563924
- let data;
563925
- try {
563926
- data = parseToml(await t3458Fs.readFile(filePath, 'utf8'));
563927
- }
563928
- catch (error) {
563929
- if (error.code !== 'ENOENT')
563930
- throw error;
563931
- data = {};
563932
- }
563933
- const table = data.request_body_byte_limits ?? {};
563934
- const previous = t3458Learned(table[key]);
563935
- data.request_body_byte_limits = { ...table, [key]: previous === undefined ? value : Math.min(previous, value) };
563936
- await atomicWrite(filePath, `${stringifyToml(data)}\n`);
563937
- }, true);
563938
- }
563939
- };
565043
+ return {
565044
+ async load(key) {
565045
+ try { return parseToml(await t3458Fs.readFile(filePath, 'utf8')).request_body_byte_limits?.[key]; }
565046
+ catch (error) { if (error.code === 'ENOENT') return undefined; throw error; }
565047
+ },
565048
+ async save(key, value) {
565049
+ const now = Date.now();
565050
+ const incoming = typeof value === 'number' ? t3458LimitEntry({ version: 1, limit: value, observedAt: now }, undefined, now) :
565051
+ t3458LimitEntry(value, undefined, now);
565052
+ if (!/^[a-f0-9]{64}$/.test(key) || incoming?.version !== 1) return;
565053
+ await t3458WithConfigLock(filePath, async () => {
565054
+ let data;
565055
+ try { data = parseToml(await t3458Fs.readFile(filePath, 'utf8')); }
565056
+ catch (error) { if (error.code !== 'ENOENT') throw error; data = {}; }
565057
+ const table = data.request_body_byte_limits ?? {};
565058
+ if (typeof table !== 'object' || table === null || Array.isArray(table)) throw new Error('INVALID_BYTE_LIMIT_TABLE');
565059
+ const previous = t3458LimitEntry(table[key], undefined, Date.now());
565060
+ data.request_body_byte_limits = { ...table, [key]: t3458LatestEntry(previous, incoming) };
565061
+ await atomicWrite(filePath, `${stringifyToml(data)}\n`);
565062
+ }, true);
565063
+ },
565064
+ };
563940
565065
  }
563941
565066
  async function t3458Measure(provider, params, options) {
563942
- const endpoint = t3458Endpoint(provider._baseUrl);
563943
- const key = t3458Key(provider._baseUrl);
563944
- const option = typeof provider._requestBodyByteLimit === 'function' ? provider._requestBodyByteLimit() : provider._requestBodyByteLimit;
563945
- const configured = t3458ValidLimit(options?.requestBodyBudget?.limitBytes) ?? t3458ValidLimit(option) ?? t3458ValidLimit(Number(process.env.BLUN_REQUEST_BODY_BYTE_LIMIT));
563946
- let persisted;
563947
- if (key !== undefined && provider._requestBodyByteLimitStore !== undefined) {
563948
- try {
563949
- persisted = t3458Learned(await provider._requestBodyByteLimitStore.load(key));
563950
- }
563951
- catch { }
563952
- }
563953
- const learned = t3458Learned(provider._t3458ObservedLimit);
563954
- const observed = learned === undefined ? persisted : persisted === undefined ? learned : Math.min(learned, persisted);
563955
- const fallback = endpoint === 'https://api.blun.ai/coding/v1' ? 500000 : undefined;
563956
- const limit = configured === undefined ? observed ?? fallback : observed === undefined ? configured : Math.min(configured, observed);
563957
- const bytes = Buffer.byteLength(JSON.stringify(params), 'utf8');
563958
- options?.requestBodyBudget?.onMeasured?.(bytes, limit, endpoint);
563959
- if (!options?.isCompactionRequest && limit !== undefined && bytes >= limit)
563960
- throw t3458Pressure(bytes, limit, endpoint);
563961
- return { key, limit, bytes };
565067
+ const endpoint = t3458Endpoint(provider._baseUrl), key = t3458Key(provider._baseUrl);
565068
+ const option = typeof provider._requestBodyByteLimit === 'function' ? provider._requestBodyByteLimit() : provider._requestBodyByteLimit;
565069
+ const configured = t3458ValidLimit(options?.requestBodyBudget?.limitBytes) ?? t3458ValidLimit(option) ??
565070
+ t3458ValidLimit(Number(process.env.BLUN_REQUEST_BODY_BYTE_LIMIT));
565071
+ let saved;
565072
+ if (key !== undefined && provider._requestBodyByteLimitStore !== undefined) {
565073
+ try { saved = await provider._requestBodyByteLimitStore.load(key); } catch { /* Best effort. */ }
565074
+ }
565075
+ const now = Date.now(), persisted = t3458LimitEntry(saved, endpoint, now);
565076
+ const runtimeValue = Object.hasOwn(provider, '_t3458ObservedLimitEntry') ? provider._t3458ObservedLimitEntry : provider._t3458ObservedLimit;
565077
+ const observed = t3458LatestEntry(t3458LimitEntry(runtimeValue, endpoint, now), persisted);
565078
+ const fallback = t3458KnownEndpoint(endpoint) ? 700000 : undefined;
565079
+ const limit = configured === undefined ? observed?.limit ?? fallback : observed === undefined ? configured : Math.min(configured, observed.limit);
565080
+ const bytes = Buffer.byteLength(JSON.stringify(params), 'utf8');
565081
+ options?.requestBodyBudget?.onMeasured?.(bytes, limit, endpoint);
565082
+ if (!options?.isCompactionRequest && limit !== undefined && bytes >= limit) throw t3458Pressure(bytes, limit, endpoint);
565083
+ return { key, limit, bytes };
563962
565084
  }
563963
565085
  function t3458Pressure(byteLength, limitBytes, endpoint) {
563964
565086
  const error = new ChatProviderError(`Request body ${byteLength} bytes reaches limit ${limitBytes} bytes.`);
@@ -563980,15 +565102,16 @@ function t3458Observed(error) {
563980
565102
  return match === null ? undefined : t3458Learned(Number(match[1]));
563981
565103
  }
563982
565104
  async function t3458Learn(provider, error, measured, options) {
563983
- const limit = t3458Observed(error);
563984
- if (limit === undefined)
563985
- return;
563986
- provider._t3458ObservedLimit = Math.min(t3458Learned(provider._t3458ObservedLimit) ?? Infinity, limit);
563987
- options?.requestBodyBudget?.onLimitObserved?.(limit);
563988
- if (measured.key !== undefined && provider._requestBodyByteLimitStore !== undefined) {
563989
- try {
563990
- await provider._requestBodyByteLimitStore.save(measured.key, limit);
563991
- }
563992
- catch { }
563993
- }
565105
+ const limit = t3458Observed(error);
565106
+ if (limit === undefined) return;
565107
+ const now = Date.now(), incoming = { version: 1, limit, observedAt: now };
565108
+ const endpoint = t3458Endpoint(provider._baseUrl);
565109
+ const previous = Object.hasOwn(provider, '_t3458ObservedLimitEntry') ? provider._t3458ObservedLimitEntry : provider._t3458ObservedLimit;
565110
+ const entry = t3458LatestEntry(t3458LimitEntry(previous, endpoint, now), incoming);
565111
+ provider._t3458ObservedLimitEntry = entry;
565112
+ provider._t3458ObservedLimit = entry.limit;
565113
+ options?.requestBodyBudget?.onLimitObserved?.(limit);
565114
+ if (measured.key !== undefined && provider._requestBodyByteLimitStore !== undefined) {
565115
+ try { await provider._requestBodyByteLimitStore.save(measured.key, incoming); } catch { /* Best effort. */ }
565116
+ }
563994
565117
  }