blun-king-cli 9.1.640 → 9.1.642

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
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- // BLUN_BUILD_INPUT_SHA256:4ddd869ff27cd786caab65fef2e4a43ddeb636eb25fdea7ff03b52a5a716faab
2
+ // BLUN_BUILD_INPUT_SHA256:e50c78300e52dc6fc7d8003478fe2fa01fe7fdff8b1a749e108e6627de244e7e
3
3
  /*! wasm-webp 0.1.0
4
4
  MIT License
5
5
 
@@ -21190,6 +21190,7 @@ var init_commands$1 = __esmMin((() => {
21190
21190
  }));
21191
21191
  var init_types$20 = __esmMin((() => {}));
21192
21192
  var FLAG_DEFINITIONS;
21193
+ var InputControl, controls, CHANNEL_QUEUE_DEADLINE_MS, QueueDeadlineWatchdog, StoppedInputScopes, SEARCH_LIMITS, SearchStop, active, inside, sessionSearchRequests, ActiveInputDelivery;
21193
21194
  var init_registry$4 = __esmMin((() => {
21194
21195
  FLAG_DEFINITIONS = [
21195
21196
  {
@@ -21533,7 +21534,7 @@ var init_registry$4 = __esmMin((() => {
21533
21534
  title: "Session queue policies",
21534
21535
  description: "Apply explicitly persisted session queue admission rules.",
21535
21536
  env: "BLUN_EXPERIMENTAL_QUEUE_POLICIES",
21536
- default: false,
21537
+ default: true,
21537
21538
  surface: "core"
21538
21539
  },
21539
21540
  {
@@ -29909,6 +29910,62 @@ var init_task$3 = __esmMin((() => {
29909
29910
  ]);
29910
29911
  }));
29911
29912
  var DenyAllPermissionPolicy;
29913
+ function inputControl(signal) {
29914
+ let control = controls.get(signal);
29915
+ if (control === void 0) {
29916
+ control = new InputControl();
29917
+ controls.set(signal, control);
29918
+ }
29919
+ return control;
29920
+ }
29921
+ function inheritInputControl(signal, control) {
29922
+ if (control !== void 0) controls.set(signal, control);
29923
+ }
29924
+ var init_input_control = __esmMin((() => {
29925
+ init_abort();
29926
+ InputControl = class {
29927
+ epoch = 0;
29928
+ stopped = false;
29929
+ provider;
29930
+ preparations = /* @__PURE__ */ new Set();
29931
+ listeners = /* @__PURE__ */ new Set();
29932
+ onChange(listener) {
29933
+ this.listeners.add(listener);
29934
+ return () => {
29935
+ this.listeners.delete(listener);
29936
+ };
29937
+ }
29938
+ changed(stop = false) {
29939
+ this.epoch++;
29940
+ this.stopped ||= stop;
29941
+ this.provider?.abort(new DOMException("INPUT_SUPERSEDED", "AbortError"));
29942
+ for (const controller of this.preparations) controller.abort(new DOMException("INPUT_SUPERSEDED", "AbortError"));
29943
+ for (const listener of this.listeners) listener();
29944
+ }
29945
+ async prepare(signal, operation) {
29946
+ const controller = new AbortController();
29947
+ this.preparations.add(controller);
29948
+ const preparationSignal = AbortSignal.any([signal, controller.signal]);
29949
+ try {
29950
+ return await abortable(Promise.resolve().then(() => {
29951
+ preparationSignal.throwIfAborted();
29952
+ return operation(preparationSignal);
29953
+ }), preparationSignal);
29954
+ } finally {
29955
+ this.preparations.delete(controller);
29956
+ }
29957
+ }
29958
+ beginProvider() {
29959
+ const controller = new AbortController();
29960
+ this.provider = controller;
29961
+ return controller;
29962
+ }
29963
+ endProvider(controller) {
29964
+ if (this.provider === controller) this.provider = void 0;
29965
+ }
29966
+ };
29967
+ controls = /* @__PURE__ */ new WeakMap();
29968
+ }));
29912
29969
  var init_deny_all = __esmMin((() => {
29913
29970
  DenyAllPermissionPolicy = class {
29914
29971
  message;
@@ -30235,8 +30292,11 @@ var init_persistence$1 = __esmMin((() => {
30235
30292
  this.shouldClear = false;
30236
30293
  const content = (this.options.blobStore !== void 0 ? await Promise.all(batch.map((record) => this.options.blobStore.offload(record))) : batch).map((e) => JSON.stringify(e) + "\n").join("");
30237
30294
  const directory = dirname$3(this.filePath);
30238
- await mkdir(directory, { recursive: true });
30239
- const fh = await open(this.filePath, shouldClear ? "w" : "a");
30295
+ await mkdir(directory, {
30296
+ recursive: true,
30297
+ mode: 448
30298
+ });
30299
+ const fh = await open(this.filePath, shouldClear ? "w" : "a", 384);
30240
30300
  try {
30241
30301
  const before = await fh.stat();
30242
30302
  if (shouldClear || before.size === 0) this.persistedRecordCount = 0;
@@ -183784,10 +183844,17 @@ IMPORTANT:
183784
183844
  - If you do not know the answer, say so directly.
183785
183845
  `;
183786
183846
  nativeExecutionCompletions = /* @__PURE__ */ new WeakMap();
183787
- SessionSubagentHost = class {
183847
+ init_input_control();
183848
+ SessionSubagentHost = class {
183788
183849
  session;
183789
183850
  ownerAgentId;
183790
- admissionClosed = false;
183851
+ inputLeases = /* @__PURE__ */ new WeakMap();
183852
+ assertInputLease(options) {
183853
+ const lease = this.inputLeases.get(options);
183854
+ if (lease?.active?.runInBackground) return;
183855
+ if (lease !== void 0 && (lease.control.stopped || lease.control.epoch !== lease.epoch)) throw new DOMException("INPUT_SUPERSEDED", "AbortError");
183856
+ }
183857
+ admissionClosed = false;
183791
183858
  operations = new ExecutionLedger();
183792
183859
  childExecutions = new ExecutionLedger();
183793
183860
  preparedDisposers = /* @__PURE__ */ new Set();
@@ -183822,8 +183889,16 @@ IMPORTANT:
183822
183889
  assertAdmissionOpen() {
183823
183890
  if (this.admissionClosed) throw new Error("Subagent admission is closed for quiescence");
183824
183891
  }
183825
- runOperation(id, operation) {
183892
+ runOperation(id, operation, input) {
183826
183893
  this.assertAdmissionOpen();
183894
+ if (input !== void 0) {
183895
+ const control = inputControl(input.signal);
183896
+ this.inputLeases.set(input, {
183897
+ control,
183898
+ epoch: control.epoch
183899
+ });
183900
+ this.assertInputLease(input);
183901
+ }
183827
183902
  const completion = operation();
183828
183903
  this.operations.track(id, completion);
183829
183904
  return completion;
@@ -183857,7 +183932,7 @@ IMPORTANT:
183857
183932
  return this.session.getReadyAgent(currentId);
183858
183933
  }
183859
183934
  async spawn(options) {
183860
- return this.runOperation("spawn", () => this.spawnInner(options));
183935
+ return this.runOperation("spawn", () => this.spawnInner(options), options);
183861
183936
  }
183862
183937
  async spawnInner(options) {
183863
183938
  options.signal.throwIfAborted();
@@ -183889,7 +183964,7 @@ IMPORTANT:
183889
183964
  });
183890
183965
  }
183891
183966
  async resume(agentId, options) {
183892
- return this.runOperation("resume", () => this.resumeInner(agentId, options));
183967
+ return this.runOperation("resume", () => this.resumeInner(agentId, options), options);
183893
183968
  }
183894
183969
  async resumeInner(agentId, options) {
183895
183970
  options.signal.throwIfAborted();
@@ -183916,7 +183991,7 @@ IMPORTANT:
183916
183991
  });
183917
183992
  }
183918
183993
  async retry(agentId, options) {
183919
- return this.runOperation("retry", () => this.retryInner(agentId, options));
183994
+ return this.runOperation("retry", () => this.retryInner(agentId, options), options);
183920
183995
  }
183921
183996
  async retryInner(agentId, options) {
183922
183997
  options.signal.throwIfAborted();
@@ -183928,6 +184003,7 @@ IMPORTANT:
183928
184003
  modelAlias: parent.config.modelAlias,
183929
184004
  actionStyle: parent.config.actionStyle
183930
184005
  });
184006
+ this.assertInputLease(runOptions);
183931
184007
  this.emitSubagentStarted(parent, agentId);
183932
184008
  if (child.turn.retry("agent-host") === null) throw new Error(`Agent instance "${agentId}" could not start a retry turn`);
183933
184009
  this.observeFirstRequest(child, runOptions);
@@ -184042,7 +184118,7 @@ IMPORTANT:
184042
184118
  completion,
184043
184119
  update: (message) => this.updateActiveRun(agentId, completion, message)
184044
184120
  });
184045
- })
184121
+ }, options)
184046
184122
  };
184047
184123
  } catch (error) {
184048
184124
  await dispose();
@@ -184130,6 +184206,7 @@ IMPORTANT:
184130
184206
  }
184131
184207
  runWithActiveChild(childId, options, run) {
184132
184208
  this.assertAdmissionOpen();
184209
+ this.assertInputLease(options);
184133
184210
  if (this.activeChildren.has(childId)) throw new Error(`Agent instance "${childId}" is already running`);
184134
184211
  const controller = new AbortController();
184135
184212
  const unlinkAbortSignal = linkAbortSignal(options.signal, controller);
@@ -184138,10 +184215,22 @@ IMPORTANT:
184138
184215
  runInBackground: options.runInBackground
184139
184216
  };
184140
184217
  this.activeChildren.set(childId, active);
184141
- const completion = run({
184218
+ const runOptions = {
184142
184219
  ...options,
184143
184220
  signal: controller.signal
184144
- }).finally(() => {
184221
+ };
184222
+ const lease = this.inputLeases.get(options);
184223
+ if (lease !== void 0) {
184224
+ lease.active = active;
184225
+ this.inputLeases.set(runOptions, lease);
184226
+ }
184227
+ const unlinkInput = lease?.control.onChange(() => {
184228
+ if (active.runInBackground) return;
184229
+ const child = this.session.getReadyAgent(childId);
184230
+ if (child !== void 0) child.turn.stop(child.turn.currentId);
184231
+ });
184232
+ const completion = run(runOptions).finally(() => {
184233
+ unlinkInput?.();
184145
184234
  unlinkAbortSignal();
184146
184235
  if (this.activeChildren.get(childId) === active) this.activeChildren.delete(childId);
184147
184236
  });
@@ -184167,6 +184256,7 @@ IMPORTANT:
184167
184256
  }
184168
184257
  async runPromptTurn(parent, childId, child, profileName, options) {
184169
184258
  options.signal.throwIfAborted();
184259
+ this.assertInputLease(options);
184170
184260
  await this.triggerSubagentStart(parent, profileName, options.prompt, options.signal);
184171
184261
  options.signal.throwIfAborted();
184172
184262
  let childPrompt = options.prompt;
@@ -184174,6 +184264,7 @@ IMPORTANT:
184174
184264
  const gitContext = await collectGitContext(child.kaos, child.config.cwd);
184175
184265
  if (gitContext) childPrompt = `${gitContext}\n\n${childPrompt}`;
184176
184266
  }
184267
+ this.assertInputLease(options);
184177
184268
  this.emitSubagentStarted(parent, childId);
184178
184269
  if (child.turn.prompt([{
184179
184270
  type: "text",
@@ -184189,6 +184280,7 @@ IMPORTANT:
184189
184280
  while (remainingContinuations > 0 && result.length < SUMMARY_MIN_LENGTH) {
184190
184281
  remainingContinuations -= 1;
184191
184282
  options.signal.throwIfAborted();
184283
+ this.assertInputLease(options);
184192
184284
  child.turn.prompt([{
184193
184285
  type: "text",
184194
184286
  text: summary_continuation_default
@@ -248678,6 +248770,11 @@ async function prepareSkippedToolCall(step, call) {
248678
248770
  await dispatchToolCall(step, call, call.args);
248679
248771
  return makeResolvedToolCallTask(makeErrorToolResult(call, call.args, output));
248680
248772
  }
248773
+ function waitForPreparationBoundary(step, operation) {
248774
+ if (step.canStart?.() === false) return Promise.reject(new DOMException("INPUT_SUPERSEDED", "AbortError"));
248775
+ if (step.inputControl === void 0) return waitForToolBoundary(step, () => operation(step.signal));
248776
+ return step.inputControl.prepare(step.signal, (signal) => operation(signal));
248777
+ }
248681
248778
  function waitForToolBoundary(step, operation) {
248682
248779
  if (step.programmaticParentCallId === void 0) return Promise.resolve(operation());
248683
248780
  step.signal.throwIfAborted();
@@ -248705,6 +248802,11 @@ function makeResolvedToolCallTask(result) {
248705
248802
  async function runPrepareToolExecutionHook(step, call) {
248706
248803
  const { hooks, signal, turnId, currentStep, llm } = step;
248707
248804
  const { toolCall, args } = call;
248805
+ if (step.canStart?.() === false) return {
248806
+ kind: "blocked",
248807
+ args,
248808
+ output: "INPUT_SUPERSEDED"
248809
+ };
248708
248810
  const hook = hooks?.prepareToolExecution;
248709
248811
  if (hook === void 0) return {
248710
248812
  kind: "allowed",
@@ -248756,7 +248858,7 @@ async function runAuthorizeToolExecutionHook(step, call, args, execution) {
248756
248858
  const hook = hooks?.authorizeToolExecution;
248757
248859
  if (hook === void 0) return void 0;
248758
248860
  try {
248759
- return await waitForToolBoundary(step, () => hook({
248861
+ return await waitForPreparationBoundary(step, (preparationSignal) => hook({
248760
248862
  toolCall: call.toolCall,
248761
248863
  toolCalls: step.toolCalls,
248762
248864
  tool: call.tool,
@@ -248764,7 +248866,7 @@ async function runAuthorizeToolExecutionHook(step, call, args, execution) {
248764
248866
  execution,
248765
248867
  turnId,
248766
248868
  stepNumber: currentStep,
248767
- signal,
248869
+ signal: preparationSignal,
248768
248870
  llm
248769
248871
  }));
248770
248872
  } catch (error) {
@@ -248818,6 +248920,7 @@ async function runRunnableToolCall(step, call, effectiveArgs, metadata, executio
248818
248920
  function createNestedToolInvoker(step, parent) {
248819
248921
  const controller = new AbortController();
248820
248922
  const parentSignal = AbortSignal.any([step.signal, controller.signal]);
248923
+ inheritInputControl(parentSignal, step.inputControl);
248821
248924
  let accepting = true;
248822
248925
  let stopped = false;
248823
248926
  let sequence = 0;
@@ -248844,6 +248947,7 @@ function createNestedToolInvoker(step, parent) {
248844
248947
  while (reservedIds.has(id));
248845
248948
  reservedIds.add(id);
248846
248949
  const signal = input.signal === void 0 ? parentSignal : AbortSignal.any([parentSignal, input.signal]);
248950
+ inheritInputControl(signal, step.inputControl);
248847
248951
  const run = async () => {
248848
248952
  if (stopped) throw new Error("A nested tool stopped the turn.");
248849
248953
  signal.throwIfAborted();
@@ -248933,6 +249037,10 @@ async function finalizePendingToolResult(step, pendingResult) {
248933
249037
  async function executeTool(step, execution, toolCall, toolName, metadata, invokeTool) {
248934
249038
  const { dispatchEvent, signal, turnId } = step;
248935
249039
  signal.throwIfAborted();
249040
+ if (step.canStart?.() === false) return {
249041
+ output: "INPUT_SUPERSEDED",
249042
+ isError: true
249043
+ };
248936
249044
  const executePromise = execution.execute({
248937
249045
  turnId,
248938
249046
  toolCallId: toolCall.id,
@@ -249082,6 +249190,7 @@ var init_tool_call$1 = __esmMin((() => {
249082
249190
  init_path_access();
249083
249191
  init_abort();
249084
249192
  init_errors$5();
249193
+ init_input_control();
249085
249194
  init_execution_observer();
249086
249195
  init_tool_args_parse();
249087
249196
  init_tool_access();
@@ -249101,6 +249210,8 @@ var init_tool_call$1 = __esmMin((() => {
249101
249210
  */
249102
249211
  async function executeLoopStep(deps) {
249103
249212
  const { turnId, signal, buildMessages, buildMessagesStrict, dispatchEvent, llm, tools, hooks, executionObserver, log, currentStep, maxRetryAttempts, checkpointBeforeRetry, recordUsage, onStepStarted } = deps;
249213
+ const control = inputControl(signal);
249214
+ const inputEpoch = control.epoch;
249104
249215
  if (hooks?.beforeStep !== void 0) {
249105
249216
  const beforeStep = await hooks.beforeStep({
249106
249217
  turnId,
@@ -249119,10 +249230,13 @@ async function executeLoopStep(deps) {
249119
249230
  turnId,
249120
249231
  currentStep,
249121
249232
  stepUuid,
249122
- onStepStarted
249233
+ onStepStarted,
249234
+ acceptOutput: () => !control.stopped && control.epoch === inputEpoch
249123
249235
  });
249124
249236
  const prepareRequestBoundary = llm.prepareRequestBoundary?.bind(llm);
249125
249237
  const step = {
249238
+ inputControl: control,
249239
+ canStart: () => !control.stopped && control.epoch === inputEpoch,
249126
249240
  tools,
249127
249241
  hooks,
249128
249242
  executionObserver,
@@ -249138,6 +249252,7 @@ async function executeLoopStep(deps) {
249138
249252
  messages,
249139
249253
  tools: tools ?? [],
249140
249254
  signal,
249255
+ boundarySignal: signal,
249141
249256
  ...stepEvents.callbacks
249142
249257
  };
249143
249258
  if (prepareRequestBoundary === void 0) await stepEvents.start();
@@ -249187,6 +249302,12 @@ async function executeLoopStep(deps) {
249187
249302
  log
249188
249303
  };
249189
249304
  let response;
249305
+ const provider = control.beginProvider();
249306
+ chatParams = {
249307
+ ...chatParams,
249308
+ signal: AbortSignal.any([signal, provider.signal])
249309
+ };
249310
+ if (control.stopped || control.epoch !== inputEpoch) provider.abort();
249190
249311
  try {
249191
249312
  response = await chatWithRetry({
249192
249313
  ...retryInput,
@@ -249194,35 +249315,50 @@ async function executeLoopStep(deps) {
249194
249315
  });
249195
249316
  } catch (error) {
249196
249317
  await stepEvents.drain();
249197
- if (buildMessagesStrict === void 0 || !isRecoverableRequestStructureError(error) || prepareRequestBoundary !== void 0 && stepEvents.hasOutput) throw error;
249198
- signal.throwIfAborted();
249199
- log?.warn("provider rejected request structure; resending with strict projection", {
249200
- turnStep: `${turnId}.${String(currentStep)}`,
249201
- model: llm.modelName
249202
- });
249203
- const strictMessages = await buildMessagesStrict();
249204
- signal.throwIfAborted();
249205
- let strictParams = {
249206
- ...chatParams,
249207
- messages: strictMessages
249318
+ if (provider.signal.aborted && !signal.aborted) response = {
249319
+ toolCalls: [],
249320
+ usage: emptyUsage()
249208
249321
  };
249209
- if (prepareRequestBoundary !== void 0) strictParams = await prepareRequestBoundary(strictParams, buildMessagesStrict);
249210
- signal.throwIfAborted();
249211
- try {
249212
- response = await chatWithRetry({
249213
- ...retryInput,
249214
- params: strictParams
249215
- });
249216
- } catch (strictError) {
249217
- log?.error("strict resend still rejected by provider; request remains wire-invalid", {
249322
+ else if (buildMessagesStrict === void 0 || !isRecoverableRequestStructureError(error) || prepareRequestBoundary !== void 0 && stepEvents.hasOutput) throw error;
249323
+ else try {
249324
+ signal.throwIfAborted();
249325
+ log?.warn("provider rejected request structure; resending with strict projection", {
249218
249326
  turnStep: `${turnId}.${String(currentStep)}`,
249219
- model: llm.modelName,
249220
- originalError: errorMessage$13(error),
249221
- strictError: errorMessage$13(strictError)
249327
+ model: llm.modelName
249222
249328
  });
249223
- throw strictError;
249329
+ const strictMessages = await buildMessagesStrict();
249330
+ signal.throwIfAborted();
249331
+ let strictParams = {
249332
+ ...chatParams,
249333
+ messages: strictMessages
249334
+ };
249335
+ if (prepareRequestBoundary !== void 0) strictParams = await prepareRequestBoundary(strictParams, buildMessagesStrict);
249336
+ signal.throwIfAborted();
249337
+ try {
249338
+ response = await chatWithRetry({
249339
+ ...retryInput,
249340
+ params: strictParams
249341
+ });
249342
+ } catch (strictError) {
249343
+ if (provider.signal.aborted) throw strictError;
249344
+ log?.error("strict resend still rejected by provider; request remains wire-invalid", {
249345
+ turnStep: `${turnId}.${String(currentStep)}`,
249346
+ model: llm.modelName,
249347
+ originalError: errorMessage$13(error),
249348
+ strictError: errorMessage$13(strictError)
249349
+ });
249350
+ throw strictError;
249351
+ }
249352
+ log?.info("recovered after strict resend", { turnStep: `${turnId}.${String(currentStep)}` });
249353
+ } catch (strictBoundaryError) {
249354
+ if (!provider.signal.aborted || signal.aborted) throw strictBoundaryError;
249355
+ response = {
249356
+ toolCalls: [],
249357
+ usage: emptyUsage()
249358
+ };
249224
249359
  }
249225
- log?.info("recovered after strict resend", { turnStep: `${turnId}.${String(currentStep)}` });
249360
+ } finally {
249361
+ control.endProvider(provider);
249226
249362
  }
249227
249363
  await stepEvents.start();
249228
249364
  await stepEvents.drain();
@@ -249233,6 +249369,7 @@ async function executeLoopStep(deps) {
249233
249369
  if (effectiveStopReason === "tool_use") {
249234
249370
  if ((await runToolCallBatch(step, response)).stopTurn) effectiveStopReason = "end_turn";
249235
249371
  }
249372
+ if (control.epoch !== inputEpoch) effectiveStopReason = control.stopped ? "end_turn" : "tool_use";
249236
249373
  signal.throwIfAborted();
249237
249374
  await dispatchEvent({
249238
249375
  type: "step.end",
@@ -249343,8 +249480,10 @@ function createStepEventGate(deps) {
249343
249480
  return startPromise;
249344
249481
  };
249345
249482
  const enqueue = (dispatch) => {
249483
+ if (!deps.acceptOutput()) return Promise.resolve();
249346
249484
  hasOutput = true;
249347
249485
  const queued = eventQueue.then(async () => {
249486
+ if (!deps.acceptOutput()) return;
249348
249487
  await start();
249349
249488
  await dispatch();
249350
249489
  });
@@ -249427,6 +249566,7 @@ function createStepEventGate(deps) {
249427
249566
  }
249428
249567
  var init_turn_step = __esmMin((() => {
249429
249568
  init_src$8();
249569
+ init_input_control();
249430
249570
  init_errors$5();
249431
249571
  init_execution_observer();
249432
249572
  init_retry();
@@ -249449,6 +249589,10 @@ async function runTurn(input) {
249449
249589
  try {
249450
249590
  while (true) {
249451
249591
  signal.throwIfAborted();
249592
+ if (inputControl(signal).stopped) {
249593
+ stopReason = "aborted";
249594
+ break;
249595
+ }
249452
249596
  if (maxSteps !== void 0 && maxSteps > 0 && steps >= maxSteps) throw createMaxStepsExceededError(maxSteps);
249453
249597
  steps += 1;
249454
249598
  const stepNumber = steps;
@@ -249470,6 +249614,10 @@ async function runTurn(input) {
249470
249614
  onStepStarted: setActiveStep.bind(void 0, stepNumber)
249471
249615
  });
249472
249616
  activeStep = void 0;
249617
+ if (inputControl(signal).stopped) {
249618
+ stopReason = "aborted";
249619
+ break;
249620
+ }
249473
249621
  if (stepResult.stopReason === "tool_use") continue;
249474
249622
  const terminalStopReason = stepResult.stopReason;
249475
249623
  stopReason = terminalStopReason;
@@ -249513,6 +249661,7 @@ var init_run_turn = __esmMin((() => {
249513
249661
  init_src$8();
249514
249662
  init_errors$5();
249515
249663
  init_turn_step();
249664
+ init_input_control();
249516
249665
  }));
249517
249666
  var init_loop$1 = __esmMin((() => {
249518
249667
  init_tool_access();
@@ -250173,7 +250322,8 @@ var init_prompt$1 = __esmMin((() => {
250173
250322
  sessionAdmissionSteerRequestSchema = admissionReadIdentitySchema.omit({ timeout_ms: true }).extend({ expected_turn_id: admissionTurnSchema });
250174
250323
  sessionAdmissionCancelRequestSchema = object$1({
250175
250324
  scope: admissionIdentitySchema,
250176
- turn_id: admissionTurnSchema
250325
+ turn_id: admissionTurnSchema,
250326
+ graceful: boolean$1().optional()
250177
250327
  }).strict();
250178
250328
  sessionAdmissionCancelResponseSchema = sessionAdmissionCancelRequestSchema.extend({
250179
250329
  session_id: string().min(1),
@@ -256655,6 +256805,43 @@ function convertMCPContentBlock(block) {
256655
256805
  * `mcp__github__create_pr`) — embedded into the `<mcp_tool_result name="…">`
256656
256806
  * wrap when the result is media-only, so the model can attribute binary parts.
256657
256807
  */
256808
+ async function retainOriginalText(parts, toolName, homedir) {
256809
+ const textParts = parts.flatMap((part) => {
256810
+ if (part.type !== "text") return [];
256811
+ const chunks = [];
256812
+ for (let offset = 0; offset < part.text.length; offset += 256) chunks.push(part.text.slice(offset, offset + 256));
256813
+ return [chunks];
256814
+ });
256815
+ const archive = JSON.stringify({
256816
+ version: 1,
256817
+ textParts
256818
+ }, null, 2);
256819
+ const outputPath = homedir === void 0 ? void 0 : await saveToolResult({
256820
+ homedir,
256821
+ toolName,
256822
+ toolCallId: "mcp-original",
256823
+ directoryPolicy: "private-retention"
256824
+ }, archive);
256825
+ if (outputPath === void 0) return "\n\n[Originaltext nicht gespeichert: Sitzungsverzeichnis fehlt oder Schreiben fehlgeschlagen. Die Ausgabe bleibt begrenzt.]";
256826
+ return [
256827
+ "",
256828
+ "",
256829
+ "MCP-Originaltext vor Kürzung gespeichert (JSON, version: 1, textParts: Zeichenabschnitte je Textblock; ohne Binärdaten).",
256830
+ `output_path: ${outputPath}`,
256831
+ "Mit Read seitenweise nachlesen. Zeichenabschnitte je Block ohne Trennzeichen verbinden; Blockreihenfolge erhalten."
256832
+ ].join("\n");
256833
+ }
256834
+ function appendTextNotice(parts, text) {
256835
+ const last = parts.at(-1);
256836
+ if (last?.type === "text") parts[parts.length - 1] = {
256837
+ ...last,
256838
+ text: last.text + text
256839
+ };
256840
+ else parts.push({
256841
+ type: "text",
256842
+ text
256843
+ });
256844
+ }
256658
256845
  async function mcpResultToExecutableOutput(result, qualifiedToolName, options = {}) {
256659
256846
  const converted = [];
256660
256847
  for (const block of result.content) {
@@ -256662,8 +256849,10 @@ async function mcpResultToExecutableOutput(result, qualifiedToolName, options =
256662
256849
  if (part !== null) converted.push(part);
256663
256850
  }
256664
256851
  const budgeted = applyTextBudget(wrapMediaOnly(converted, qualifiedToolName));
256852
+ const retentionNotice = budgeted.truncated ? await retainOriginalText(converted, qualifiedToolName, options.homedir) : void 0;
256665
256853
  const capped = applyBinaryPartCap(await compressImageContentParts(budgeted.parts, { annotate: { persistOriginal: (bytes, mimeType) => persistOriginalImage(bytes, mimeType, options.originalsDir === void 0 ? {} : { dir: options.originalsDir }) } }));
256666
256854
  const truncated = budgeted.truncated || capped.truncated;
256855
+ if (retentionNotice !== void 0) appendTextNotice(capped.parts, retentionNotice);
256667
256856
  const output = collapseSingleText(capped.parts);
256668
256857
  return truncated ? {
256669
256858
  output,
@@ -256809,6 +256998,7 @@ function collapseSingleText(parts) {
256809
256998
  }
256810
256999
  var MCP_MAX_OUTPUT_CHARS, MCP_OUTPUT_TRUNCATED_TEXT, MCP_MAX_BINARY_PART_BYTES, MCP_MAX_BINARY_PART_CHARS;
256811
257000
  var init_output = __esmMin((() => {
257001
+ init_tool_result_budget();
256812
257002
  init_image_compress();
256813
257003
  init_image_originals();
256814
257004
  MCP_MAX_OUTPUT_CHARS = 1e5;
@@ -265065,7 +265255,8 @@ async function budgetToolResultForModel(options) {
265065
265255
  const outputPath = await saveToolResult({
265066
265256
  homedir: options.homedir,
265067
265257
  toolName: options.toolName,
265068
- toolCallId: options.toolCallId
265258
+ toolCallId: options.toolCallId,
265259
+ directoryPolicy: "compatible-spill"
265069
265260
  }, text);
265070
265261
  if (outputPath === void 0) return options.result;
265071
265262
  const output = renderPersistedToolResult(options.toolName, options.toolCallId, text, outputPath);
@@ -265084,19 +265275,33 @@ function persistableToolResultText(output) {
265084
265275
  return output.map((part) => part.text).join("");
265085
265276
  }
265086
265277
  async function saveToolResult(options, text) {
265278
+ if (!isAbsolute$2(options.homedir)) return void 0;
265279
+ let createdPath;
265087
265280
  try {
265088
265281
  const dir = join$4(options.homedir, "tool-results");
265089
265282
  await mkdir(dir, {
265090
265283
  recursive: true,
265091
265284
  mode: 448
265092
265285
  });
265286
+ const info = await lstat(dir);
265287
+ if (info.isSymbolicLink()) return void 0;
265288
+ if (process.platform !== "win32") {
265289
+ if (info.uid !== process.getuid?.()) return void 0;
265290
+ if (options.directoryPolicy === "private-retention" && (info.mode & 63) !== 0) return;
265291
+ }
265292
+ const home = await realpath(options.homedir);
265293
+ if (normalize$4(await realpath(dir)) !== join$4(home, "tool-results")) return void 0;
265093
265294
  const outputPath = join$4(dir, `${safeToolResultFileStem(options.toolName, options.toolCallId)}-${randomUUID()}.txt`);
265094
- await writeFile(outputPath, text, {
265095
- encoding: "utf8",
265096
- flag: "wx"
265097
- });
265295
+ const file = await open(outputPath, "wx", 384);
265296
+ createdPath = outputPath;
265297
+ try {
265298
+ await file.writeFile(text, { encoding: "utf8" });
265299
+ } finally {
265300
+ await file.close();
265301
+ }
265098
265302
  return outputPath;
265099
265303
  } catch {
265304
+ if (createdPath !== void 0) await unlink(createdPath).catch(() => void 0);
265100
265305
  return;
265101
265306
  }
265102
265307
  }
@@ -265826,7 +266031,8 @@ var init_turn = __esmMin((() => {
265826
266031
  "Otherwise keep going — use the existing conversation context and your tools,",
265827
266032
  "and do not ask the user for input unless a real blocker prevents progress."
265828
266033
  ].join(" ");
265829
- TurnFlow = class {
266034
+ init_input_control();
266035
+ TurnFlow = class {
265830
266036
  agent;
265831
266037
  admissionClosed = false;
265832
266038
  loadedToolNames = /* @__PURE__ */ new Set();
@@ -265903,6 +266109,7 @@ var init_turn = __esmMin((() => {
265903
266109
  if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 2147483647) throw new Error("INVALID_PROMPT_TIMEOUT");
265904
266110
  }
265905
266111
  this.assertAdmissionOpen();
266112
+ this.stopRequested = false;
265906
266113
  this.agent.records.logRecord({
265907
266114
  type: "turn.prompt",
265908
266115
  input,
@@ -265919,6 +266126,7 @@ var init_turn = __esmMin((() => {
265919
266126
  }
265920
266127
  steer(input, origin = USER_PROMPT_ORIGIN) {
265921
266128
  this.assertAdmissionOpen();
266129
+ this.stopRequested = false;
265922
266130
  this.agent.records.logRecord({
265923
266131
  type: "turn.steer",
265924
266132
  input,
@@ -265932,7 +266140,7 @@ var init_turn = __esmMin((() => {
265932
266140
  }
265933
266141
  /** Buffer only into the currently active turn; never launch from an idle state. */
265934
266142
  steerActive(input, expectedTurnId, origin = USER_PROMPT_ORIGIN, onDisposition) {
265935
- if (this.admissionClosed) return null;
266143
+ if (this.admissionClosed || this.stopRequested) return null;
265936
266144
  const active = this.activeTurn;
265937
266145
  if (active === null || active === "resuming" || !active.acceptingSteers || expectedTurnId !== void 0 && expectedTurnId !== this.currentId) return null;
265938
266146
  this.agent.records.logRecord({
@@ -266023,7 +266231,19 @@ var init_turn = __esmMin((() => {
266023
266231
  this.turnId += 1;
266024
266232
  this.activeTurn = "resuming";
266025
266233
  }
266026
- cancel(turnId, reason) {
266234
+ stopRequested = false;
266235
+ stop(turnId) {
266236
+ const active = this.activeTurn;
266237
+ if (turnId !== this.currentId) return;
266238
+ this.stopRequested = true;
266239
+ if (active === null || active === "resuming") return;
266240
+ this.agent.records.logRecord({
266241
+ type: "turn.cancel",
266242
+ turnId
266243
+ });
266244
+ inputControl(active.controller.signal).changed(true);
266245
+ }
266246
+ cancel(turnId, reason) {
266027
266247
  this.agent.records.logRecord({
266028
266248
  type: "turn.cancel",
266029
266249
  turnId
@@ -266094,6 +266314,8 @@ var init_turn = __esmMin((() => {
266094
266314
  timeoutMs
266095
266315
  });
266096
266316
  this.nextSteerSequence += 1;
266317
+ const active = this.activeTurn;
266318
+ if (origin.kind !== "background_task" && active !== null && active !== "resuming") inputControl(active.controller.signal).changed();
266097
266319
  }
266098
266320
  flushSteerBuffer(turnId = this.currentId, throughSequence = Number.POSITIVE_INFINITY) {
266099
266321
  if (this.steerBuffer.length === 0) return false;
@@ -266154,7 +266376,7 @@ var init_turn = __esmMin((() => {
266154
266376
  * draining into it via `flushSteerBuffer`.
266155
266377
  */
266156
266378
  onCompactionFinished() {
266157
- if (this.admissionClosed) return;
266379
+ if (this.admissionClosed || this.stopRequested) return;
266158
266380
  if (this.steerBuffer.length === 0) return;
266159
266381
  if (this.activeTurn !== null) return;
266160
266382
  const next = this.steerBuffer.shift();
@@ -266183,7 +266405,7 @@ var init_turn = __esmMin((() => {
266183
266405
  try {
266184
266406
  if (this.agent.goal.getGoal().goal?.status === "active") return finish(await this.driveGoal(firstTurnId, input, origin, signal));
266185
266407
  const end = await this.runOneTurn(firstTurnId, input, origin, signal, true);
266186
- if (this.agent.goal.getGoal().goal?.status === "active" && end.event.reason !== "cancelled" && end.event.reason !== "failed" && end.event.reason !== "filtered") return finish(await this.driveGoal(this.allocateTurnId(), [{
266408
+ if (this.agent.goal.getGoal().goal?.status === "active" && !inputControl(signal).stopped && end.event.reason !== "cancelled" && end.event.reason !== "failed" && end.event.reason !== "filtered") return finish(await this.driveGoal(this.allocateTurnId(), [{
266187
266409
  type: "text",
266188
266410
  text: GOAL_CONTINUATION_PROMPT
266189
266411
  }], goalContinuationOrigin(origin), signal));
@@ -266221,6 +266443,11 @@ var init_turn = __esmMin((() => {
266221
266443
  let turnInput = input;
266222
266444
  let turnOrigin = origin;
266223
266445
  while (true) {
266446
+ if (inputControl(signal).stopped) return { event: {
266447
+ type: "turn.ended",
266448
+ turnId,
266449
+ reason: "cancelled"
266450
+ } };
266224
266451
  const goalBeforeTurn = this.agent.goal.getGoal().goal;
266225
266452
  if (goalBeforeTurn?.status === "active" && goalBeforeTurn.budget.overBudget) {
266226
266453
  await this.agent.goal.markBlocked({ reason: "A configured budget was reached" });
@@ -266310,7 +266537,13 @@ var init_turn = __esmMin((() => {
266310
266537
  let completedResponse;
266311
266538
  let errorEvent;
266312
266539
  try {
266540
+ const checkStop = () => {
266541
+ signal.throwIfAborted();
266542
+ if (inputControl(signal).stopped) throw new DOMException("INPUT_STOPPED", "AbortError");
266543
+ };
266544
+ checkStop();
266313
266545
  const promptHookEnded = await this.applyUserPromptHook(turnId, input, origin, signal, startedAt);
266546
+ checkStop();
266314
266547
  if (promptHookEnded !== void 0) {
266315
266548
  ended = promptHookEnded.event;
266316
266549
  blockedByUserPromptHook = promptHookEnded.blocked;
@@ -266329,6 +266562,7 @@ var init_turn = __esmMin((() => {
266329
266562
  this.agent.log.warn("Turn-start observation failed");
266330
266563
  }
266331
266564
  signal.throwIfAborted();
266565
+ checkStop();
266332
266566
  const stopReason = await this.runStepLoop(turnId, signal, input, origin, (response) => {
266333
266567
  completedResponse = response;
266334
266568
  });
@@ -266581,7 +266815,7 @@ var init_turn = __esmMin((() => {
266581
266815
  },
266582
266816
  settleStep: async ({ signal: stepSignal }) => {
266583
266817
  if (stopForGoalBudget) this.setActiveSteerAcceptance(turnId, false);
266584
- await this.agent.fullCompaction.afterStep(stepSignal);
266818
+ if (!inputControl(stepSignal).stopped) await this.agent.fullCompaction.afterStep(stepSignal);
266585
266819
  },
266586
266820
  afterStep: async () => {
266587
266821
  deduper.endStep();
@@ -269342,63 +269576,66 @@ var init_tool$1 = __esmMin((() => {
269342
269576
  }
269343
269577
  }
269344
269578
  registerMcpServer(serverName, client, tools, enabledTools) {
269345
- this.unregisterMcpServer(serverName);
269346
- const qualifiedNames = [];
269347
- const collisions = [];
269348
- const seenInThisCall = /* @__PURE__ */ new Map();
269349
- for (const tool of tools) {
269350
- if (enabledTools !== void 0 && !enabledTools.has(tool.name)) continue;
269351
- const qualified = qualifyMcpToolName(serverName, tool.name);
269352
- const firstInThisCall = seenInThisCall.get(qualified);
269353
- if (firstInThisCall !== void 0) {
269354
- collisions.push({
269355
- qualified,
269356
- toolName: tool.name,
269357
- collidesWith: {
269358
- kind: "same_server",
269359
- toolName: firstInThisCall
269360
- }
269361
- });
269362
- continue;
269363
- }
269364
- const existingEntry = this.mcpTools.get(qualified);
269365
- if (existingEntry !== void 0) {
269366
- collisions.push({
269367
- qualified,
269368
- toolName: tool.name,
269369
- collidesWith: {
269370
- kind: "other_server",
269371
- serverName: existingEntry.serverName
269372
- }
269373
- });
269374
- continue;
269375
- }
269376
- seenInThisCall.set(qualified, tool.name);
269377
- const wrapped = {
269378
- name: qualified,
269379
- description: tool.description,
269380
- parameters: tool.parameters,
269381
- resolveExecution: (args) => {
269382
- return {
269383
- approvalRule: qualified,
269384
- execute: async (context) => {
269385
- return mcpResultToExecutableOutput(await client.callTool(tool.name, args ?? {}, context.signal), qualified, { originalsDir: this.agent.mediaOriginalsDir });
269386
- }
269387
- };
269579
+ this.unregisterMcpServer(serverName);
269580
+ const qualifiedNames = [];
269581
+ const collisions = [];
269582
+ const seenInThisCall = /* @__PURE__ */ new Map();
269583
+ for (const tool of tools) {
269584
+ if (enabledTools !== void 0 && !enabledTools.has(tool.name)) continue;
269585
+ const qualified = qualifyMcpToolName(serverName, tool.name);
269586
+ const firstInThisCall = seenInThisCall.get(qualified);
269587
+ if (firstInThisCall !== void 0) {
269588
+ collisions.push({
269589
+ qualified,
269590
+ toolName: tool.name,
269591
+ collidesWith: {
269592
+ kind: "same_server",
269593
+ toolName: firstInThisCall
269388
269594
  }
269389
- };
269390
- this.mcpTools.set(qualified, {
269391
- tool: wrapped,
269392
- serverName
269393
269595
  });
269394
- qualifiedNames.push(qualified);
269596
+ continue;
269395
269597
  }
269396
- this.mcpToolsByServer.set(serverName, qualifiedNames);
269397
- return {
269398
- registered: qualifiedNames,
269399
- collisions
269598
+ const existingEntry = this.mcpTools.get(qualified);
269599
+ if (existingEntry !== void 0) {
269600
+ collisions.push({
269601
+ qualified,
269602
+ toolName: tool.name,
269603
+ collidesWith: {
269604
+ kind: "other_server",
269605
+ serverName: existingEntry.serverName
269606
+ }
269607
+ });
269608
+ continue;
269609
+ }
269610
+ seenInThisCall.set(qualified, tool.name);
269611
+ const wrapped = {
269612
+ name: qualified,
269613
+ description: tool.description,
269614
+ parameters: tool.parameters,
269615
+ resolveExecution: (args) => {
269616
+ return {
269617
+ approvalRule: qualified,
269618
+ execute: async (context) => {
269619
+ return mcpResultToExecutableOutput(await client.callTool(tool.name, args ?? {}, context.signal), qualified, {
269620
+ originalsDir: this.agent.mediaOriginalsDir,
269621
+ homedir: this.agent.homedir
269622
+ });
269623
+ }
269624
+ };
269625
+ }
269400
269626
  };
269627
+ this.mcpTools.set(qualified, {
269628
+ tool: wrapped,
269629
+ serverName
269630
+ });
269631
+ qualifiedNames.push(qualified);
269401
269632
  }
269633
+ this.mcpToolsByServer.set(serverName, qualifiedNames);
269634
+ return {
269635
+ registered: qualifiedNames,
269636
+ collisions
269637
+ };
269638
+ }
269402
269639
  unregisterMcpServer(serverName) {
269403
269640
  const existing = this.mcpToolsByServer.get(serverName);
269404
269641
  if (existing === void 0) return false;
@@ -270606,7 +270843,7 @@ var init_agent = __esmMin((() => {
270606
270843
  messages: await rebuildMessages()
270607
270844
  };
270608
270845
  let systemPrompt = this.effectiveSystemPrompt;
270609
- const compacted = await this.fullCompaction.beforeStep(params.signal, {
270846
+ const compacted = await this.fullCompaction.beforeStep(params.boundarySignal ?? params.signal, {
270610
270847
  messages: params.messages,
270611
270848
  additionalMessages: steers.messages,
270612
270849
  rebuildMessages,
@@ -270771,6 +271008,12 @@ var init_agent = __esmMin((() => {
270771
271008
  };
270772
271009
  },
270773
271010
  cancel: (payload) => {
271011
+ if (payload.graceful === true) {
271012
+ if (payload.turnId === void 0) throw new Error("STOP_TURN_REQUIRED");
271013
+ if (payload.turnId !== this.turn.currentId) return;
271014
+ this.turn.stop(payload.turnId);
271015
+ return Promise.all([this.turn.waitForExecutionEnd(), this.fullCompaction.waitForExecutionEnd()]).then(() => void 0);
271016
+ }
270774
271017
  const waitForExecution = this.experimentalFlags.enabled("queue_policies") && payload.turnId !== void 0 && payload.turnId === this.turn.currentId;
270775
271018
  if (this.turn.hasActiveTurn) this.telemetry.track("cancel", { from: "streaming" });
270776
271019
  this.turn.cancel(payload.turnId, payload.cancellationReason === "timeout" ? new DOMException("Prompt execution timed out", "TimeoutError") : void 0);
@@ -336942,7 +337185,10 @@ async function appendSessionIndexEntry(homeDir, entry) {
336942
337185
  recursive: true,
336943
337186
  mode: 448
336944
337187
  });
336945
- await appendFile(indexPath, `${JSON.stringify(entry)}\n`, "utf-8");
337188
+ await appendFile(indexPath, `${JSON.stringify(entry)}\n`, {
337189
+ encoding: "utf-8",
337190
+ mode: 384
337191
+ });
336946
337192
  }
336947
337193
  async function readSessionIndex$1(homeDir, sessionsDir) {
336948
337194
  let raw;
@@ -346195,12 +346441,14 @@ var init_sessionService = __esmMin((() => {
346195
346441
  sessionId: id,
346196
346442
  agentId: "main",
346197
346443
  expectedScope: request.scope,
346198
- turnId: request.turn_id
346444
+ turnId: request.turn_id,
346445
+ graceful: request.graceful
346199
346446
  });
346200
346447
  return {
346201
346448
  session_id: id,
346202
346449
  scope: request.scope,
346203
346450
  turn_id: request.turn_id,
346451
+ graceful: request.graceful,
346204
346452
  settled: true
346205
346453
  };
346206
346454
  }
@@ -349351,13 +349599,14 @@ var init_session$1 = __esmMin((() => {
349351
349599
  this.ensureOpen();
349352
349600
  await this.trackLocalInputRequest(() => this.rpc.cancel({ sessionId: this.id }));
349353
349601
  }
349354
- async cancelTurn(turnId, expectedScope) {
349602
+ async cancelTurn(turnId, expectedScope, graceful) {
349355
349603
  this.ensureOpen();
349356
349604
  if (!Number.isSafeInteger(turnId) || turnId < 0) throw new Error("INVALID_TURN_ID");
349357
349605
  await this.trackLocalInputRequest(() => this.rpc.cancelTurn({
349358
349606
  sessionId: this.id,
349359
349607
  turnId,
349360
- expectedScope
349608
+ expectedScope,
349609
+ graceful
349361
349610
  }));
349362
349611
  }
349363
349612
  async setModel(model, options) {
@@ -350789,7 +351038,8 @@ var init_rpc = __esmMin((() => {
350789
351038
  sessionId: input.sessionId,
350790
351039
  agentId,
350791
351040
  turnId: input.turnId,
350792
- expectedScope: input.expectedScope
351041
+ expectedScope: input.expectedScope,
351042
+ graceful: input.graceful
350793
351043
  });
350794
351044
  }
350795
351045
  async registerTool(input) {
@@ -352954,7 +353204,7 @@ var init_gateway_session_client = __esmMin((() => {
352954
353204
  if ((await this.metadata(owner)).capabilities.admission_cancel !== true) throw new GatewayCommandError("GATEWAY_CAPABILITY_UNAVAILABLE");
352955
353205
  owner?.throwIfAborted();
352956
353206
  const response = await this.post(path, request, sessionAdmissionCancelResponseSchema, owner);
352957
- if (response.session_id !== sessionId || response.scope !== request.scope || response.turn_id !== request.turn_id) throw new GatewayCommandError("GATEWAY_COMMAND_OUTCOME_UNKNOWN");
353207
+ if (response.session_id !== sessionId || response.scope !== request.scope || response.turn_id !== request.turn_id || response.graceful !== request.graceful) throw new GatewayCommandError("GATEWAY_COMMAND_OUTCOME_UNKNOWN");
352958
353208
  return response;
352959
353209
  }
352960
353210
  async steerWithReceipt(sessionId, input, owner) {
@@ -353389,7 +353639,8 @@ var init_gateway_session_rpc = __esmMin((() => {
353389
353639
  if (this.interactiveAgentId !== "main" || !input.expectedScope) throw new GatewayRpcError("GATEWAY_RPC_CAPABILITY_UNAVAILABLE");
353390
353640
  await this.client.cancelAdmissionTurn(this.sessionId, {
353391
353641
  scope: input.expectedScope,
353392
- turn_id: input.turnId
353642
+ turn_id: input.turnId,
353643
+ graceful: input.graceful
353393
353644
  }, this.lifetime.signal);
353394
353645
  this.assertScope(input);
353395
353646
  if (this.interactiveAgentId !== "main") throw new GatewayRpcError("GATEWAY_RPC_CAPABILITY_UNAVAILABLE");
@@ -368373,7 +368624,7 @@ function optionalBuildString(value) {
368373
368624
  var BLUN_BUILD_INFO;
368374
368625
  var init_build_info = __esmMin((() => {
368375
368626
  BLUN_BUILD_INFO = {
368376
- version: optionalBuildString("9.1.640"),
368627
+ version: optionalBuildString("9.1.642"),
368377
368628
  channel: typeof __BLUN_CHANNEL__ === "string" ? optionalBuildString(__BLUN_CHANNEL__) : void 0,
368378
368629
  commit: typeof __BLUN_COMMIT__ === "string" ? optionalBuildString(__BLUN_COMMIT__) : void 0,
368379
368630
  buildTarget: typeof __BLUN_BUILD_TARGET__ === "string" ? optionalBuildString(__BLUN_BUILD_TARGET__) : void 0
@@ -491685,6 +491936,117 @@ var init_rendering = __esmMin((() => {
491685
491936
  THINKING_WORD_INTERVAL_MS = 3e3;
491686
491937
  }));
491687
491938
  /** The caller supplies the authoritative, workspace-scoped inventory. */
491939
+ var init_channel_queue = __esmMin((() => {
491940
+ CHANNEL_QUEUE_DEADLINE_MS = 3e4;
491941
+ }));
491942
+ var init_queue_deadline_watchdog = __esmMin((() => {
491943
+ init_channel_queue();
491944
+ QueueDeadlineWatchdog = class {
491945
+ snapshot;
491946
+ onStatus;
491947
+ now;
491948
+ owner;
491949
+ observed = /* @__PURE__ */ new WeakMap();
491950
+ statusHead;
491951
+ status;
491952
+ timer;
491953
+ disposed = false;
491954
+ generation = 0;
491955
+ constructor(snapshot, onStatus, now = () => performance.now()) {
491956
+ this.snapshot = snapshot;
491957
+ this.onStatus = onStatus;
491958
+ this.now = now;
491959
+ }
491960
+ /** Steer restoration may copy an entry; keep its original monotonic age. */
491961
+ transfer(from, to) {
491962
+ const started = this.observed.get(from);
491963
+ if (started !== void 0) this.observed.set(to, started);
491964
+ if (this.statusHead === from) this.statusHead = to;
491965
+ }
491966
+ sync() {
491967
+ if (this.disposed) return;
491968
+ this.clearTimer();
491969
+ const snapshot = this.snapshot();
491970
+ if (snapshot.owner !== this.owner) {
491971
+ this.owner = snapshot.owner;
491972
+ this.observed = /* @__PURE__ */ new WeakMap();
491973
+ this.statusHead = void 0;
491974
+ this.publish(void 0);
491975
+ }
491976
+ const now = this.now();
491977
+ for (const entry of snapshot.entries) if (!this.observed.has(entry)) this.observed.set(entry, now);
491978
+ const head = snapshot.entries[0];
491979
+ if (head === void 0) {
491980
+ this.publish(void 0);
491981
+ return;
491982
+ }
491983
+ const elapsedMs = Math.max(0, now - this.observed.get(head));
491984
+ if (elapsedMs >= 3e4) {
491985
+ const status = {
491986
+ code: "QUEUE_DEADLINE_EXCEEDED",
491987
+ deadlineMs: CHANNEL_QUEUE_DEADLINE_MS,
491988
+ elapsedMs,
491989
+ reason: snapshot.reason
491990
+ };
491991
+ this.publish(status, head);
491992
+ return;
491993
+ }
491994
+ this.publish(void 0);
491995
+ const generation = this.generation;
491996
+ this.timer = setTimeout(() => {
491997
+ if (this.disposed || generation !== this.generation) return;
491998
+ this.timer = void 0;
491999
+ this.sync();
492000
+ }, CHANNEL_QUEUE_DEADLINE_MS - elapsedMs);
492001
+ this.timer.unref?.();
492002
+ }
492003
+ dispose() {
492004
+ this.disposed = true;
492005
+ this.clearTimer();
492006
+ this.publish(void 0);
492007
+ }
492008
+ publish(status, head) {
492009
+ if (this.statusHead === head && this.status?.reason === status?.reason && this.status === void 0 === (status === void 0)) return;
492010
+ this.statusHead = head;
492011
+ this.status = status;
492012
+ this.onStatus(status);
492013
+ }
492014
+ clearTimer() {
492015
+ this.generation += 1;
492016
+ if (this.timer !== void 0) clearTimeout(this.timer);
492017
+ this.timer = void 0;
492018
+ }
492019
+ };
492020
+ }));
492021
+ var init_stopped_input_scopes = __esmMin((() => {
492022
+ StoppedInputScopes = class {
492023
+ owners = /* @__PURE__ */ new WeakMap();
492024
+ stop(owner, scope) {
492025
+ let agents = this.owners.get(owner);
492026
+ if (agents === void 0) {
492027
+ agents = /* @__PURE__ */ new Map();
492028
+ this.owners.set(owner, agents);
492029
+ }
492030
+ agents.set(scope.agentId, scope);
492031
+ }
492032
+ get(owner, agentId) {
492033
+ const scope = this.owners.get(owner)?.get(agentId);
492034
+ return scope?.sessionId === owner.id ? scope : void 0;
492035
+ }
492036
+ clear(owner, agentId, expected = this.get(owner, agentId)) {
492037
+ if (expected !== void 0 && this.get(owner, agentId) === expected) this.owners.get(owner)?.delete(agentId);
492038
+ }
492039
+ resumeChannel(owner, agentId, envelope, turnId, runtimeScope) {
492040
+ const scope = this.get(owner, agentId);
492041
+ if (scope === void 0) return false;
492042
+ const boundary = scope.boundary;
492043
+ const start = envelope.meta["queue_start"];
492044
+ if (scope.chatId === void 0 || scope.chatId !== envelope.meta.chat_id || envelope.meta["control_authorized"] !== "true" || !/^\d+$/.test(envelope.meta["user_id"] ?? "") || !/^-?\d+$/.test(envelope.meta.chat_id) || !["true", "1"].includes(envelope.meta["addressed"] ?? "") || turnId !== void 0 && scope.turnId !== turnId || runtimeScope !== scope.runtimeScope || boundary === void 0 || boundary === "absent" || envelope.meta["queue_file_id"] !== boundary.fileId || start === void 0 || !/^\d+$/.test(start) || !Number.isSafeInteger(Number(start)) || Number(start) < boundary.frontier) return false;
492045
+ this.clear(owner, agentId, scope);
492046
+ return true;
492047
+ }
492048
+ };
492049
+ }));
491688
492050
  function resolveSessionReference(sessions, reference) {
491689
492051
  const value = reference.trim();
491690
492052
  if (value.length === 0) return { kind: "missing" };
@@ -492114,9 +492476,10 @@ var init_queue_prompt_delivery = __esmMin((() => {
492114
492476
  init_queue_overflow_delivery();
492115
492477
  }));
492116
492478
  /** Resolves only from request-specific evidence, never from UI step/turn events. */
492117
- async function deliverQueueSteer(sender, input, expectedTurnId, signal, onAccepted) {
492479
+ async function deliverQueueSteer(sender, input, expectedTurnId, signal, onAccepted, state) {
492118
492480
  if (!Number.isSafeInteger(expectedTurnId) || expectedTurnId < 0) throw new Error("INVALID_STEER_RECEIPT_TURN");
492119
- const payload = structuredClone(input);
492481
+ const payload = state?.payload ?? structuredClone(input);
492482
+ if (state !== void 0) state.payload = payload;
492120
492483
  const check = () => {
492121
492484
  if (signal.aborted) throw new Error("QUEUE_STEER_CANCELLED");
492122
492485
  };
@@ -492130,7 +492493,8 @@ async function deliverQueueSteer(sender, input, expectedTurnId, signal, onAccept
492130
492493
  check();
492131
492494
  };
492132
492495
  if (typeof sender.getPromptAdmissionScope !== "function" || typeof sender.steerActiveWithReceipt !== "function" || typeof sender.getSteerAdmissionReceipt !== "function") throw new Error("STEER_RECEIPTS_UNAVAILABLE");
492133
- let identity;
492496
+ let identity = state?.identity;
492497
+ const resuming = identity !== void 0;
492134
492498
  while (identity === void 0) {
492135
492499
  check();
492136
492500
  try {
@@ -492141,19 +492505,22 @@ async function deliverQueueSteer(sender, input, expectedTurnId, signal, onAccept
492141
492505
  requestId: randomUUID(),
492142
492506
  expectedTurnId
492143
492507
  };
492508
+ if (state !== void 0) state.identity = identity;
492144
492509
  } catch (error) {
492145
492510
  check();
492146
492511
  if (isPromptAdmissionProtocolFailure(error)) throw error;
492147
492512
  await wait();
492148
492513
  }
492149
492514
  }
492150
- let submit = true;
492515
+ let submit = !resuming;
492151
492516
  let accepted = false;
492152
492517
  const markAccepted = () => {
492153
492518
  if (accepted) return;
492154
492519
  accepted = true;
492520
+ if (state !== void 0) state.accepted = true;
492155
492521
  onAccepted?.();
492156
492522
  };
492523
+ if (state?.accepted) markAccepted();
492157
492524
  for (;;) {
492158
492525
  check();
492159
492526
  if (submit) {
@@ -499491,6 +499858,12 @@ var init_telegram_channel_copy = __esmMin((() => {
499491
499858
  });
499492
499859
  }));
499493
499860
  var SESSION_QUEUE_READ_BYTES;
499861
+ function isChannelStop(envelope) {
499862
+ if (envelope.meta["control_authorized"] !== "true" || !/^\d+$/.test(envelope.meta["user_id"] ?? "") || !/^-?\d+$/.test(envelope.meta.chat_id) || !["true", "1"].includes(envelope.meta["addressed"] ?? "")) return false;
499863
+ const match = /^\/stop(?:@([A-Za-z0-9_]+))?$/i.exec(envelope.text.trim());
499864
+ return match !== null && (match[1] === void 0 || match[1].toLowerCase() === envelope.meta["bot_username"]?.toLowerCase());
499865
+ }
499866
+ var init_channel_control = __esmMin((() => {}));
499494
499867
  var init_telegram_session_queue$1 = __esmMin((() => {
499495
499868
  SESSION_QUEUE_READ_BYTES = 65536;
499496
499869
  }));
@@ -499745,11 +500118,13 @@ var init_telegram_session_queue_delivery = __esmMin((() => {
499745
500118
  init_channel_injection();
499746
500119
  init_telegram_session_queue();
499747
500120
  init_telegram_session_queue_store();
499748
- SessionQueueDelivery = class {
500121
+ init_channel_control();
500122
+ SessionQueueDelivery = class {
499749
500123
  host;
499750
500124
  boundSessionId;
499751
500125
  inFlight = /* @__PURE__ */ new Set();
499752
- queueFile;
500126
+ controlsInFlight = /* @__PURE__ */ new Set();
500127
+ queueFile;
499753
500128
  stateFile;
499754
500129
  constructor(dir, host) {
499755
500130
  this.host = host;
@@ -499784,15 +500159,41 @@ var init_telegram_session_queue_delivery = __esmMin((() => {
499784
500159
  if (state === void 0) throw new Error("Telegram session queue checkpoint is missing");
499785
500160
  state = observeSessionQueue(state, position);
499786
500161
  if (JSON.stringify(state) !== before) writeSessionQueue(this.stateFile, state);
499787
- if (rebind) this.inFlight.clear();
500162
+ if (rebind) {
500163
+ this.inFlight.clear();
500164
+ this.controlsInFlight.clear();
500165
+ }
499788
500166
  this.boundSessionId = scope.sessionId;
499789
500167
  if (!deliver) return;
499790
- if (this.inFlight.size >= 16) return;
500168
+ for (const pending of pendingSessionQueue(state, scope.sessionId)) for (const line of readLines(this.queueFile, pending)) {
500169
+ if (!this.host.ownsChannel() || this.host.currentSessionId() !== scope.sessionId) return;
500170
+ const envelope = parseChannelEnvelope(line.text);
500171
+ if (envelope === void 0 || !isChannelStop(envelope)) continue;
500172
+ const key = `${line.range.fileId}:${line.range.start}:${line.range.end}`;
500173
+ if (this.controlsInFlight.has(key)) continue;
500174
+ this.controlsInFlight.add(key);
500175
+ const scopedEnvelope = {
500176
+ ...envelope,
500177
+ meta: {
500178
+ ...envelope.meta,
500179
+ queue_file_id: line.range.fileId,
500180
+ queue_start: String(line.range.start),
500181
+ queue_end: String(line.range.end)
500182
+ }
500183
+ };
500184
+ this.host.inject(scopedEnvelope, () => {
500185
+ if (!this.host.ownsChannel()) return;
500186
+ const current = readSessionQueue(this.stateFile);
500187
+ if (current === void 0) throw new Error("Telegram session queue checkpoint is missing");
500188
+ writeSessionQueue(this.stateFile, acknowledgeSessionQueue(current, scope.sessionId, line.range));
500189
+ this.controlsInFlight.delete(key);
500190
+ });
500191
+ }
499791
500192
  let delivered = 0;
499792
500193
  for (const pending of pendingSessionQueue(state, scope.sessionId)) for (const line of readLines(this.queueFile, pending)) {
499793
500194
  if (!this.host.ownsChannel() || this.host.currentSessionId() !== scope.sessionId) return;
499794
500195
  const key = `${line.range.fileId}:${line.range.start}:${line.range.end}`;
499795
- if (this.inFlight.has(key)) continue;
500196
+ if (this.inFlight.has(key) || this.controlsInFlight.has(key)) continue;
499796
500197
  const acknowledge = () => {
499797
500198
  if (!this.host.ownsChannel()) return;
499798
500199
  const current = readSessionQueue(this.stateFile);
@@ -499803,9 +500204,20 @@ var init_telegram_session_queue_delivery = __esmMin((() => {
499803
500204
  this.inFlight.add(key);
499804
500205
  const envelope = parseChannelEnvelope(line.text);
499805
500206
  if (envelope === void 0) acknowledge();
499806
- else this.host.inject(envelope, acknowledge);
500207
+ else if (isChannelStop(envelope)) {
500208
+ this.inFlight.delete(key);
500209
+ continue;
500210
+ } else this.host.inject({
500211
+ ...envelope,
500212
+ meta: {
500213
+ ...envelope.meta,
500214
+ queue_file_id: line.range.fileId,
500215
+ queue_start: String(line.range.start),
500216
+ queue_end: String(line.range.end)
500217
+ }
500218
+ }, acknowledge);
499807
500219
  delivered += 1;
499808
- if (delivered >= 16 || this.inFlight.size >= 16) return;
500220
+ if (delivered >= 16) return;
499809
500221
  }
499810
500222
  }
499811
500223
  };
@@ -525310,7 +525722,306 @@ var init_web = __esmMin((() => {
525310
525722
  WEB_CONFIRM = "confirm";
525311
525723
  WEB_CANCEL = "cancel";
525312
525724
  }));
525725
+ var session_search_exports = /* @__PURE__ */ __exportAll({
525726
+ SEARCH_LIMITS: () => SEARCH_LIMITS,
525727
+ handleSessionSearchCommand: () => handleSessionSearchCommand,
525728
+ searchSessionMessages: () => searchSessionMessages
525729
+ });
525730
+ async function searchSessionMessages(input) {
525731
+ const result = {
525732
+ scope: input.all ? "all" : "cwd",
525733
+ hits: [],
525734
+ partial: false,
525735
+ reasons: [],
525736
+ bytesRead: 0,
525737
+ sessionsScanned: 0,
525738
+ rejected: 0,
525739
+ malformed: 0
525740
+ };
525741
+ const reason = (value) => {
525742
+ result.partial = true;
525743
+ if (!result.reasons.includes(value)) result.reasons.push(value);
525744
+ };
525745
+ if (typeof input.query !== "string" || !input.query.trim() || input.query.length > 256) throw new Error("query-length");
525746
+ if (!isAbsolute(input.homeDir) || !isAbsolute(input.workDir)) throw new Error("absolute-scope-required");
525747
+ const limits = { ...SEARCH_LIMITS };
525748
+ for (const key of Object.keys(limits)) {
525749
+ const value = input.limits?.[key];
525750
+ if (value !== void 0) {
525751
+ if (!Number.isSafeInteger(value) || value < 1 || value > SEARCH_LIMITS[key]) throw new Error("invalid-budget");
525752
+ limits[key] = value;
525753
+ }
525754
+ }
525755
+ const start = performance$1.now(), home = resolve(input.homeDir), sessions = join(home, "sessions");
525756
+ const check = () => {
525757
+ if (input.signal?.aborted || input.isCurrent?.() === false) throw new SearchStop("cancelled");
525758
+ if (performance$1.now() - start >= limits.milliseconds) throw new SearchStop("time-limit");
525759
+ };
525760
+ const owner = typeof process.getuid === "function" ? process.getuid() : void 0;
525761
+ const identity = async (file) => lstat(file, { bigint: true });
525762
+ const same = (a, b) => String(a.dev) === String(b.dev) && String(a.ino) === String(b.ino) && a.mode === b.mode && a.uid === b.uid && a.gid === b.gid && a.nlink === b.nlink;
525763
+ const valid = (st, directory) => !st.isSymbolicLink() && (directory ? st.isDirectory() : st.isFile()) && (owner === void 0 || Number(st.uid) === owner && (Number(st.mode) & 18) === 0) && (directory || Number(st.nlink) === 1);
525764
+ async function safePath(file, bounded = true) {
525765
+ if (bounded) check();
525766
+ if (!inside(home, file) || await realpath(home) !== home) throw new Error("unsafe-path");
525767
+ let current = home;
525768
+ const parts = relative(home, file).split(sep), ancestors = [];
525769
+ for (let i = -1; i < parts.length; i++) {
525770
+ if (i >= 0) current = join(current, parts[i]);
525771
+ const st = await identity(current);
525772
+ if (!valid(st, i < parts.length - 1)) throw new Error("unsafe-owner-path");
525773
+ ancestors.push(st);
525774
+ }
525775
+ if (await realpath(file) !== file) throw new Error("unsafe-path");
525776
+ const leaf = await identity(file);
525777
+ if (!valid(leaf, false) || !same(leaf, ancestors.at(-1))) throw new Error("file-changed");
525778
+ if (bounded) check();
525779
+ return {
525780
+ leaf,
525781
+ ancestors
525782
+ };
525783
+ }
525784
+ const samePath = (a, b) => a.ancestors.length === b.ancestors.length && a.ancestors.every((st, i) => same(st, b.ancestors[i])) && same(a.leaf, b.leaf);
525785
+ async function* lines(file, byteLimit, label) {
525786
+ const before = await safePath(file);
525787
+ const handle = await open(file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
525788
+ try {
525789
+ const opened = await handle.stat({ bigint: true });
525790
+ if (!valid(opened, false) || !same(opened, before.leaf)) throw new Error("file-changed");
525791
+ const bound = await safePath(file);
525792
+ if (!samePath(before, bound) || !same(opened, bound.leaf)) throw new Error("file-changed");
525793
+ const openedSize = Number(opened.size), end = Math.min(openedSize, byteLimit);
525794
+ if (openedSize > end) reason(label);
525795
+ const validateFinish = async () => {
525796
+ const after = await handle.stat({ bigint: true });
525797
+ const finalPath = await safePath(file, false);
525798
+ if (!valid(after, false) || !same(opened, after) || !samePath(bound, finalPath) || !same(after, finalPath.leaf) || after.size !== opened.size || after.mtimeNs !== opened.mtimeNs || after.ctimeNs !== opened.ctimeNs) throw new Error("file-changed");
525799
+ };
525800
+ try {
525801
+ let position = 0, line = 1, offset = 0, pending = Buffer.alloc(0), oversized = false;
525802
+ while (position < end) {
525803
+ check();
525804
+ if (result.bytesRead >= limits.totalBytes) throw new SearchStop("total-byte-limit");
525805
+ const size = Math.min(32768, end - position, limits.totalBytes - result.bytesRead);
525806
+ const buffer = Buffer.allocUnsafe(size);
525807
+ const read = await handle.read(buffer, 0, size, position);
525808
+ result.bytesRead += read.bytesRead;
525809
+ check();
525810
+ if (read.bytesRead === 0) throw new Error("file-changed");
525811
+ position += read.bytesRead;
525812
+ const chunk = buffer.subarray(0, read.bytesRead);
525813
+ let at = 0;
525814
+ while (at < chunk.length) {
525815
+ check();
525816
+ const newline = chunk.indexOf(10, at), stop = newline < 0 ? chunk.length : newline;
525817
+ if (!oversized) if (pending.length + stop - at > limits.lineBytes) {
525818
+ pending = Buffer.alloc(0);
525819
+ oversized = true;
525820
+ reason("line-limit");
525821
+ } else pending = Buffer.concat([pending, chunk.subarray(at, stop)]);
525822
+ if (newline < 0) break;
525823
+ if (!oversized) yield {
525824
+ raw: pending,
525825
+ line,
525826
+ offset
525827
+ };
525828
+ offset = position - chunk.length + newline + 1;
525829
+ line++;
525830
+ pending = Buffer.alloc(0);
525831
+ oversized = false;
525832
+ at = newline + 1;
525833
+ }
525834
+ }
525835
+ if (pending.length && !oversized && position === openedSize) yield {
525836
+ raw: pending,
525837
+ line,
525838
+ offset
525839
+ };
525840
+ } finally {
525841
+ await validateFinish();
525842
+ }
525843
+ } finally {
525844
+ await handle.close();
525845
+ }
525846
+ }
525847
+ const parse = (raw) => {
525848
+ if (raw.length === 0 || raw.toString("utf8").trim() === "") return void 0;
525849
+ try {
525850
+ if (!isUtf8(raw)) throw new Error("utf8");
525851
+ return JSON.parse(raw.toString("utf8"));
525852
+ } catch {
525853
+ result.malformed++;
525854
+ reason("malformed-record");
525855
+ return;
525856
+ }
525857
+ };
525858
+ try {
525859
+ check();
525860
+ const entries = /* @__PURE__ */ new Map();
525861
+ try {
525862
+ const stagedEntries = /* @__PURE__ */ new Map();
525863
+ for await (const row of lines(join(home, "session_index.jsonl"), limits.indexBytes, "index-byte-limit")) {
525864
+ const e = parse(row.raw);
525865
+ if (!e || typeof e.sessionId !== "string" || typeof e.sessionDir !== "string" || typeof e.workDir !== "string" || !isAbsolute(e.sessionDir) || !isAbsolute(e.workDir) || !inside(sessions, resolve(e.sessionDir)) || basename(resolve(e.sessionDir)) !== e.sessionId || !/^[a-zA-Z0-9_-]+$/.test(e.sessionId)) {
525866
+ if (e !== void 0) {
525867
+ result.rejected++;
525868
+ reason("rejected-index-entry");
525869
+ }
525870
+ continue;
525871
+ }
525872
+ if (!stagedEntries.has(e.sessionId) && stagedEntries.size >= limits.sessions) {
525873
+ reason("session-limit");
525874
+ break;
525875
+ }
525876
+ stagedEntries.set(e.sessionId, {
525877
+ id: e.sessionId,
525878
+ dir: resolve(e.sessionDir),
525879
+ workDir: resolve(e.workDir)
525880
+ });
525881
+ }
525882
+ for (const [id, entry] of stagedEntries) entries.set(id, entry);
525883
+ } catch (error) {
525884
+ if (error instanceof SearchStop) throw error;
525885
+ result.rejected++;
525886
+ reason("index-unavailable");
525887
+ if (error instanceof Error && error.message === "file-changed") reason("file-changed");
525888
+ }
525889
+ for (const entry of entries.values()) {
525890
+ if (!input.all && entry.workDir !== resolve(input.workDir)) continue;
525891
+ check();
525892
+ const wire = join(entry.dir, "agents", "main", "wire.jsonl");
525893
+ result.sessionsScanned++;
525894
+ try {
525895
+ const stagedHits = [];
525896
+ let hitLimit = false;
525897
+ rows: for await (const row of lines(wire, limits.fileBytes, "file-byte-limit")) {
525898
+ const record = parse(row.raw);
525899
+ const message = record?.type === "context.append_message" ? record.message : void 0;
525900
+ if (!message || message.role !== "user" && message.role !== "assistant" || !Array.isArray(message.content)) continue;
525901
+ const origin = message.origin;
525902
+ if (origin !== void 0 && (origin === null || typeof origin !== "object" || Array.isArray(origin) || typeof origin.kind !== "string")) {
525903
+ result.malformed++;
525904
+ reason("malformed-record");
525905
+ continue;
525906
+ }
525907
+ try {
525908
+ if (input.isInternalMessage(message)) continue;
525909
+ } catch {
525910
+ result.malformed++;
525911
+ reason("malformed-record");
525912
+ continue;
525913
+ }
525914
+ for (let partIndex = 0; partIndex < message.content.length; partIndex++) {
525915
+ const part = message.content[partIndex];
525916
+ if (part?.type !== "text" || typeof part.text !== "string") continue;
525917
+ for (let from = 0; from <= part.text.length - input.query.length;) {
525918
+ check();
525919
+ const found = part.text.indexOf(input.query, from);
525920
+ if (found < 0) break;
525921
+ stagedHits.push({
525922
+ sessionId: entry.id,
525923
+ wire: "agents/main/wire.jsonl",
525924
+ line: row.line,
525925
+ recordByteOffset: row.offset,
525926
+ partIndex,
525927
+ utf16Offset: found,
525928
+ utf16Length: input.query.length,
525929
+ role: message.role,
525930
+ preview: part.text.slice(Math.max(0, found - 60), found + input.query.length + 60)
525931
+ });
525932
+ if (result.hits.length + stagedHits.length >= limits.hits) {
525933
+ hitLimit = true;
525934
+ break rows;
525935
+ }
525936
+ from = found + 1;
525937
+ }
525938
+ }
525939
+ }
525940
+ result.hits.push(...stagedHits);
525941
+ if (hitLimit) throw new SearchStop("hit-limit");
525942
+ } catch (error) {
525943
+ if (error instanceof SearchStop) throw error;
525944
+ result.rejected++;
525945
+ reason("wire-unavailable");
525946
+ if (error instanceof Error && error.message === "file-changed") reason("file-changed");
525947
+ }
525948
+ }
525949
+ } catch (error) {
525950
+ if (!(error instanceof SearchStop)) throw error;
525951
+ reason(error.message);
525952
+ }
525953
+ return result;
525954
+ }
525955
+ async function handleSessionSearchCommand(host, args, isInternalMessage, requestController) {
525956
+ if (requestController?.signal.aborted) return;
525957
+ const text = args.trim();
525958
+ if (host.getChannelCommandContext?.() !== void 0 || host.session?.connectionKind === "gateway") {
525959
+ host.showError("local-console-only");
525960
+ return;
525961
+ }
525962
+ if (text === "--cancel") {
525963
+ active.get(host)?.abort();
525964
+ active.delete(host);
525965
+ return;
525966
+ }
525967
+ const all = text.startsWith("--all "), query = all ? text.slice(6).trim() : text;
525968
+ if (!query || query.length > 256 || query.startsWith("--")) {
525969
+ host.showStatus(JSON.stringify({
525970
+ format: "blun-session-search-json-v1",
525971
+ usage: "/sessions search [--all] <text> | /sessions search --cancel"
525972
+ }));
525973
+ return;
525974
+ }
525975
+ active.get(host)?.abort();
525976
+ const controller = requestController ?? new AbortController();
525977
+ active.set(host, controller);
525978
+ const session = host.session, workDir = host.state.appState.workDir, sessionId = host.state.appState.sessionId;
525979
+ const harness = host.harness, homeDir = harness.homeDir;
525980
+ const current = () => !host.aborted && !controller.signal.aborted && active.get(host) === controller && host.session === session && host.session?.connectionKind !== "gateway" && host.harness === harness && host.harness.homeDir === homeDir && host.state.appState.workDir === workDir && host.state.appState.sessionId === sessionId && host.getChannelCommandContext?.() === void 0;
525981
+ try {
525982
+ const result = await searchSessionMessages({
525983
+ homeDir,
525984
+ workDir,
525985
+ query,
525986
+ all,
525987
+ signal: controller.signal,
525988
+ isCurrent: current,
525989
+ isInternalMessage
525990
+ });
525991
+ if (current()) host.showStatus(JSON.stringify({
525992
+ format: "blun-session-search-json-v1",
525993
+ ...result
525994
+ }, null, 2).replace(/[\u007f-\u009f\u202a-\u202e\u2066-\u2069]/g, (char) => `\\u${char.charCodeAt(0).toString(16).padStart(4, "0")}`));
525995
+ } catch (error) {
525996
+ if (current()) host.showError(error instanceof Error ? error.message : "search-failed");
525997
+ } finally {
525998
+ if (active.get(host) === controller) active.delete(host);
525999
+ }
526000
+ }
526001
+ var init_session_search = __esmMin((() => {
526002
+ SEARCH_LIMITS = Object.freeze({
526003
+ indexBytes: 1024 * 1024,
526004
+ fileBytes: 4 * 1024 * 1024,
526005
+ totalBytes: 16 * 1024 * 1024,
526006
+ lineBytes: 256 * 1024,
526007
+ sessions: 128,
526008
+ hits: 100,
526009
+ milliseconds: 1500
526010
+ });
526011
+ SearchStop = class extends Error {};
526012
+ active = /* @__PURE__ */ new WeakMap();
526013
+ inside = (root, child) => {
526014
+ const rel = relative(root, child);
526015
+ return rel !== "" && !isAbsolute(rel) && rel !== ".." && !rel.startsWith(`..${sep}`);
526016
+ };
526017
+ }));
526018
+ function tryCancelSessionSearchInput(host, text) {
526019
+ if (!/^\/sessions[ \t]+search[ \t]+--cancel$/.test(text.trim()) || host.getChannelCommandContext?.() !== void 0 || host.session?.connectionKind === "gateway") return false;
526020
+ sessionSearchRequests.get(host)?.abort();
526021
+ return true;
526022
+ }
525313
526023
  function dispatchInput(host, text) {
526024
+ if (tryCancelSessionSearchInput(host, text)) return Promise.resolve();
525314
526025
  if (isExperimentalFlagEnabled("multiline_chat_input") && isMultilineChatInput(text)) {
525315
526026
  host.sendNormalUserInput(text);
525316
526027
  return Promise.resolve();
@@ -525453,6 +526164,24 @@ async function handleBuiltInSlashCommand(host, name, args, invokedName = name) {
525453
526164
  host.state.ui.requestRender();
525454
526165
  return;
525455
526166
  case "sessions":
526167
+ if (/^search(?:\s|$)/.test(args.trim())) {
526168
+ const searchOwner = host.session;
526169
+ const searchWorkDir = host.state.appState.workDir;
526170
+ const searchSessionId = host.state.appState.sessionId;
526171
+ const searchHarness = host.harness;
526172
+ const searchHomeDir = searchHarness.homeDir;
526173
+ sessionSearchRequests.get(host)?.abort();
526174
+ const searchController = new AbortController();
526175
+ sessionSearchRequests.set(host, searchController);
526176
+ try {
526177
+ const { handleSessionSearchCommand } = await Promise.resolve().then(() => (init_session_search(), session_search_exports));
526178
+ if (searchController.signal.aborted || sessionSearchRequests.get(host) !== searchController || host.aborted || host.session !== searchOwner || host.state.appState.workDir !== searchWorkDir || host.state.appState.sessionId !== searchSessionId || host.harness !== searchHarness || host.harness.homeDir !== searchHomeDir) return;
526179
+ await handleSessionSearchCommand(host, args.trim().slice(6), isInternalMessage, searchController);
526180
+ } finally {
526181
+ if (sessionSearchRequests.get(host) === searchController) sessionSearchRequests.delete(host);
526182
+ }
526183
+ return;
526184
+ }
525456
526185
  if ((host.session?.connectionKind === "gateway" || isExperimentalFlagEnabled("session_references")) && args.trim().length > 0) await host.showSessionPicker(args.trim());
525457
526186
  else await host.showSessionPicker();
525458
526187
  return;
@@ -525631,6 +526360,7 @@ async function handleBuiltInSlashCommand(host, name, args, invokedName = name) {
525631
526360
  }
525632
526361
  }
525633
526362
  var init_dispatch = __esmMin((() => {
526363
+ init_export_markdown();
525634
526364
  init_dispatch_swarm_copy();
525635
526365
  init_activation();
525636
526366
  init_elevated();
@@ -525669,6 +526399,7 @@ var init_dispatch = __esmMin((() => {
525669
526399
  init_telegram_access();
525670
526400
  init_undo();
525671
526401
  init_web();
526402
+ sessionSearchRequests = /* @__PURE__ */ new WeakMap();
525672
526403
  }));
525673
526404
  var init_commands = __esmMin((() => {
525674
526405
  init_experimental_flags();
@@ -527798,7 +528529,7 @@ function singleLine$1(text) {
527798
528529
  return sanitizeTerminalText(text).replaceAll(/\s+/g, " ").trim();
527799
528530
  }
527800
528531
  function sessionSearchText(session) {
527801
- return singleLine$1(`${session.id} ${session.title ?? ""}`);
528532
+ return singleLine$1(`${session.id} ${session.title ?? ""} ${session.work_dir ?? ""} ${session.last_prompt ?? ""}`);
527802
528533
  }
527803
528534
  var ELLIPSIS$3, SessionPickerComponent;
527804
528535
  var init_session_picker$1 = __esmMin((() => {
@@ -530653,16 +531384,22 @@ var init_channel_queue_deadline = __esmMin((() => {
530653
531384
  deliveryInFlight = false;
530654
531385
  pendingReleaseCount = 0;
530655
531386
  disposed = false;
530656
- constructor(host) {
531387
+ scope;
531388
+ constructor(host) {
530657
531389
  this.host = host;
531390
+ this.scope = host.deliveryScope?.();
531391
+ }
531392
+ sync() {
531393
+ this.refreshScope();
530658
531394
  }
530659
- sync() {}
530660
531395
  requestDeliveryAtSafePoint() {
531396
+ this.refreshScope();
530661
531397
  if (this.retainReleaseWhileDeliveryIsInFlight()) return;
530662
531398
  if (this.host.hasWaitingWork() && !this.host.canDeliverWork()) return;
530663
531399
  this.requestDelivery();
530664
531400
  }
530665
531401
  requestDeliveryNow() {
531402
+ this.refreshScope();
530666
531403
  if (this.retainReleaseWhileDeliveryIsInFlight()) return;
530667
531404
  if (this.host.hasWaitingWork() && !this.host.canDeliverWork()) return;
530668
531405
  this.requestDelivery();
@@ -530681,7 +531418,14 @@ var init_channel_queue_deadline = __esmMin((() => {
530681
531418
  this.pendingReleaseCount += 1;
530682
531419
  this.pumpDelivery();
530683
531420
  }
530684
- pumpDelivery() {
531421
+ refreshScope() {
531422
+ const scope = this.host.deliveryScope?.();
531423
+ if (scope === this.scope) return;
531424
+ this.scope = scope;
531425
+ this.pendingReleaseCount = 0;
531426
+ }
531427
+ pumpDelivery() {
531428
+ this.refreshScope();
530685
531429
  if (this.disposed || this.deliveryInFlight || this.pendingReleaseCount === 0) return;
530686
531430
  if (!this.host.hasWaitingWork() || !this.host.canDeliverWork()) {
530687
531431
  this.pendingReleaseCount = 0;
@@ -530689,7 +531433,8 @@ var init_channel_queue_deadline = __esmMin((() => {
530689
531433
  }
530690
531434
  this.pendingReleaseCount -= 1;
530691
531435
  this.deliveryInFlight = true;
530692
- Promise.resolve().then(() => this.host.deliverOne()).catch(() => false).finally(() => {
531436
+ const scope = this.host.deliveryScope?.();
531437
+ Promise.resolve().then(() => this.disposed || scope !== this.host.deliveryScope?.() || !this.host.hasWaitingWork() || !this.host.canDeliverWork() ? false : this.host.deliverOne()).catch(() => false).finally(() => {
530693
531438
  this.deliveryInFlight = false;
530694
531439
  this.pumpDelivery();
530695
531440
  });
@@ -530697,6 +531442,81 @@ var init_channel_queue_deadline = __esmMin((() => {
530697
531442
  };
530698
531443
  }));
530699
531444
  var REMOTE_COMMANDS, REMOTE_COMMAND_LIST;
531445
+ var init_active_input_delivery = __esmMin((() => {
531446
+ ActiveInputDelivery = class {
531447
+ host;
531448
+ attempts = /* @__PURE__ */ new Map();
531449
+ pumping = false;
531450
+ dirty = false;
531451
+ ended = false;
531452
+ constructor(host) {
531453
+ this.host = host;
531454
+ }
531455
+ has(item) {
531456
+ return item !== void 0 && this.attempts.has(item);
531457
+ }
531458
+ endTurn() {
531459
+ this.ended = true;
531460
+ for (const [item, attempt] of this.attempts) if (attempt.terminal) this.attempts.delete(item);
531461
+ this.host.retry();
531462
+ }
531463
+ cancel() {
531464
+ for (const attempt of this.attempts.values()) attempt.abort.abort();
531465
+ this.attempts.clear();
531466
+ }
531467
+ request() {
531468
+ if (this.ended) return;
531469
+ this.dirty = true;
531470
+ if (this.pumping) return;
531471
+ this.pumping = true;
531472
+ this.pump().finally(() => {
531473
+ this.pumping = false;
531474
+ if (this.dirty) this.request();
531475
+ });
531476
+ }
531477
+ async pump() {
531478
+ do {
531479
+ this.dirty = false;
531480
+ for (const item of this.host.items()) {
531481
+ const prior = this.attempts.get(item);
531482
+ if (prior !== void 0) {
531483
+ if (!prior.accepted) return;
531484
+ continue;
531485
+ }
531486
+ const attempt = {
531487
+ accepted: false,
531488
+ terminal: false,
531489
+ abort: new AbortController()
531490
+ };
531491
+ this.attempts.set(item, attempt);
531492
+ let admitted;
531493
+ const acceptance = new Promise((resolve) => {
531494
+ admitted = resolve;
531495
+ });
531496
+ this.host.send(item, attempt.abort.signal, () => {
531497
+ attempt.accepted = true;
531498
+ admitted();
531499
+ }).then((disposition) => {
531500
+ if (attempt.abort.signal.aborted || this.attempts.get(item) !== attempt) return;
531501
+ attempt.terminal = true;
531502
+ if (disposition === "context") {
531503
+ this.attempts.delete(item);
531504
+ this.host.commit(item);
531505
+ }
531506
+ if (disposition !== "context" && this.ended) {
531507
+ this.attempts.delete(item);
531508
+ this.host.retry();
531509
+ }
531510
+ }).catch((error) => {
531511
+ if (!attempt.abort.signal.aborted) this.host.error(error);
531512
+ }).finally(admitted);
531513
+ await acceptance;
531514
+ if (attempt.abort.signal.aborted || !attempt.accepted) return;
531515
+ }
531516
+ } while (this.dirty);
531517
+ }
531518
+ };
531519
+ }));
530700
531520
  var init_channel_command$1 = __esmMin((() => {
530701
531521
  REMOTE_COMMANDS = new Set([
530702
531522
  "loop",
@@ -530712,6 +531532,7 @@ var init_channel_command$1 = __esmMin((() => {
530712
531532
  REMOTE_COMMAND_LIST = "/loop [interval] [prompt]\n/loop status|pause|resume|stop\n/goal\n/idea\n/chancenradar\n/curiosity\n/scout\n/reload\n/memory status|on|off\n/befehle";
530713
531533
  }));
530714
531534
  function channelCommandInput(envelope) {
531535
+ if (isChannelStop(envelope)) return "/stop";
530715
531536
  if (!channelMessageAddressed(envelope) || envelope.meta["addressed"]?.trim().toLowerCase() === "semantic") return void 0;
530716
531537
  const parsed = parseSlashInput(envelope.text.trim());
530717
531538
  if (parsed === null) return void 0;
@@ -530720,6 +531541,7 @@ function channelCommandInput(envelope) {
530720
531541
  return parsed.args.length === 0 ? `/${name}` : `/${name} ${parsed.args}`;
530721
531542
  }
530722
531543
  function channelCommandCanInterrupt(input) {
531544
+ if (input.trim() === "/stop") return true;
530723
531545
  const parsed = parseSlashInput(input);
530724
531546
  if (parsed?.name === "befehle") return true;
530725
531547
  if (parsed === null) return false;
@@ -530742,7 +531564,8 @@ var init_channel_command = __esmMin((() => {
530742
531564
  init_channel_command$1();
530743
531565
  init_channel_injection();
530744
531566
  init_event_payload();
530745
- ChannelCommandController = class {
531567
+ init_channel_control();
531568
+ ChannelCommandController = class {
530746
531569
  host;
530747
531570
  execution = new AsyncLocalStorage();
530748
531571
  constructor(host) {
@@ -530752,7 +531575,8 @@ var init_channel_command = __esmMin((() => {
530752
531575
  const execution = this.execution.getStore();
530753
531576
  return execution?.active ? {
530754
531577
  input: execution.input,
530755
- chatId: execution.envelope.meta.chat_id
531578
+ chatId: execution.envelope.meta.chat_id,
531579
+ envelope: execution.envelope
530756
531580
  } : void 0;
530757
531581
  }
530758
531582
  commit() {
@@ -536441,7 +537265,11 @@ var init_session_event_handler = __esmMin((() => {
536441
537265
  });
536442
537266
  this.host.resetLivePane();
536443
537267
  this.host.requestQueueDrain();
536444
- } else { this.host.setAppState({ isCompacting: false }); this.host.steerQueueFlushPrefix(); }
537268
+ } else {
537269
+ this.host.setAppState({ isCompacting: false });
537270
+ this.host.steerQueueFlushPrefix();
537271
+ }
537272
+ this.host.releaseChannelQueueAtSafePoint();
536445
537273
  }
536446
537274
  handleBackgroundTaskEvent(event) {
536447
537275
  const { state } = this.host;
@@ -544285,7 +545113,10 @@ var init_blun_tui = __esmMin((() => {
544285
545113
  init_transcript_id();
544286
545114
  init_blun_tui_copy();
544287
545115
  DETACH_HINT_DISPLAY_MS = 4e3;
544288
- BlunTUI = class {
545116
+ init_queue_deadline_watchdog();
545117
+ init_stopped_input_scopes();
545118
+ init_active_input_delivery();
545119
+ BlunTUI = class {
544289
545120
  gatewayStartup;
544290
545121
  localHarness;
544291
545122
  gatewayLifetime = new AbortController();
@@ -544374,7 +545205,12 @@ var init_blun_tui = __esmMin((() => {
544374
545205
  telegramSessionScope;
544375
545206
  channelPreamble = createChannelPreambleState();
544376
545207
  channelQueueDeadline;
544377
- activeApprovalPanel;
545208
+ queueDeadlineWatchdog;
545209
+ queueDeadlineStatus;
545210
+ getQueueDeadlineStatus() {
545211
+ return this.queueDeadlineStatus;
545212
+ }
545213
+ activeApprovalPanel;
544378
545214
  approvalPreview;
544379
545215
  onExit;
544380
545216
  setupHandoff;
@@ -544460,10 +545296,19 @@ var init_blun_tui = __esmMin((() => {
544460
545296
  this.appearanceBasePalette = currentTheme.palette;
544461
545297
  this.resolvedAutoTheme = currentTheme.palette === lightColors ? "light" : "dark";
544462
545298
  currentTheme.setPalette(applyAppearanceToPalette(currentTheme.palette, initialAppState.appearance));
545299
+ this.queueDeadlineWatchdog = new QueueDeadlineWatchdog(() => ({
545300
+ owner: this.session,
545301
+ entries: [...this.queueSteerInFlight?.items ?? [], ...this.state.queuedMessages],
545302
+ reason: this.queueDeadlineBlockingReason()
545303
+ }), (status) => {
545304
+ this.queueDeadlineStatus = status;
545305
+ this.state.ui.requestRender();
545306
+ });
544463
545307
  this.channelQueueDeadline = new ChannelQueueDeadlineController({
544464
545308
  hasWaitingWork: () => this.hasWaitingChannelMessage(),
544465
545309
  canDeliverWork: () => this.canDeliverQueuedChannelHead(),
544466
- deliverOne: () => this.deliverQueuedChannelHead()
545310
+ deliverOne: () => this.deliverQueuedChannelHead(),
545311
+ deliveryScope: () => this.session
544467
545312
  });
544468
545313
  this.managedQuotaWarningController = new ManagedQuotaWarningController({ onChange: (warning) => {
544469
545314
  this.state.quotaWarning.setMessage(warning === void 0 ? void 0 : formatManagedQuotaWarning(warning));
@@ -545206,6 +546051,7 @@ var init_blun_tui = __esmMin((() => {
545206
546051
  }
545207
546052
  this.loopCountdown.dispose();
545208
546053
  this.channelQueueDeadline?.dispose();
546054
+ this.queueDeadlineWatchdog?.dispose();
545209
546055
  try {
545210
546056
  await this.telegramChannel?.stop();
545211
546057
  } catch (error) {
@@ -545294,6 +546140,7 @@ var init_blun_tui = __esmMin((() => {
545294
546140
  this.isShuttingDown = true;
545295
546141
  this.unregisterSignalHandlers();
545296
546142
  this.channelQueueDeadline?.dispose();
546143
+ this.queueDeadlineWatchdog?.dispose();
545297
546144
  this.telegramChannel?.stopNow();
545298
546145
  this.telegramChannel = void 0;
545299
546146
  restoreTerminalModes();
@@ -545360,6 +546207,7 @@ var init_blun_tui = __esmMin((() => {
545360
546207
  }
545361
546208
  const historyText = wasBashMode ? `!${text}` : text;
545362
546209
  this.persistInputHistory(historyText);
546210
+ if (!wasBashMode && tryCancelSessionSearchInput(this, text)) return;
545363
546211
  if (this.editorReplacementActive || this.queueCommandRunning || this.localShellConsentRequest !== void 0) {
545364
546212
  if (wasBashMode) this.enqueueMessage(text, void 0, "bash");
545365
546213
  else if (text.trimStart().startsWith("/") && !(isExperimentalFlagEnabled("multiline_chat_input") && isMultilineChatInput(text))) {
@@ -545581,13 +546429,17 @@ var init_blun_tui = __esmMin((() => {
545581
546429
  return this.state.queuedMessages.some((item) => item.mode === "channel");
545582
546430
  }
545583
546431
  canInterruptForQueuedChannel() {
546432
+ if (this.session !== void 0 && (this.stoppedInputSession === this.session || this.stoppedInputScopes?.get(this.session, this.state.queuedMessages[0]?.agentId ?? this.interactiveAgentId) !== void 0)) return false;
545584
546433
  if (this.hasPendingQueueCommandCancellation()) return false;
545585
546434
  const item = this.state.queuedMessages[0];
545586
546435
  if (/^[1-9]\d*$/u.test(this.pendingChannelReplyGuard?.chatId ?? "") && item?.channelChatId?.startsWith("-") === true) return false;
545587
546436
  return item?.mode === "channel" && item.channelContextOnly !== true && this.session !== void 0 && this.queueSteerInFlight === void 0 && this.manualPromptInFlight === void 0 && this.localShellConsentRequest === void 0 && !this.deferUserMessages && !this.state.appState.isCompacting && this.state.appState.streamingPhase !== "idle" && this.state.appState.streamingPhase !== "shell" && this.shellOutputStreams.size === 0 && !this.streamingUI.hasActiveToolCalls();
545588
546437
  }
545589
546438
  canDeliverQueuedChannelHead() {
546439
+ if (this.session !== void 0 && (this.stoppedInputSession === this.session || this.stoppedInputScopes?.get(this.session, this.state.queuedMessages[0]?.agentId ?? this.interactiveAgentId) !== void 0)) return false;
546440
+ if (this.activeInputDelivery?.has(this.state.queuedMessages[0])) return false;
545590
546441
  if (this.hasPendingQueueCommandCancellation()) return false;
546442
+ if (this.state.appState.isCompacting || this.streamingUI.hasActiveToolCalls() || this.shellOutputStreams.size > 0 || this.state.appState.streamingPhase === "shell") return false;
545591
546443
  const item = this.state.queuedMessages[0];
545592
546444
  if (this.isShuttingDown || this.queueCommandRunning || this.localShellConsentRequest !== void 0 || this.queueSteerInFlight !== void 0 || this.manualPromptInFlight !== void 0 || this.editorReplacementActive || this.deferUserMessages || this.session === void 0 || this.state.appState.model.trim().length === 0 || item?.mode !== "channel") return false;
545593
546445
  const guard = this.pendingChannelReplyGuard;
@@ -545630,6 +546482,7 @@ var init_blun_tui = __esmMin((() => {
545630
546482
  ...item,
545631
546483
  channelTranscriptRendered: transcriptRendered
545632
546484
  };
546485
+ this.queueDeadlineWatchdog?.transfer(item, queuedItem);
545633
546486
  const previousGuard = this.pendingChannelReplyGuard;
545634
546487
  let installedGuard;
545635
546488
  if (previousGuard === void 0 && item.channelChatId !== void 0) {
@@ -545695,6 +546548,11 @@ var init_blun_tui = __esmMin((() => {
545695
546548
  this.commitQueuedSteerIfReady(inFlight);
545696
546549
  }
545697
546550
  restoreQueuedSteerAtTurnEnd(turnId) {
546551
+ if (this.activeInputScope === JSON.stringify([
546552
+ this.session?.id,
546553
+ this.interactiveAgentId,
546554
+ String(turnId)
546555
+ ])) this.activeInputDelivery?.endTurn();
545698
546556
  const inFlight = this.queueSteerInFlight;
545699
546557
  if (inFlight === void 0 || inFlight.turnId !== String(turnId)) return;
545700
546558
  inFlight.turnEnded = true;
@@ -545723,15 +546581,177 @@ var init_blun_tui = __esmMin((() => {
545723
546581
  return false;
545724
546582
  }
545725
546583
  syncChannelQueueDeadline() {
546584
+ this.admitActiveQueuedInputs();
545726
546585
  this.channelQueueDeadline?.sync();
546586
+ this.queueDeadlineWatchdog?.sync();
546587
+ }
546588
+ queueDeadlineBlockingReason() {
546589
+ if (this.isShuttingDown) return "shutdown";
546590
+ if (this.session === void 0) return "no_session";
546591
+ if (this.state.appState.isCompacting) return "compaction";
546592
+ if (this.streamingUI.hasActiveToolCalls() || this.shellOutputStreams.size > 0 || this.state.appState.streamingPhase === "shell") return "tool_or_shell";
546593
+ if (this.activeInputDelivery?.has(this.state.queuedMessages[0]) || this.queueSteerInFlight !== void 0 || this.manualPromptInFlight !== void 0) return "receipt_pending";
546594
+ if (this.deferUserMessages || this.queueCommandRunning || this.localShellConsentRequest !== void 0 || this.editorReplacementActive || this.hasPendingQueueCommandCancellation()) return "admission_barrier";
546595
+ const item = this.state.queuedMessages[0];
546596
+ if (this.pendingChannelReplyGuard !== void 0 && (item?.mode !== "channel" || item.channelChatId !== this.pendingChannelReplyGuard.chatId)) return "chat_boundary";
546597
+ if (this.state.appState.model.trim().length === 0) return "no_model";
546598
+ if (item?.mode === "command" || item?.mode === "bash" || item !== void 0 && item.mode !== "channel" && queueSteerPrefixLength([item], this.interactiveAgentId, 1) === 0) return "fifo_barrier";
546599
+ return this.state.appState.streamingPhase === "idle" ? "idle_admission_pending" : "model_step_or_safe_point";
546600
+ }
546601
+ stoppedInputScopes;
546602
+ get stoppedInputSession() {
546603
+ const session = this.session;
546604
+ return session !== void 0 && this.stoppedInputScopes?.get(session, this.interactiveAgentId) !== void 0 ? session : void 0;
546605
+ }
546606
+ set stoppedInputSession(session) {
546607
+ if (session === void 0) {
546608
+ if (this.session !== void 0) this.stoppedInputScopes?.clear(this.session, this.interactiveAgentId);
546609
+ return;
546610
+ }
546611
+ const turnId = this.streamingUI.getTurnContext().turnId;
546612
+ const agentId = this.interactiveAgentId;
546613
+ const command = this.channelCommands?.context;
546614
+ const activeChat = this.activeInputScope === JSON.stringify([
546615
+ session.id,
546616
+ agentId,
546617
+ turnId
546618
+ ]) ? this.activeInputChat : void 0;
546619
+ this.stoppedInputScopes ??= new StoppedInputScopes();
546620
+ this.stoppedInputScopes.stop(session, {
546621
+ sessionId: session.id,
546622
+ agentId,
546623
+ turnId,
546624
+ chatId: command?.input === "/stop" ? command.chatId : this.pendingChannelReplyGuard?.chatId ?? activeChat,
546625
+ runtimeScope: this.gatewayResetTurn?.session === session ? this.gatewayResetTurn.scope : void 0
546626
+ });
546627
+ }
546628
+ get stoppedQueueBoundary() {
546629
+ return this.session === void 0 ? void 0 : this.stoppedInputScopes?.get(this.session, this.interactiveAgentId)?.boundary;
546630
+ }
546631
+ set stoppedQueueBoundary(boundary) {
546632
+ const scope = this.session === void 0 ? void 0 : this.stoppedInputScopes?.get(this.session, this.interactiveAgentId);
546633
+ if (scope !== void 0) scope.boundary = boundary;
545727
546634
  }
545728
- releaseChannelQueueAtSafePoint() {
545729
- this.channelQueueDeadline.requestDeliveryAtSafePoint();
546635
+ channelOwnsStoppedInput(chatId) {
546636
+ const scope = this.session === void 0 ? void 0 : this.stoppedInputScopes?.get(this.session, this.interactiveAgentId);
546637
+ return scope === void 0 || scope.chatId === chatId;
546638
+ }
546639
+ activeInputRequests;
546640
+ activeInputDelivery;
546641
+ activeInputScope;
546642
+ activeInputChat;
546643
+ admitActiveQueuedInputs() {
546644
+ const session = this.session;
546645
+ if (!isExperimentalFlagEnabled("queue_policies") || session === void 0 || this.stoppedInputSession === session || this.isShuttingDown || this.state.appState.streamingPhase === "idle" || this.state.appState.streamingPhase === "shell" || this.queueSteerInFlight !== void 0 || this.manualPromptInFlight !== void 0 || this.deferUserMessages || this.queueCommandRunning || this.editorReplacementActive || this.localShellConsentRequest !== void 0 || this.hasPendingQueueCommandCancellation() || this.queuePolicyBlocksInput(session)) return false;
546646
+ const turn = this.streamingUI.getTurnContext().turnId;
546647
+ if (turn === void 0 || !/^\d+$/.test(turn) || !Number.isSafeInteger(Number(turn))) return false;
546648
+ const agentId = this.interactiveAgentId;
546649
+ const scope = JSON.stringify([
546650
+ session.id,
546651
+ agentId,
546652
+ turn
546653
+ ]);
546654
+ if (this.activeInputScope !== scope) {
546655
+ this.activeInputDelivery?.cancel();
546656
+ this.activeInputScope = scope;
546657
+ this.activeInputChat = this.pendingChannelReplyGuard?.chatId;
546658
+ const current = () => this.session === session && this.activeInputScope === scope && this.interactiveAgentId === agentId;
546659
+ this.activeInputDelivery = new ActiveInputDelivery({
546660
+ items: () => {
546661
+ if (!current()) return [];
546662
+ const result = [];
546663
+ for (const item of this.state.queuedMessages) {
546664
+ if ((item.agentId ?? "main") !== agentId) break;
546665
+ if (this.activeInputDelivery?.has(item)) {
546666
+ result.push(item);
546667
+ continue;
546668
+ }
546669
+ if (item.mode === "channel") {
546670
+ if (this.activeInputChat === void 0) this.activeInputChat = item.channelChatId;
546671
+ if (item.channelContextOnly === true || this.activeInputChat !== void 0 && this.activeInputChat !== item.channelChatId || this.pendingChannelReplyGuard !== void 0 && this.pendingChannelReplyGuard.chatId !== item.channelChatId) break;
546672
+ } else if (item.mode !== void 0 && item.mode !== "prompt") break;
546673
+ result.push(item);
546674
+ }
546675
+ return result;
546676
+ },
546677
+ send: (item, signal, accepted) => {
546678
+ this.activeInputRequests ??= /* @__PURE__ */ new WeakMap();
546679
+ let request = this.activeInputRequests.get(item) ?? {};
546680
+ this.activeInputRequests.set(item, request);
546681
+ const image = item.channelImagePath === void 0 ? void 0 : buildChannelImagePart(item.channelImagePath);
546682
+ const input = item.parts !== void 0 ? [...item.parts] : image !== void 0 && this.canReadImages() ? [{
546683
+ type: "text",
546684
+ text: item.text.trim()
546685
+ }, image] : item.text.trim();
546686
+ return this.withInteractiveAgent(agentId, async () => {
546687
+ const originalTurn = request.identity?.expectedTurnId;
546688
+ let disposition = await deliverQueueSteer(session, input, Number(turn), signal, () => {
546689
+ if (request.identity?.expectedTurnId === Number(turn)) accepted();
546690
+ }, request);
546691
+ if (originalTurn !== void 0 && originalTurn !== Number(turn) && disposition !== "context") {
546692
+ request = {};
546693
+ this.activeInputRequests.set(item, request);
546694
+ disposition = await deliverQueueSteer(session, input, Number(turn), signal, accepted, request);
546695
+ }
546696
+ if (disposition !== "context") this.activeInputRequests?.delete(item);
546697
+ return disposition;
546698
+ });
546699
+ },
546700
+ commit: (item) => {
546701
+ if (!current() || !this.state.queuedMessages.includes(item)) return;
546702
+ this.activeInputRequests?.delete(item);
546703
+ this.state.queuedMessages = this.state.queuedMessages.filter((entry) => entry !== item);
546704
+ if (!(item.transcriptRendered || item.channelTranscriptRendered)) this.appendTranscriptEntry({
546705
+ id: nextTranscriptId(),
546706
+ kind: "user",
546707
+ turnId: turn,
546708
+ renderMode: "plain",
546709
+ content: item.displayText ?? item.text.trim(),
546710
+ origin: item.origin,
546711
+ imageAttachmentIds: item.imageAttachmentIds
546712
+ });
546713
+ item.channelAcknowledge?.();
546714
+ this.updateQueueDisplay();
546715
+ this.state.ui.requestRender();
546716
+ },
546717
+ error: (error) => {
546718
+ if (current()) this.showError(formatErrorMessage$2(error));
546719
+ },
546720
+ retry: () => {
546721
+ if (current()) this.scheduleQueueDrain();
546722
+ }
546723
+ });
546724
+ }
546725
+ this.activeInputDelivery.request();
546726
+ return true;
546727
+ }
546728
+ releaseChannelQueueAtSafePoint() {
546729
+ if (this.session !== void 0 && (this.stoppedInputSession === this.session || this.stoppedInputScopes?.get(this.session, this.state.queuedMessages[0]?.agentId ?? this.interactiveAgentId) !== void 0)) return;
546730
+ if (this.admitActiveQueuedInputs()) return;
546731
+ this.syncChannelQueueDeadline();
546732
+ if (this.state.appState.isCompacting || this.streamingUI.hasActiveToolCalls() || this.shellOutputStreams.size > 0 || this.state.appState.streamingPhase === "shell") return;
546733
+ if (this.state.appState.streamingPhase === "idle") {
546734
+ this.scheduleQueueDrain();
546735
+ return;
546736
+ }
546737
+ if (this.state.queuedMessages[0]?.mode === "channel") {
546738
+ this.channelQueueDeadline.requestDeliveryAtSafePoint();
546739
+ return;
546740
+ }
546741
+ if (this.pendingChannelReplyGuard !== void 0 || this.queueSteerInFlight !== void 0 || this.manualPromptInFlight !== void 0 || this.deferUserMessages || this.queueCommandRunning || this.localShellConsentRequest !== void 0 || this.editorReplacementActive || this.hasPendingQueueCommandCancellation() || queueSteerPrefixLength(this.state.queuedMessages, this.interactiveAgentId, 1) === 0) return;
546742
+ this.automaticSteerBatch = true;
546743
+ this.queueFlushBatchRemaining = Math.max(1, this.queueFlushBatchRemaining);
546744
+ this.steerQueueFlushPrefix();
545730
546745
  }
545731
546746
  canDrainQueue() {
545732
546747
  if (this.gatewayStartup && !this.gatewayViewReady) return false;
546748
+ if (this.session !== void 0 && this.stoppedInputSession === this.session) return false;
545733
546749
  if (this.queueInterruptCancellations.size > 0) return false;
545734
546750
  const head = this.state.queuedMessages[0];
546751
+ if (this.session !== void 0 && this.stoppedInputScopes?.get(this.session, head?.agentId ?? this.interactiveAgentId) !== void 0) return false;
546752
+ if (this.activeInputDelivery?.has(head)) return false;
546753
+ if (head?.text === "/stop" && head.channelCommandEnvelope !== void 0 && this.activeInputChat !== void 0 && head.channelChatId !== this.activeInputChat) return false;
546754
+ if (head?.text === "/stop" && head.channelCommandEnvelope !== void 0 && this.pendingChannelReplyGuard !== void 0 && head.channelChatId !== this.pendingChannelReplyGuard.chatId) return false;
545735
546755
  if (isExperimentalFlagEnabled("queue_policies") && (head?.mode === void 0 || head.mode === "prompt") && this.session !== void 0 && (this.queueReplayRecoveries.has(JSON.stringify([this.session.id, head?.agentId ?? this.interactiveAgentId])) || this.contextResetRecoveries.has(JSON.stringify([this.session.id, head?.agentId ?? this.interactiveAgentId])))) return false;
545736
546756
  if (isExperimentalFlagEnabled("queue_policies") && (head?.mode === void 0 || head.mode === "prompt") && this.session !== void 0 && this.queueOverflowAdmissionFailures.has(JSON.stringify([this.session.id, head?.agentId ?? this.interactiveAgentId]))) return false;
545737
546757
  if ((head?.mode === void 0 || head.mode === "prompt") && this.session !== void 0 && this.queuePolicyBlocksInput(this.session)) return false;
@@ -545739,6 +546759,7 @@ var init_blun_tui = __esmMin((() => {
545739
546759
  return !this.isShuttingDown && !this.queueCommandRunning && this.queueSteerInFlight === void 0 && this.manualPromptInFlight === void 0 && !this.editorReplacementActive && !this.deferUserMessages && (remoteControl || this.state.appState.streamingPhase === "idle" && !this.state.appState.isCompacting);
545740
546760
  }
545741
546761
  scheduleQueueDrain(minimumDelay = 0) {
546762
+ if (this.admitActiveQueuedInputs()) return;
545742
546763
  if (!this.canDrainQueue()) return;
545743
546764
  if (this.queueDrainTimer !== void 0) {
545744
546765
  if (minimumDelay <= 0) return;
@@ -545938,6 +546959,8 @@ var init_blun_tui = __esmMin((() => {
545938
546959
  const session = this.session;
545939
546960
  if (session === void 0) return;
545940
546961
  const head = this.state.queuedMessages[0];
546962
+ if (this.activeInputDelivery?.has(head)) return;
546963
+ if (head?.text === "/stop" && head.channelCommandEnvelope !== void 0 && this.pendingChannelReplyGuard !== void 0 && head.channelChatId !== this.pendingChannelReplyGuard.chatId) return;
545941
546964
  if (isExperimentalFlagEnabled("queue_policies") && (head?.mode === void 0 || head.mode === "prompt")) {
545942
546965
  const agentId = head?.agentId ?? this.interactiveAgentId;
545943
546966
  const key = JSON.stringify([session.id, agentId]);
@@ -546051,8 +547074,12 @@ var init_blun_tui = __esmMin((() => {
546051
547074
  channelCommandEnvelope: envelope,
546052
547075
  channelAcknowledge: acknowledge
546053
547076
  };
547077
+ if (command === "/stop" && this.session !== void 0 && !this.isShuttingDown && this.channelOwnsStoppedInput(envelope.meta.chat_id) && (this.activeInputChat === void 0 || this.activeInputChat === envelope.meta.chat_id) && (this.pendingChannelReplyGuard === void 0 || this.pendingChannelReplyGuard.chatId === envelope.meta.chat_id)) {
547078
+ this.runChannelCommand(item, envelope);
547079
+ return;
547080
+ }
546054
547081
  const busy = this.state.queuedMessages.length > 0 || this.queueSteerInFlight !== void 0 || this.manualPromptInFlight !== void 0 || this.state.appState.streamingPhase !== "idle" || this.state.appState.isCompacting;
546055
- if (this.session === void 0 || this.deferUserMessages || this.queueCommandRunning || this.localShellConsentRequest !== void 0 || this.editorReplacementActive || busy && !channelCommandCanInterrupt(command)) {
547082
+ if (this.session === void 0 || this.deferUserMessages || this.queueCommandRunning || this.localShellConsentRequest !== void 0 || this.editorReplacementActive || command === "/stop" && !this.channelOwnsStoppedInput(envelope.meta.chat_id) || command === "/stop" && this.activeInputChat !== void 0 && this.activeInputChat !== envelope.meta.chat_id || command === "/stop" && this.pendingChannelReplyGuard !== void 0 && this.pendingChannelReplyGuard.chatId !== envelope.meta.chat_id || busy && !channelCommandCanInterrupt(command)) {
546056
547083
  this.state.queuedMessages.push(item);
546057
547084
  this.scheduleQueueDrain();
546058
547085
  this.updateQueueDisplay();
@@ -546063,11 +547090,13 @@ var init_blun_tui = __esmMin((() => {
546063
547090
  injectChannelEnvelope({
546064
547091
  activationMode: () => !isExperimentalFlagEnabled("session_activation") ? void 0 : this.session !== void 0 && this.state.sessionActivation?.sessionId === this.session.id ? this.state.sessionActivation.mode ?? void 0 : "mention",
546065
547092
  canDeliver: () => this.session !== void 0 && this.state.appState.model.trim().length > 0,
546066
- isBusy: () => this.queueCommandRunning || this.localShellConsentRequest !== void 0 || this.state.queuedMessages.length > 0 || this.queueSteerInFlight !== void 0 || this.manualPromptInFlight !== void 0 || this.deferUserMessages || this.state.appState.streamingPhase !== "idle" || this.state.appState.isCompacting,
547093
+ isBusy: () => this.stoppedInputSession === this.session || this.queueCommandRunning || this.localShellConsentRequest !== void 0 || this.state.queuedMessages.length > 0 || this.queueSteerInFlight !== void 0 || this.manualPromptInFlight !== void 0 || this.deferUserMessages || this.state.appState.streamingPhase !== "idle" || this.state.appState.isCompacting,
546067
547094
  deliverNow: (modelInput, displayText, origin, contextOnly) => {
546068
547095
  this.sendChannelMessageInternal(this.requireSession(), modelInput, displayText, origin, envelope.meta.chat_id, envelope.meta["image_path"], contextOnly, false, acknowledge);
546069
547096
  },
546070
547097
  enqueue: (modelInput, displayText, origin, contextOnly) => {
547098
+ const session = this.session;
547099
+ if (session !== void 0) this.stoppedInputScopes?.resumeChannel(session, this.interactiveAgentId, envelope, this.state.appState.streamingPhase === "idle" ? void 0 : this.streamingUI.getTurnContext().turnId ?? "", this.gatewayResetTurn?.session === session ? this.gatewayResetTurn.scope : void 0);
546071
547100
  this.state.queuedMessages.push({
546072
547101
  text: modelInput,
546073
547102
  displayText,
@@ -546362,6 +547391,7 @@ var init_blun_tui = __esmMin((() => {
546362
547391
  return last;
546363
547392
  }
546364
547393
  enqueueMessage(text, options, mode) {
547394
+ this.stoppedInputSession = void 0;
546365
547395
  const parts = options?.parts === void 0 ? void 0 : structuredClone(options.parts);
546366
547396
  const imageAttachmentIds = options?.imageAttachmentIds?.slice();
546367
547397
  const policy = this.queuePolicyForSession(this.session);
@@ -546402,6 +547432,7 @@ var init_blun_tui = __esmMin((() => {
546402
547432
  mode,
546403
547433
  transcriptRendered: options?.transcriptRendered
546404
547434
  });
547435
+ this.syncChannelQueueDeadline();
546405
547436
  this.track("input_queue");
546406
547437
  }
546407
547438
  enqueueSlashCommand(text) {
@@ -546806,7 +547837,41 @@ var init_blun_tui = __esmMin((() => {
546806
547837
  return this.captureObservedTurnCancellation(session, agentId, turnId);
546807
547838
  }
546808
547839
  async executeSessionStopCommand(args) {
546809
- return this.executeSessionCancellationCommand(args, true);
547840
+ if (!isExperimentalFlagEnabled("queue_policies")) throw new Error("QUEUE_POLICIES_DISABLED");
547841
+ if (args.trim() !== "") throw new Error("STOP_ARGUMENTS_UNSUPPORTED");
547842
+ const session = this.session;
547843
+ if (session === void 0) return;
547844
+ const command = this.channelCommands?.context;
547845
+ if (command?.input === "/stop" && !this.channelOwnsStoppedInput(command.chatId)) return;
547846
+ const previous = this.stoppedInputScopes?.get(session, this.interactiveAgentId);
547847
+ if (command?.input === "/stop" && previous?.boundary !== void 0 && previous.boundary !== "absent") {
547848
+ const fileId = command.envelope.meta["queue_file_id"];
547849
+ const end = command.envelope.meta["queue_end"];
547850
+ if (fileId !== previous.boundary.fileId || end === void 0 || !/^\d+$/.test(end) || !Number.isSafeInteger(Number(end)) || Number(end) <= previous.boundary.frontier) return;
547851
+ }
547852
+ this.stoppedInputSession = session;
547853
+ if (command?.input === "/stop") {
547854
+ const fileId = command.envelope.meta["queue_file_id"];
547855
+ const rawEnd = command.envelope.meta["queue_end"];
547856
+ const end = Number(rawEnd);
547857
+ this.stoppedQueueBoundary = fileId !== void 0 && rawEnd !== void 0 && /^\d+$/.test(rawEnd) && Number.isSafeInteger(end) ? {
547858
+ fileId,
547859
+ frontier: end
547860
+ } : void 0;
547861
+ } else this.stoppedQueueBoundary = this.telegramChannel === void 0 ? void 0 : this.captureTelegramQueueBoundary();
547862
+ this.activeInputDelivery?.cancel();
547863
+ const turn = this.streamingUI.getTurnContext().turnId;
547864
+ if (turn === void 0 || !/^\d+$/.test(turn)) return;
547865
+ const turnId = Number(turn);
547866
+ if (!Number.isSafeInteger(turnId)) throw new Error("ACTIVE_TURN_ID_UNAVAILABLE");
547867
+ const agentId = this.interactiveAgentId;
547868
+ let scope;
547869
+ if (session.connectionKind === "gateway") {
547870
+ const observed = this.gatewayResetTurn;
547871
+ if (agentId !== "main" || observed?.session !== session || observed.turnId !== turnId) throw new Error("RESET_CONTEXT_SCOPE_UNAVAILABLE");
547872
+ scope = observed.scope;
547873
+ }
547874
+ await this.withInteractiveAgent(agentId, () => session.cancelTurn(turnId, scope, true));
546810
547875
  }
546811
547876
  async executeSessionAbortCommand(args) {
546812
547877
  return this.executeSessionCancellationCommand(args, false);
@@ -546924,6 +547989,22 @@ var init_blun_tui = __esmMin((() => {
546924
547989
  this.enqueueMessage(input, options);
546925
547990
  return;
546926
547991
  }
547992
+ if (isExperimentalFlagEnabled("queue_policies") && this.session === session && this.state.appState.streamingPhase !== "idle" && this.state.appState.streamingPhase !== "shell") {
547993
+ this.stoppedInputSession = void 0;
547994
+ this.state.queuedMessages.push({
547995
+ text: input,
547996
+ agentId: this.interactiveAgentId,
547997
+ parts: options?.parts === void 0 ? void 0 : structuredClone(options.parts),
547998
+ imageAttachmentIds: options?.imageAttachmentIds?.slice(),
547999
+ transcriptRendered: options?.transcriptRendered
548000
+ });
548001
+ this.syncChannelQueueDeadline();
548002
+ this.track("input_queue");
548003
+ this.updateQueueDisplay();
548004
+ this.state.ui.requestRender();
548005
+ this.scheduleQueueDrain();
548006
+ return;
548007
+ }
546927
548008
  const policy = this.queuePolicyForSession(session);
546928
548009
  const timedSteer = isExperimentalFlagEnabled("queue_policies") && policy?.mode === "steer" && options?.parts === void 0 && (options?.imageAttachmentIds?.length ?? 0) === 0 && (this.state.appState.streamingPhase !== "idle" || this.state.queuedMessages.length > 0);
546929
548010
  if (timedSteer) {
@@ -547044,6 +548125,8 @@ var init_blun_tui = __esmMin((() => {
547044
548125
  }
547045
548126
  clearQueuedMessages(preserveCancellations = false) {
547046
548127
  if (!preserveCancellations) this.queueInterruptCancellations.clear();
548128
+ this.activeInputDelivery?.cancel();
548129
+ this.activeInputScope = void 0;
547047
548130
  this.queueSteerInFlight?.receiptAbort?.abort();
547048
548131
  if (this.manualPromptInFlight?.promptAbort !== void 0 && !this.manualPromptInFlight.promptSubmitted && this.state.appState.streamingPhase === "waiting" && !this.streamingUI.hasActiveTurn()) {
547049
548132
  this.setAppState({ streamingPhase: "idle" });
@@ -547425,6 +548508,8 @@ var init_blun_tui = __esmMin((() => {
547425
548508
  this.sessionBindingRequest = void 0;
547426
548509
  const previous = this.session;
547427
548510
  this.queueInterruptCancellations.clear();
548511
+ this.activeInputDelivery?.cancel();
548512
+ this.activeInputScope = void 0;
547428
548513
  this.queueSteerInFlight?.receiptAbort?.abort();
547429
548514
  this.manualPromptInFlight?.promptAbort?.abort();
547430
548515
  this.managedQuotaWarningController.dismiss();
@@ -547511,7 +548596,11 @@ var init_blun_tui = __esmMin((() => {
547511
548596
  this.localShellConsentRequest = void 0;
547512
548597
  if (this.session !== void 0) this.localShellConsent.invalidate(this.session);
547513
548598
  if (!this.preserveQueueAcrossSessionReset) this.queueInterruptCancellations.clear();
547514
- if (!this.preserveQueueAcrossSessionReset) this.queueSteerInFlight?.receiptAbort?.abort();
548599
+ if (!this.preserveQueueAcrossSessionReset) {
548600
+ this.activeInputDelivery?.cancel();
548601
+ this.activeInputScope = void 0;
548602
+ this.queueSteerInFlight?.receiptAbort?.abort();
548603
+ }
547515
548604
  this.manualPromptInFlight?.promptAbort?.abort();
547516
548605
  for (const recovery of this.queueReplayRecoveries.values()) recovery.cancel();
547517
548606
  this.queueReplayRecoveries.clear();
@@ -548417,6 +549506,7 @@ var init_blun_tui = __esmMin((() => {
548417
549506
  return this.state.livePane.mode;
548418
549507
  }
548419
549508
  updateQueueDisplay() {
549509
+ this.syncChannelQueueDeadline();
548420
549510
  this.state.queueContainer.clear();
548421
549511
  const queued = [...this.queueSteerInFlight?.items ?? [], ...this.state.queuedMessages];
548422
549512
  if (queued.length === 0) return;