blun-king-cli 9.1.641 → 9.1.643

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,6 @@
1
1
  #!/usr/bin/env node
2
- // BLUN_BUILD_INPUT_SHA256:d4df2815be55011d12f15cf3f9b01e9c4c1ba80d84ef9322ad9e8fd20b13e018
2
+ // BLUN_BUILD_INPUT_SHA256:e50c78300e52dc6fc7d8003478fe2fa01fe7fdff8b1a749e108e6627de244e7e
3
+ import toolLiveness642 from "./tool-liveness642/index.cjs";
3
4
  /*! wasm-webp 0.1.0
4
5
  MIT License
5
6
 
@@ -21190,6 +21191,7 @@ var init_commands$1 = __esmMin((() => {
21190
21191
  }));
21191
21192
  var init_types$20 = __esmMin((() => {}));
21192
21193
  var FLAG_DEFINITIONS;
21194
+ var InputControl, controls, CHANNEL_QUEUE_DEADLINE_MS, QueueDeadlineWatchdog, StoppedInputScopes, SEARCH_LIMITS, SearchStop, active, inside, sessionSearchRequests, ActiveInputDelivery;
21193
21195
  var init_registry$4 = __esmMin((() => {
21194
21196
  FLAG_DEFINITIONS = [
21195
21197
  {
@@ -21533,7 +21535,7 @@ var init_registry$4 = __esmMin((() => {
21533
21535
  title: "Session queue policies",
21534
21536
  description: "Apply explicitly persisted session queue admission rules.",
21535
21537
  env: "BLUN_EXPERIMENTAL_QUEUE_POLICIES",
21536
- default: false,
21538
+ default: true,
21537
21539
  surface: "core"
21538
21540
  },
21539
21541
  {
@@ -29909,6 +29911,62 @@ var init_task$3 = __esmMin((() => {
29909
29911
  ]);
29910
29912
  }));
29911
29913
  var DenyAllPermissionPolicy;
29914
+ function inputControl(signal) {
29915
+ let control = controls.get(signal);
29916
+ if (control === void 0) {
29917
+ control = new InputControl();
29918
+ controls.set(signal, control);
29919
+ }
29920
+ return control;
29921
+ }
29922
+ function inheritInputControl(signal, control) {
29923
+ if (control !== void 0) controls.set(signal, control);
29924
+ }
29925
+ var init_input_control = __esmMin((() => {
29926
+ init_abort();
29927
+ InputControl = class {
29928
+ epoch = 0;
29929
+ stopped = false;
29930
+ provider;
29931
+ preparations = /* @__PURE__ */ new Set();
29932
+ listeners = /* @__PURE__ */ new Set();
29933
+ onChange(listener) {
29934
+ this.listeners.add(listener);
29935
+ return () => {
29936
+ this.listeners.delete(listener);
29937
+ };
29938
+ }
29939
+ changed(stop = false) {
29940
+ this.epoch++;
29941
+ this.stopped ||= stop;
29942
+ this.provider?.abort(new DOMException("INPUT_SUPERSEDED", "AbortError"));
29943
+ for (const controller of this.preparations) controller.abort(new DOMException("INPUT_SUPERSEDED", "AbortError"));
29944
+ for (const listener of this.listeners) listener();
29945
+ }
29946
+ async prepare(signal, operation) {
29947
+ const controller = new AbortController();
29948
+ this.preparations.add(controller);
29949
+ const preparationSignal = AbortSignal.any([signal, controller.signal]);
29950
+ try {
29951
+ return await abortable(Promise.resolve().then(() => {
29952
+ preparationSignal.throwIfAborted();
29953
+ return operation(preparationSignal);
29954
+ }), preparationSignal);
29955
+ } finally {
29956
+ this.preparations.delete(controller);
29957
+ }
29958
+ }
29959
+ beginProvider() {
29960
+ const controller = new AbortController();
29961
+ this.provider = controller;
29962
+ return controller;
29963
+ }
29964
+ endProvider(controller) {
29965
+ if (this.provider === controller) this.provider = void 0;
29966
+ }
29967
+ };
29968
+ controls = /* @__PURE__ */ new WeakMap();
29969
+ }));
29912
29970
  var init_deny_all = __esmMin((() => {
29913
29971
  DenyAllPermissionPolicy = class {
29914
29972
  message;
@@ -30235,8 +30293,11 @@ var init_persistence$1 = __esmMin((() => {
30235
30293
  this.shouldClear = false;
30236
30294
  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
30295
  const directory = dirname$3(this.filePath);
30238
- await mkdir(directory, { recursive: true });
30239
- const fh = await open(this.filePath, shouldClear ? "w" : "a");
30296
+ await mkdir(directory, {
30297
+ recursive: true,
30298
+ mode: 448
30299
+ });
30300
+ const fh = await open(this.filePath, shouldClear ? "w" : "a", 384);
30240
30301
  try {
30241
30302
  const before = await fh.stat();
30242
30303
  if (shouldClear || before.size === 0) this.persistedRecordCount = 0;
@@ -183784,10 +183845,17 @@ IMPORTANT:
183784
183845
  - If you do not know the answer, say so directly.
183785
183846
  `;
183786
183847
  nativeExecutionCompletions = /* @__PURE__ */ new WeakMap();
183787
- SessionSubagentHost = class {
183848
+ init_input_control();
183849
+ SessionSubagentHost = class {
183788
183850
  session;
183789
183851
  ownerAgentId;
183790
- admissionClosed = false;
183852
+ inputLeases = /* @__PURE__ */ new WeakMap();
183853
+ assertInputLease(options) {
183854
+ const lease = this.inputLeases.get(options);
183855
+ if (lease?.active?.runInBackground) return;
183856
+ if (lease !== void 0 && (lease.control.stopped || lease.control.epoch !== lease.epoch)) throw new DOMException("INPUT_SUPERSEDED", "AbortError");
183857
+ }
183858
+ admissionClosed = false;
183791
183859
  operations = new ExecutionLedger();
183792
183860
  childExecutions = new ExecutionLedger();
183793
183861
  preparedDisposers = /* @__PURE__ */ new Set();
@@ -183822,8 +183890,16 @@ IMPORTANT:
183822
183890
  assertAdmissionOpen() {
183823
183891
  if (this.admissionClosed) throw new Error("Subagent admission is closed for quiescence");
183824
183892
  }
183825
- runOperation(id, operation) {
183893
+ runOperation(id, operation, input) {
183826
183894
  this.assertAdmissionOpen();
183895
+ if (input !== void 0) {
183896
+ const control = inputControl(input.signal);
183897
+ this.inputLeases.set(input, {
183898
+ control,
183899
+ epoch: control.epoch
183900
+ });
183901
+ this.assertInputLease(input);
183902
+ }
183827
183903
  const completion = operation();
183828
183904
  this.operations.track(id, completion);
183829
183905
  return completion;
@@ -183857,7 +183933,7 @@ IMPORTANT:
183857
183933
  return this.session.getReadyAgent(currentId);
183858
183934
  }
183859
183935
  async spawn(options) {
183860
- return this.runOperation("spawn", () => this.spawnInner(options));
183936
+ return this.runOperation("spawn", () => this.spawnInner(options), options);
183861
183937
  }
183862
183938
  async spawnInner(options) {
183863
183939
  options.signal.throwIfAborted();
@@ -183889,7 +183965,7 @@ IMPORTANT:
183889
183965
  });
183890
183966
  }
183891
183967
  async resume(agentId, options) {
183892
- return this.runOperation("resume", () => this.resumeInner(agentId, options));
183968
+ return this.runOperation("resume", () => this.resumeInner(agentId, options), options);
183893
183969
  }
183894
183970
  async resumeInner(agentId, options) {
183895
183971
  options.signal.throwIfAborted();
@@ -183916,7 +183992,7 @@ IMPORTANT:
183916
183992
  });
183917
183993
  }
183918
183994
  async retry(agentId, options) {
183919
- return this.runOperation("retry", () => this.retryInner(agentId, options));
183995
+ return this.runOperation("retry", () => this.retryInner(agentId, options), options);
183920
183996
  }
183921
183997
  async retryInner(agentId, options) {
183922
183998
  options.signal.throwIfAborted();
@@ -183928,6 +184004,7 @@ IMPORTANT:
183928
184004
  modelAlias: parent.config.modelAlias,
183929
184005
  actionStyle: parent.config.actionStyle
183930
184006
  });
184007
+ this.assertInputLease(runOptions);
183931
184008
  this.emitSubagentStarted(parent, agentId);
183932
184009
  if (child.turn.retry("agent-host") === null) throw new Error(`Agent instance "${agentId}" could not start a retry turn`);
183933
184010
  this.observeFirstRequest(child, runOptions);
@@ -184042,7 +184119,7 @@ IMPORTANT:
184042
184119
  completion,
184043
184120
  update: (message) => this.updateActiveRun(agentId, completion, message)
184044
184121
  });
184045
- })
184122
+ }, options)
184046
184123
  };
184047
184124
  } catch (error) {
184048
184125
  await dispose();
@@ -184130,6 +184207,7 @@ IMPORTANT:
184130
184207
  }
184131
184208
  runWithActiveChild(childId, options, run) {
184132
184209
  this.assertAdmissionOpen();
184210
+ this.assertInputLease(options);
184133
184211
  if (this.activeChildren.has(childId)) throw new Error(`Agent instance "${childId}" is already running`);
184134
184212
  const controller = new AbortController();
184135
184213
  const unlinkAbortSignal = linkAbortSignal(options.signal, controller);
@@ -184138,10 +184216,22 @@ IMPORTANT:
184138
184216
  runInBackground: options.runInBackground
184139
184217
  };
184140
184218
  this.activeChildren.set(childId, active);
184141
- const completion = run({
184219
+ const runOptions = {
184142
184220
  ...options,
184143
184221
  signal: controller.signal
184144
- }).finally(() => {
184222
+ };
184223
+ const lease = this.inputLeases.get(options);
184224
+ if (lease !== void 0) {
184225
+ lease.active = active;
184226
+ this.inputLeases.set(runOptions, lease);
184227
+ }
184228
+ const unlinkInput = lease?.control.onChange(() => {
184229
+ if (active.runInBackground) return;
184230
+ const child = this.session.getReadyAgent(childId);
184231
+ if (child !== void 0) child.turn.stop(child.turn.currentId);
184232
+ });
184233
+ const completion = run(runOptions).finally(() => {
184234
+ unlinkInput?.();
184145
184235
  unlinkAbortSignal();
184146
184236
  if (this.activeChildren.get(childId) === active) this.activeChildren.delete(childId);
184147
184237
  });
@@ -184167,6 +184257,7 @@ IMPORTANT:
184167
184257
  }
184168
184258
  async runPromptTurn(parent, childId, child, profileName, options) {
184169
184259
  options.signal.throwIfAborted();
184260
+ this.assertInputLease(options);
184170
184261
  await this.triggerSubagentStart(parent, profileName, options.prompt, options.signal);
184171
184262
  options.signal.throwIfAborted();
184172
184263
  let childPrompt = options.prompt;
@@ -184174,6 +184265,7 @@ IMPORTANT:
184174
184265
  const gitContext = await collectGitContext(child.kaos, child.config.cwd);
184175
184266
  if (gitContext) childPrompt = `${gitContext}\n\n${childPrompt}`;
184176
184267
  }
184268
+ this.assertInputLease(options);
184177
184269
  this.emitSubagentStarted(parent, childId);
184178
184270
  if (child.turn.prompt([{
184179
184271
  type: "text",
@@ -184189,6 +184281,7 @@ IMPORTANT:
184189
184281
  while (remainingContinuations > 0 && result.length < SUMMARY_MIN_LENGTH) {
184190
184282
  remainingContinuations -= 1;
184191
184283
  options.signal.throwIfAborted();
184284
+ this.assertInputLease(options);
184192
184285
  child.turn.prompt([{
184193
184286
  type: "text",
184194
184287
  text: summary_continuation_default
@@ -185196,7 +185289,8 @@ var init_background = __esmMin((() => {
185196
185289
  * Wait for a task to reach a terminal state.
185197
185290
  * Returns immediately if already terminal. Times out after `timeoutMs`.
185198
185291
  */
185199
- async wait(taskId, timeoutMs = 3e4) {
185292
+ async wait(taskId, timeoutMs = 3e4, signal) {
185293
+ signal?.throwIfAborted();
185200
185294
  const entry = this.tasks.get(taskId);
185201
185295
  if (!entry) return void 0;
185202
185296
  if (TERMINAL_STATUSES.has(entry.status)) {
@@ -185205,7 +185299,7 @@ var init_background = __esmMin((() => {
185205
185299
  }
185206
185300
  if (timeoutMs <= 0) return this.toInfo(entry);
185207
185301
  const timeout = timeoutOutcome(timeoutMs, void 0);
185208
- await Promise.race([entry.terminal, timeout]).finally(() => timeout.clear());
185302
+ await toolLiveness642.waitForTaskTerminal(entry.terminal, timeout, signal);
185209
185303
  if (TERMINAL_STATUSES.has(entry.status)) await entry.persistWriteQueue;
185210
185304
  return this.toInfo(entry);
185211
185305
  }
@@ -248678,6 +248772,11 @@ async function prepareSkippedToolCall(step, call) {
248678
248772
  await dispatchToolCall(step, call, call.args);
248679
248773
  return makeResolvedToolCallTask(makeErrorToolResult(call, call.args, output));
248680
248774
  }
248775
+ function waitForPreparationBoundary(step, operation) {
248776
+ if (step.canStart?.() === false) return Promise.reject(new DOMException("INPUT_SUPERSEDED", "AbortError"));
248777
+ if (step.inputControl === void 0) return waitForToolBoundary(step, () => operation(step.signal));
248778
+ return step.inputControl.prepare(step.signal, (signal) => operation(signal));
248779
+ }
248681
248780
  function waitForToolBoundary(step, operation) {
248682
248781
  if (step.programmaticParentCallId === void 0) return Promise.resolve(operation());
248683
248782
  step.signal.throwIfAborted();
@@ -248705,6 +248804,11 @@ function makeResolvedToolCallTask(result) {
248705
248804
  async function runPrepareToolExecutionHook(step, call) {
248706
248805
  const { hooks, signal, turnId, currentStep, llm } = step;
248707
248806
  const { toolCall, args } = call;
248807
+ if (step.canStart?.() === false) return {
248808
+ kind: "blocked",
248809
+ args,
248810
+ output: "INPUT_SUPERSEDED"
248811
+ };
248708
248812
  const hook = hooks?.prepareToolExecution;
248709
248813
  if (hook === void 0) return {
248710
248814
  kind: "allowed",
@@ -248756,7 +248860,7 @@ async function runAuthorizeToolExecutionHook(step, call, args, execution) {
248756
248860
  const hook = hooks?.authorizeToolExecution;
248757
248861
  if (hook === void 0) return void 0;
248758
248862
  try {
248759
- return await waitForToolBoundary(step, () => hook({
248863
+ return await waitForPreparationBoundary(step, (preparationSignal) => hook({
248760
248864
  toolCall: call.toolCall,
248761
248865
  toolCalls: step.toolCalls,
248762
248866
  tool: call.tool,
@@ -248764,7 +248868,7 @@ async function runAuthorizeToolExecutionHook(step, call, args, execution) {
248764
248868
  execution,
248765
248869
  turnId,
248766
248870
  stepNumber: currentStep,
248767
- signal,
248871
+ signal: preparationSignal,
248768
248872
  llm
248769
248873
  }));
248770
248874
  } catch (error) {
@@ -248818,6 +248922,7 @@ async function runRunnableToolCall(step, call, effectiveArgs, metadata, executio
248818
248922
  function createNestedToolInvoker(step, parent) {
248819
248923
  const controller = new AbortController();
248820
248924
  const parentSignal = AbortSignal.any([step.signal, controller.signal]);
248925
+ inheritInputControl(parentSignal, step.inputControl);
248821
248926
  let accepting = true;
248822
248927
  let stopped = false;
248823
248928
  let sequence = 0;
@@ -248844,6 +248949,7 @@ function createNestedToolInvoker(step, parent) {
248844
248949
  while (reservedIds.has(id));
248845
248950
  reservedIds.add(id);
248846
248951
  const signal = input.signal === void 0 ? parentSignal : AbortSignal.any([parentSignal, input.signal]);
248952
+ inheritInputControl(signal, step.inputControl);
248847
248953
  const run = async () => {
248848
248954
  if (stopped) throw new Error("A nested tool stopped the turn.");
248849
248955
  signal.throwIfAborted();
@@ -248933,6 +249039,10 @@ async function finalizePendingToolResult(step, pendingResult) {
248933
249039
  async function executeTool(step, execution, toolCall, toolName, metadata, invokeTool) {
248934
249040
  const { dispatchEvent, signal, turnId } = step;
248935
249041
  signal.throwIfAborted();
249042
+ if (step.canStart?.() === false) return {
249043
+ output: "INPUT_SUPERSEDED",
249044
+ isError: true
249045
+ };
248936
249046
  const executePromise = execution.execute({
248937
249047
  turnId,
248938
249048
  toolCallId: toolCall.id,
@@ -249082,6 +249192,7 @@ var init_tool_call$1 = __esmMin((() => {
249082
249192
  init_path_access();
249083
249193
  init_abort();
249084
249194
  init_errors$5();
249195
+ init_input_control();
249085
249196
  init_execution_observer();
249086
249197
  init_tool_args_parse();
249087
249198
  init_tool_access();
@@ -249101,6 +249212,8 @@ var init_tool_call$1 = __esmMin((() => {
249101
249212
  */
249102
249213
  async function executeLoopStep(deps) {
249103
249214
  const { turnId, signal, buildMessages, buildMessagesStrict, dispatchEvent, llm, tools, hooks, executionObserver, log, currentStep, maxRetryAttempts, checkpointBeforeRetry, recordUsage, onStepStarted } = deps;
249215
+ const control = inputControl(signal);
249216
+ const inputEpoch = control.epoch;
249104
249217
  if (hooks?.beforeStep !== void 0) {
249105
249218
  const beforeStep = await hooks.beforeStep({
249106
249219
  turnId,
@@ -249119,10 +249232,13 @@ async function executeLoopStep(deps) {
249119
249232
  turnId,
249120
249233
  currentStep,
249121
249234
  stepUuid,
249122
- onStepStarted
249235
+ onStepStarted,
249236
+ acceptOutput: () => !control.stopped && control.epoch === inputEpoch
249123
249237
  });
249124
249238
  const prepareRequestBoundary = llm.prepareRequestBoundary?.bind(llm);
249125
249239
  const step = {
249240
+ inputControl: control,
249241
+ canStart: () => !control.stopped && control.epoch === inputEpoch,
249126
249242
  tools,
249127
249243
  hooks,
249128
249244
  executionObserver,
@@ -249138,6 +249254,7 @@ async function executeLoopStep(deps) {
249138
249254
  messages,
249139
249255
  tools: tools ?? [],
249140
249256
  signal,
249257
+ boundarySignal: signal,
249141
249258
  ...stepEvents.callbacks
249142
249259
  };
249143
249260
  if (prepareRequestBoundary === void 0) await stepEvents.start();
@@ -249187,6 +249304,12 @@ async function executeLoopStep(deps) {
249187
249304
  log
249188
249305
  };
249189
249306
  let response;
249307
+ const provider = control.beginProvider();
249308
+ chatParams = {
249309
+ ...chatParams,
249310
+ signal: AbortSignal.any([signal, provider.signal])
249311
+ };
249312
+ if (control.stopped || control.epoch !== inputEpoch) provider.abort();
249190
249313
  try {
249191
249314
  response = await chatWithRetry({
249192
249315
  ...retryInput,
@@ -249194,35 +249317,50 @@ async function executeLoopStep(deps) {
249194
249317
  });
249195
249318
  } catch (error) {
249196
249319
  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
249320
+ if (provider.signal.aborted && !signal.aborted) response = {
249321
+ toolCalls: [],
249322
+ usage: emptyUsage()
249208
249323
  };
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", {
249324
+ else if (buildMessagesStrict === void 0 || !isRecoverableRequestStructureError(error) || prepareRequestBoundary !== void 0 && stepEvents.hasOutput) throw error;
249325
+ else try {
249326
+ signal.throwIfAborted();
249327
+ log?.warn("provider rejected request structure; resending with strict projection", {
249218
249328
  turnStep: `${turnId}.${String(currentStep)}`,
249219
- model: llm.modelName,
249220
- originalError: errorMessage$13(error),
249221
- strictError: errorMessage$13(strictError)
249329
+ model: llm.modelName
249222
249330
  });
249223
- throw strictError;
249331
+ const strictMessages = await buildMessagesStrict();
249332
+ signal.throwIfAborted();
249333
+ let strictParams = {
249334
+ ...chatParams,
249335
+ messages: strictMessages
249336
+ };
249337
+ if (prepareRequestBoundary !== void 0) strictParams = await prepareRequestBoundary(strictParams, buildMessagesStrict);
249338
+ signal.throwIfAborted();
249339
+ try {
249340
+ response = await chatWithRetry({
249341
+ ...retryInput,
249342
+ params: strictParams
249343
+ });
249344
+ } catch (strictError) {
249345
+ if (provider.signal.aborted) throw strictError;
249346
+ log?.error("strict resend still rejected by provider; request remains wire-invalid", {
249347
+ turnStep: `${turnId}.${String(currentStep)}`,
249348
+ model: llm.modelName,
249349
+ originalError: errorMessage$13(error),
249350
+ strictError: errorMessage$13(strictError)
249351
+ });
249352
+ throw strictError;
249353
+ }
249354
+ log?.info("recovered after strict resend", { turnStep: `${turnId}.${String(currentStep)}` });
249355
+ } catch (strictBoundaryError) {
249356
+ if (!provider.signal.aborted || signal.aborted) throw strictBoundaryError;
249357
+ response = {
249358
+ toolCalls: [],
249359
+ usage: emptyUsage()
249360
+ };
249224
249361
  }
249225
- log?.info("recovered after strict resend", { turnStep: `${turnId}.${String(currentStep)}` });
249362
+ } finally {
249363
+ control.endProvider(provider);
249226
249364
  }
249227
249365
  await stepEvents.start();
249228
249366
  await stepEvents.drain();
@@ -249233,6 +249371,7 @@ async function executeLoopStep(deps) {
249233
249371
  if (effectiveStopReason === "tool_use") {
249234
249372
  if ((await runToolCallBatch(step, response)).stopTurn) effectiveStopReason = "end_turn";
249235
249373
  }
249374
+ if (control.epoch !== inputEpoch) effectiveStopReason = control.stopped ? "end_turn" : "tool_use";
249236
249375
  signal.throwIfAborted();
249237
249376
  await dispatchEvent({
249238
249377
  type: "step.end",
@@ -249343,8 +249482,10 @@ function createStepEventGate(deps) {
249343
249482
  return startPromise;
249344
249483
  };
249345
249484
  const enqueue = (dispatch) => {
249485
+ if (!deps.acceptOutput()) return Promise.resolve();
249346
249486
  hasOutput = true;
249347
249487
  const queued = eventQueue.then(async () => {
249488
+ if (!deps.acceptOutput()) return;
249348
249489
  await start();
249349
249490
  await dispatch();
249350
249491
  });
@@ -249427,6 +249568,7 @@ function createStepEventGate(deps) {
249427
249568
  }
249428
249569
  var init_turn_step = __esmMin((() => {
249429
249570
  init_src$8();
249571
+ init_input_control();
249430
249572
  init_errors$5();
249431
249573
  init_execution_observer();
249432
249574
  init_retry();
@@ -249449,6 +249591,10 @@ async function runTurn(input) {
249449
249591
  try {
249450
249592
  while (true) {
249451
249593
  signal.throwIfAborted();
249594
+ if (inputControl(signal).stopped) {
249595
+ stopReason = "aborted";
249596
+ break;
249597
+ }
249452
249598
  if (maxSteps !== void 0 && maxSteps > 0 && steps >= maxSteps) throw createMaxStepsExceededError(maxSteps);
249453
249599
  steps += 1;
249454
249600
  const stepNumber = steps;
@@ -249470,6 +249616,10 @@ async function runTurn(input) {
249470
249616
  onStepStarted: setActiveStep.bind(void 0, stepNumber)
249471
249617
  });
249472
249618
  activeStep = void 0;
249619
+ if (inputControl(signal).stopped) {
249620
+ stopReason = "aborted";
249621
+ break;
249622
+ }
249473
249623
  if (stepResult.stopReason === "tool_use") continue;
249474
249624
  const terminalStopReason = stepResult.stopReason;
249475
249625
  stopReason = terminalStopReason;
@@ -249513,6 +249663,7 @@ var init_run_turn = __esmMin((() => {
249513
249663
  init_src$8();
249514
249664
  init_errors$5();
249515
249665
  init_turn_step();
249666
+ init_input_control();
249516
249667
  }));
249517
249668
  var init_loop$1 = __esmMin((() => {
249518
249669
  init_tool_access();
@@ -250173,7 +250324,8 @@ var init_prompt$1 = __esmMin((() => {
250173
250324
  sessionAdmissionSteerRequestSchema = admissionReadIdentitySchema.omit({ timeout_ms: true }).extend({ expected_turn_id: admissionTurnSchema });
250174
250325
  sessionAdmissionCancelRequestSchema = object$1({
250175
250326
  scope: admissionIdentitySchema,
250176
- turn_id: admissionTurnSchema
250327
+ turn_id: admissionTurnSchema,
250328
+ graceful: boolean$1().optional()
250177
250329
  }).strict();
250178
250330
  sessionAdmissionCancelResponseSchema = sessionAdmissionCancelRequestSchema.extend({
250179
250331
  session_id: string().min(1),
@@ -256876,6 +257028,7 @@ function fullOutputHint(output) {
256876
257028
  }
256877
257029
  var OUTPUT_PREVIEW_BYTES, PAGING_HINT_LINES, TaskOutputInputSchema, TaskOutputTool;
256878
257030
  var init_task_output = __esmMin((() => {
257031
+ init_input_control();
256879
257032
  init_zod$1();
256880
257033
  init_background();
256881
257034
  init_input_schema();
@@ -256902,16 +257055,27 @@ var init_task_output = __esmMin((() => {
256902
257055
  description: `Reading output of task ${args.task_id}`,
256903
257056
  approvalRule: this.name,
256904
257057
  matchesRule: (ruleArgs) => matchesGlobRuleSubject(ruleArgs, args.task_id),
256905
- execute: () => this.execute(args)
257058
+ execute: ({ signal }) => this.execute(args, signal)
256906
257059
  };
256907
257060
  }
256908
- async execute(args) {
257061
+ async execute(args, signal = new AbortController().signal) {
257062
+ signal.throwIfAborted();
257063
+ const control642 = inputControl(signal);
257064
+ const epoch642 = control642.epoch;
257065
+ let waitReleasedForInput642 = false;
256909
257066
  const info = this.manager.getTask(args.task_id);
256910
257067
  if (!info) return {
256911
257068
  isError: true,
256912
257069
  output: `Task not found: ${args.task_id}`
256913
257070
  };
256914
- if (args.block && !isBackgroundTaskTerminal(info.status)) await this.manager.wait(args.task_id, (args.timeout ?? 30) * 1e3);
257071
+ if (args.block && !isBackgroundTaskTerminal(info.status)) {
257072
+ waitReleasedForInput642 = await toolLiveness642.waitForTaskInput({
257073
+ manager: this.manager, taskId: args.task_id,
257074
+ timeoutMs: (args.timeout ?? 30) * 1e3, signal,
257075
+ control: control642, initialEpoch: epoch642
257076
+ }) === "input";
257077
+ }
257078
+ signal.throwIfAborted();
256915
257079
  const current = this.manager.getTask(args.task_id);
256916
257080
  if (!current) return {
256917
257081
  isError: true,
@@ -256919,7 +257083,8 @@ var init_task_output = __esmMin((() => {
256919
257083
  };
256920
257084
  const output = await this.manager.getOutputSnapshot(args.task_id, OUTPUT_PREVIEW_BYTES);
256921
257085
  const lines = [formatPlainObject({
256922
- retrievalStatus: retrievalStatus(current.status, args.block),
257086
+ retrievalStatus: retrievalStatus(current.status, args.block && !waitReleasedForInput642),
257087
+ waitReleasedForInput: waitReleasedForInput642 || void 0,
256923
257088
  ...current,
256924
257089
  outputPath: output.outputPath,
256925
257090
  terminalReason: terminalReason(current),
@@ -257335,6 +257500,7 @@ function buildSubagentDescriptions(subagents) {
257335
257500
  }
257336
257501
  var AgentToolInputSchema, BACKGROUND_AGENT_UNAVAILABLE, AgentTool, USER_INTERRUPTED_SUBAGENT_MESSAGE;
257337
257502
  var init_agent$1 = __esmMin((() => {
257503
+ init_input_control();
257338
257504
  init_zod$1();
257339
257505
  init_tool_access();
257340
257506
  init_errors$5();
@@ -257408,6 +257574,8 @@ var init_agent$1 = __esmMin((() => {
257408
257574
  };
257409
257575
  }
257410
257576
  async execution(args, { toolCallId, signal }) {
257577
+ const control642 = inputControl(signal);
257578
+ const epoch642 = control642.epoch;
257411
257579
  try {
257412
257580
  signal.throwIfAborted();
257413
257581
  const runInBackground = args.run_in_background === true;
@@ -257475,8 +257643,16 @@ var init_agent$1 = __esmMin((() => {
257475
257643
  };
257476
257644
  }
257477
257645
  if (runInBackground) return { output: formatBackgroundAgentResult(taskId, handle, args.description, this.allowBackground) };
257478
- if (await this.backgroundManager.waitForForegroundRelease(taskId) === "detached") return { output: formatBackgroundAgentResult(taskId, handle, args.description, this.allowBackground) };
257479
- return await this.formatForegroundResult(taskId, handle);
257646
+ const inputYield642 = toolLiveness642.createForegroundYield({
257647
+ control: control642, initialEpoch: epoch642, signal,
257648
+ enabled: this.allowBackground, idleMs: 0,
257649
+ detach: () => this.backgroundManager.detach(taskId),
257650
+ onError: error => this.log?.warn("Could not background active agent", { error })
257651
+ });
257652
+ try {
257653
+ if (await this.backgroundManager.waitForForegroundRelease(taskId) === "detached") return { output: formatBackgroundAgentResult(taskId, handle, args.description, this.allowBackground) };
257654
+ return await this.formatForegroundResult(taskId, handle);
257655
+ } finally { inputYield642.dispose(); }
257480
257656
  } catch (error) {
257481
257657
  return {
257482
257658
  output: `subagent error: ${launchErrorMessage(error, signal)}`,
@@ -265881,7 +266057,8 @@ var init_turn = __esmMin((() => {
265881
266057
  "Otherwise keep going — use the existing conversation context and your tools,",
265882
266058
  "and do not ask the user for input unless a real blocker prevents progress."
265883
266059
  ].join(" ");
265884
- TurnFlow = class {
266060
+ init_input_control();
266061
+ TurnFlow = class {
265885
266062
  agent;
265886
266063
  admissionClosed = false;
265887
266064
  loadedToolNames = /* @__PURE__ */ new Set();
@@ -265958,6 +266135,7 @@ var init_turn = __esmMin((() => {
265958
266135
  if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 2147483647) throw new Error("INVALID_PROMPT_TIMEOUT");
265959
266136
  }
265960
266137
  this.assertAdmissionOpen();
266138
+ this.stopRequested = false;
265961
266139
  this.agent.records.logRecord({
265962
266140
  type: "turn.prompt",
265963
266141
  input,
@@ -265974,6 +266152,7 @@ var init_turn = __esmMin((() => {
265974
266152
  }
265975
266153
  steer(input, origin = USER_PROMPT_ORIGIN) {
265976
266154
  this.assertAdmissionOpen();
266155
+ this.stopRequested = false;
265977
266156
  this.agent.records.logRecord({
265978
266157
  type: "turn.steer",
265979
266158
  input,
@@ -265987,7 +266166,7 @@ var init_turn = __esmMin((() => {
265987
266166
  }
265988
266167
  /** Buffer only into the currently active turn; never launch from an idle state. */
265989
266168
  steerActive(input, expectedTurnId, origin = USER_PROMPT_ORIGIN, onDisposition) {
265990
- if (this.admissionClosed) return null;
266169
+ if (this.admissionClosed || this.stopRequested) return null;
265991
266170
  const active = this.activeTurn;
265992
266171
  if (active === null || active === "resuming" || !active.acceptingSteers || expectedTurnId !== void 0 && expectedTurnId !== this.currentId) return null;
265993
266172
  this.agent.records.logRecord({
@@ -266078,7 +266257,19 @@ var init_turn = __esmMin((() => {
266078
266257
  this.turnId += 1;
266079
266258
  this.activeTurn = "resuming";
266080
266259
  }
266081
- cancel(turnId, reason) {
266260
+ stopRequested = false;
266261
+ stop(turnId) {
266262
+ const active = this.activeTurn;
266263
+ if (turnId !== this.currentId) return;
266264
+ this.stopRequested = true;
266265
+ if (active === null || active === "resuming") return;
266266
+ this.agent.records.logRecord({
266267
+ type: "turn.cancel",
266268
+ turnId
266269
+ });
266270
+ inputControl(active.controller.signal).changed(true);
266271
+ }
266272
+ cancel(turnId, reason) {
266082
266273
  this.agent.records.logRecord({
266083
266274
  type: "turn.cancel",
266084
266275
  turnId
@@ -266149,6 +266340,8 @@ var init_turn = __esmMin((() => {
266149
266340
  timeoutMs
266150
266341
  });
266151
266342
  this.nextSteerSequence += 1;
266343
+ const active = this.activeTurn;
266344
+ if (origin.kind !== "background_task" && active !== null && active !== "resuming") inputControl(active.controller.signal).changed();
266152
266345
  }
266153
266346
  flushSteerBuffer(turnId = this.currentId, throughSequence = Number.POSITIVE_INFINITY) {
266154
266347
  if (this.steerBuffer.length === 0) return false;
@@ -266209,7 +266402,7 @@ var init_turn = __esmMin((() => {
266209
266402
  * draining into it via `flushSteerBuffer`.
266210
266403
  */
266211
266404
  onCompactionFinished() {
266212
- if (this.admissionClosed) return;
266405
+ if (this.admissionClosed || this.stopRequested) return;
266213
266406
  if (this.steerBuffer.length === 0) return;
266214
266407
  if (this.activeTurn !== null) return;
266215
266408
  const next = this.steerBuffer.shift();
@@ -266238,7 +266431,7 @@ var init_turn = __esmMin((() => {
266238
266431
  try {
266239
266432
  if (this.agent.goal.getGoal().goal?.status === "active") return finish(await this.driveGoal(firstTurnId, input, origin, signal));
266240
266433
  const end = await this.runOneTurn(firstTurnId, input, origin, signal, true);
266241
- 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(), [{
266434
+ 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(), [{
266242
266435
  type: "text",
266243
266436
  text: GOAL_CONTINUATION_PROMPT
266244
266437
  }], goalContinuationOrigin(origin), signal));
@@ -266276,6 +266469,11 @@ var init_turn = __esmMin((() => {
266276
266469
  let turnInput = input;
266277
266470
  let turnOrigin = origin;
266278
266471
  while (true) {
266472
+ if (inputControl(signal).stopped) return { event: {
266473
+ type: "turn.ended",
266474
+ turnId,
266475
+ reason: "cancelled"
266476
+ } };
266279
266477
  const goalBeforeTurn = this.agent.goal.getGoal().goal;
266280
266478
  if (goalBeforeTurn?.status === "active" && goalBeforeTurn.budget.overBudget) {
266281
266479
  await this.agent.goal.markBlocked({ reason: "A configured budget was reached" });
@@ -266365,7 +266563,13 @@ var init_turn = __esmMin((() => {
266365
266563
  let completedResponse;
266366
266564
  let errorEvent;
266367
266565
  try {
266566
+ const checkStop = () => {
266567
+ signal.throwIfAborted();
266568
+ if (inputControl(signal).stopped) throw new DOMException("INPUT_STOPPED", "AbortError");
266569
+ };
266570
+ checkStop();
266368
266571
  const promptHookEnded = await this.applyUserPromptHook(turnId, input, origin, signal, startedAt);
266572
+ checkStop();
266369
266573
  if (promptHookEnded !== void 0) {
266370
266574
  ended = promptHookEnded.event;
266371
266575
  blockedByUserPromptHook = promptHookEnded.blocked;
@@ -266384,6 +266588,7 @@ var init_turn = __esmMin((() => {
266384
266588
  this.agent.log.warn("Turn-start observation failed");
266385
266589
  }
266386
266590
  signal.throwIfAborted();
266591
+ checkStop();
266387
266592
  const stopReason = await this.runStepLoop(turnId, signal, input, origin, (response) => {
266388
266593
  completedResponse = response;
266389
266594
  });
@@ -266636,7 +266841,7 @@ var init_turn = __esmMin((() => {
266636
266841
  },
266637
266842
  settleStep: async ({ signal: stepSignal }) => {
266638
266843
  if (stopForGoalBudget) this.setActiveSteerAcceptance(turnId, false);
266639
- await this.agent.fullCompaction.afterStep(stepSignal);
266844
+ if (!inputControl(stepSignal).stopped) await this.agent.fullCompaction.afterStep(stepSignal);
266640
266845
  },
266641
266846
  afterStep: async () => {
266642
266847
  deduper.endStep();
@@ -267330,6 +267535,7 @@ function rewriteWindowsNullRedirect(command) {
267330
267535
  }
267331
267536
  var MS_PER_SECOND, DEFAULT_TIMEOUT_S, MAX_TIMEOUT_S, DEFAULT_BACKGROUND_TIMEOUT_S, MAX_BACKGROUND_TIMEOUT_S, USER_INTERRUPT_REASON, BashInputSchema, SHELL_TIMEOUT_VARS, BashTool, WINDOWS_NUL_REDIRECT;
267332
267537
  var init_bash = __esmMin((() => {
267538
+ init_input_control();
267333
267539
  init_zod$1();
267334
267540
  init_background();
267335
267541
  init_render_prompt();
@@ -267493,6 +267699,9 @@ var init_bash = __esmMin((() => {
267493
267699
  return this.kaos.execWithEnv(shellArgs, mergedEnv);
267494
267700
  }
267495
267701
  async execution(args, signal, onUpdate, onForegroundTaskStart) {
267702
+ const inputControl642 = inputControl(signal);
267703
+ const inputEpoch642 = inputControl642.epoch;
267704
+ let foregroundYield642;
267496
267705
  const validationError = this.validateRunRequest(args, signal);
267497
267706
  if (validationError !== void 0) return validationError;
267498
267707
  const startsInBackground = args.run_in_background === true;
@@ -267517,6 +267726,7 @@ var init_bash = __esmMin((() => {
267517
267726
  let foregroundTaskId;
267518
267727
  const onProcessOutput = startsInBackground ? void 0 : (kind, text) => {
267519
267728
  if (!collectForegroundOutput) return;
267729
+ if (text.length > 0) foregroundYield642?.touch();
267520
267730
  onUpdate?.({
267521
267731
  kind,
267522
267732
  text
@@ -267546,6 +267756,13 @@ var init_bash = __esmMin((() => {
267546
267756
  };
267547
267757
  }
267548
267758
  if (!startsInBackground) onForegroundTaskStart?.(taskId);
267759
+ foregroundYield642 = toolLiveness642.createForegroundYield({
267760
+ control: inputControl642, initialEpoch: inputEpoch642, signal,
267761
+ enabled: !startsInBackground && this.allowBackground,
267762
+ detach: () => this.backgroundManager.detach(taskId),
267763
+ onError: () => onUpdate?.({ kind: "status",
267764
+ text: "Could not move this command to the background; it remains running." }),
267765
+ });
267549
267766
  if (startsInBackground) return this.backgroundStartedResult(taskId, proc, description, {
267550
267767
  title: "Background task started",
267551
267768
  brief: `Started ${taskId}`
@@ -267560,6 +267777,7 @@ var init_bash = __esmMin((() => {
267560
267777
  }
267561
267778
  return await this.foregroundCompletionResult(taskId, proc, builder, foregroundTimeoutMs);
267562
267779
  } finally {
267780
+ foregroundYield642?.dispose();
267563
267781
  collectForegroundOutput = false;
267564
267782
  }
267565
267783
  }
@@ -270664,7 +270882,7 @@ var init_agent = __esmMin((() => {
270664
270882
  messages: await rebuildMessages()
270665
270883
  };
270666
270884
  let systemPrompt = this.effectiveSystemPrompt;
270667
- const compacted = await this.fullCompaction.beforeStep(params.signal, {
270885
+ const compacted = await this.fullCompaction.beforeStep(params.boundarySignal ?? params.signal, {
270668
270886
  messages: params.messages,
270669
270887
  additionalMessages: steers.messages,
270670
270888
  rebuildMessages,
@@ -270829,6 +271047,12 @@ var init_agent = __esmMin((() => {
270829
271047
  };
270830
271048
  },
270831
271049
  cancel: (payload) => {
271050
+ if (payload.graceful === true) {
271051
+ if (payload.turnId === void 0) throw new Error("STOP_TURN_REQUIRED");
271052
+ if (payload.turnId !== this.turn.currentId) return;
271053
+ this.turn.stop(payload.turnId);
271054
+ return Promise.all([this.turn.waitForExecutionEnd(), this.fullCompaction.waitForExecutionEnd()]).then(() => void 0);
271055
+ }
270832
271056
  const waitForExecution = this.experimentalFlags.enabled("queue_policies") && payload.turnId !== void 0 && payload.turnId === this.turn.currentId;
270833
271057
  if (this.turn.hasActiveTurn) this.telemetry.track("cancel", { from: "streaming" });
270834
271058
  this.turn.cancel(payload.turnId, payload.cancellationReason === "timeout" ? new DOMException("Prompt execution timed out", "TimeoutError") : void 0);
@@ -337000,7 +337224,10 @@ async function appendSessionIndexEntry(homeDir, entry) {
337000
337224
  recursive: true,
337001
337225
  mode: 448
337002
337226
  });
337003
- await appendFile(indexPath, `${JSON.stringify(entry)}\n`, "utf-8");
337227
+ await appendFile(indexPath, `${JSON.stringify(entry)}\n`, {
337228
+ encoding: "utf-8",
337229
+ mode: 384
337230
+ });
337004
337231
  }
337005
337232
  async function readSessionIndex$1(homeDir, sessionsDir) {
337006
337233
  let raw;
@@ -346253,12 +346480,14 @@ var init_sessionService = __esmMin((() => {
346253
346480
  sessionId: id,
346254
346481
  agentId: "main",
346255
346482
  expectedScope: request.scope,
346256
- turnId: request.turn_id
346483
+ turnId: request.turn_id,
346484
+ graceful: request.graceful
346257
346485
  });
346258
346486
  return {
346259
346487
  session_id: id,
346260
346488
  scope: request.scope,
346261
346489
  turn_id: request.turn_id,
346490
+ graceful: request.graceful,
346262
346491
  settled: true
346263
346492
  };
346264
346493
  }
@@ -349409,13 +349638,14 @@ var init_session$1 = __esmMin((() => {
349409
349638
  this.ensureOpen();
349410
349639
  await this.trackLocalInputRequest(() => this.rpc.cancel({ sessionId: this.id }));
349411
349640
  }
349412
- async cancelTurn(turnId, expectedScope) {
349641
+ async cancelTurn(turnId, expectedScope, graceful) {
349413
349642
  this.ensureOpen();
349414
349643
  if (!Number.isSafeInteger(turnId) || turnId < 0) throw new Error("INVALID_TURN_ID");
349415
349644
  await this.trackLocalInputRequest(() => this.rpc.cancelTurn({
349416
349645
  sessionId: this.id,
349417
349646
  turnId,
349418
- expectedScope
349647
+ expectedScope,
349648
+ graceful
349419
349649
  }));
349420
349650
  }
349421
349651
  async setModel(model, options) {
@@ -350847,7 +351077,8 @@ var init_rpc = __esmMin((() => {
350847
351077
  sessionId: input.sessionId,
350848
351078
  agentId,
350849
351079
  turnId: input.turnId,
350850
- expectedScope: input.expectedScope
351080
+ expectedScope: input.expectedScope,
351081
+ graceful: input.graceful
350851
351082
  });
350852
351083
  }
350853
351084
  async registerTool(input) {
@@ -353012,7 +353243,7 @@ var init_gateway_session_client = __esmMin((() => {
353012
353243
  if ((await this.metadata(owner)).capabilities.admission_cancel !== true) throw new GatewayCommandError("GATEWAY_CAPABILITY_UNAVAILABLE");
353013
353244
  owner?.throwIfAborted();
353014
353245
  const response = await this.post(path, request, sessionAdmissionCancelResponseSchema, owner);
353015
- if (response.session_id !== sessionId || response.scope !== request.scope || response.turn_id !== request.turn_id) throw new GatewayCommandError("GATEWAY_COMMAND_OUTCOME_UNKNOWN");
353246
+ 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");
353016
353247
  return response;
353017
353248
  }
353018
353249
  async steerWithReceipt(sessionId, input, owner) {
@@ -353447,7 +353678,8 @@ var init_gateway_session_rpc = __esmMin((() => {
353447
353678
  if (this.interactiveAgentId !== "main" || !input.expectedScope) throw new GatewayRpcError("GATEWAY_RPC_CAPABILITY_UNAVAILABLE");
353448
353679
  await this.client.cancelAdmissionTurn(this.sessionId, {
353449
353680
  scope: input.expectedScope,
353450
- turn_id: input.turnId
353681
+ turn_id: input.turnId,
353682
+ graceful: input.graceful
353451
353683
  }, this.lifetime.signal);
353452
353684
  this.assertScope(input);
353453
353685
  if (this.interactiveAgentId !== "main") throw new GatewayRpcError("GATEWAY_RPC_CAPABILITY_UNAVAILABLE");
@@ -368431,7 +368663,7 @@ function optionalBuildString(value) {
368431
368663
  var BLUN_BUILD_INFO;
368432
368664
  var init_build_info = __esmMin((() => {
368433
368665
  BLUN_BUILD_INFO = {
368434
- version: optionalBuildString("9.1.640"),
368666
+ version: optionalBuildString("9.1.643"),
368435
368667
  channel: typeof __BLUN_CHANNEL__ === "string" ? optionalBuildString(__BLUN_CHANNEL__) : void 0,
368436
368668
  commit: typeof __BLUN_COMMIT__ === "string" ? optionalBuildString(__BLUN_COMMIT__) : void 0,
368437
368669
  buildTarget: typeof __BLUN_BUILD_TARGET__ === "string" ? optionalBuildString(__BLUN_BUILD_TARGET__) : void 0
@@ -491743,6 +491975,117 @@ var init_rendering = __esmMin((() => {
491743
491975
  THINKING_WORD_INTERVAL_MS = 3e3;
491744
491976
  }));
491745
491977
  /** The caller supplies the authoritative, workspace-scoped inventory. */
491978
+ var init_channel_queue = __esmMin((() => {
491979
+ CHANNEL_QUEUE_DEADLINE_MS = 3e4;
491980
+ }));
491981
+ var init_queue_deadline_watchdog = __esmMin((() => {
491982
+ init_channel_queue();
491983
+ QueueDeadlineWatchdog = class {
491984
+ snapshot;
491985
+ onStatus;
491986
+ now;
491987
+ owner;
491988
+ observed = /* @__PURE__ */ new WeakMap();
491989
+ statusHead;
491990
+ status;
491991
+ timer;
491992
+ disposed = false;
491993
+ generation = 0;
491994
+ constructor(snapshot, onStatus, now = () => performance.now()) {
491995
+ this.snapshot = snapshot;
491996
+ this.onStatus = onStatus;
491997
+ this.now = now;
491998
+ }
491999
+ /** Steer restoration may copy an entry; keep its original monotonic age. */
492000
+ transfer(from, to) {
492001
+ const started = this.observed.get(from);
492002
+ if (started !== void 0) this.observed.set(to, started);
492003
+ if (this.statusHead === from) this.statusHead = to;
492004
+ }
492005
+ sync() {
492006
+ if (this.disposed) return;
492007
+ this.clearTimer();
492008
+ const snapshot = this.snapshot();
492009
+ if (snapshot.owner !== this.owner) {
492010
+ this.owner = snapshot.owner;
492011
+ this.observed = /* @__PURE__ */ new WeakMap();
492012
+ this.statusHead = void 0;
492013
+ this.publish(void 0);
492014
+ }
492015
+ const now = this.now();
492016
+ for (const entry of snapshot.entries) if (!this.observed.has(entry)) this.observed.set(entry, now);
492017
+ const head = snapshot.entries[0];
492018
+ if (head === void 0) {
492019
+ this.publish(void 0);
492020
+ return;
492021
+ }
492022
+ const elapsedMs = Math.max(0, now - this.observed.get(head));
492023
+ if (elapsedMs >= 3e4) {
492024
+ const status = {
492025
+ code: "QUEUE_DEADLINE_EXCEEDED",
492026
+ deadlineMs: CHANNEL_QUEUE_DEADLINE_MS,
492027
+ elapsedMs,
492028
+ reason: snapshot.reason
492029
+ };
492030
+ this.publish(status, head);
492031
+ return;
492032
+ }
492033
+ this.publish(void 0);
492034
+ const generation = this.generation;
492035
+ this.timer = setTimeout(() => {
492036
+ if (this.disposed || generation !== this.generation) return;
492037
+ this.timer = void 0;
492038
+ this.sync();
492039
+ }, CHANNEL_QUEUE_DEADLINE_MS - elapsedMs);
492040
+ this.timer.unref?.();
492041
+ }
492042
+ dispose() {
492043
+ this.disposed = true;
492044
+ this.clearTimer();
492045
+ this.publish(void 0);
492046
+ }
492047
+ publish(status, head) {
492048
+ if (this.statusHead === head && this.status?.reason === status?.reason && this.status === void 0 === (status === void 0)) return;
492049
+ this.statusHead = head;
492050
+ this.status = status;
492051
+ this.onStatus(status);
492052
+ }
492053
+ clearTimer() {
492054
+ this.generation += 1;
492055
+ if (this.timer !== void 0) clearTimeout(this.timer);
492056
+ this.timer = void 0;
492057
+ }
492058
+ };
492059
+ }));
492060
+ var init_stopped_input_scopes = __esmMin((() => {
492061
+ StoppedInputScopes = class {
492062
+ owners = /* @__PURE__ */ new WeakMap();
492063
+ stop(owner, scope) {
492064
+ let agents = this.owners.get(owner);
492065
+ if (agents === void 0) {
492066
+ agents = /* @__PURE__ */ new Map();
492067
+ this.owners.set(owner, agents);
492068
+ }
492069
+ agents.set(scope.agentId, scope);
492070
+ }
492071
+ get(owner, agentId) {
492072
+ const scope = this.owners.get(owner)?.get(agentId);
492073
+ return scope?.sessionId === owner.id ? scope : void 0;
492074
+ }
492075
+ clear(owner, agentId, expected = this.get(owner, agentId)) {
492076
+ if (expected !== void 0 && this.get(owner, agentId) === expected) this.owners.get(owner)?.delete(agentId);
492077
+ }
492078
+ resumeChannel(owner, agentId, envelope, turnId, runtimeScope) {
492079
+ const scope = this.get(owner, agentId);
492080
+ if (scope === void 0) return false;
492081
+ const boundary = scope.boundary;
492082
+ const start = envelope.meta["queue_start"];
492083
+ 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;
492084
+ this.clear(owner, agentId, scope);
492085
+ return true;
492086
+ }
492087
+ };
492088
+ }));
491746
492089
  function resolveSessionReference(sessions, reference) {
491747
492090
  const value = reference.trim();
491748
492091
  if (value.length === 0) return { kind: "missing" };
@@ -492172,9 +492515,10 @@ var init_queue_prompt_delivery = __esmMin((() => {
492172
492515
  init_queue_overflow_delivery();
492173
492516
  }));
492174
492517
  /** Resolves only from request-specific evidence, never from UI step/turn events. */
492175
- async function deliverQueueSteer(sender, input, expectedTurnId, signal, onAccepted) {
492518
+ async function deliverQueueSteer(sender, input, expectedTurnId, signal, onAccepted, state) {
492176
492519
  if (!Number.isSafeInteger(expectedTurnId) || expectedTurnId < 0) throw new Error("INVALID_STEER_RECEIPT_TURN");
492177
- const payload = structuredClone(input);
492520
+ const payload = state?.payload ?? structuredClone(input);
492521
+ if (state !== void 0) state.payload = payload;
492178
492522
  const check = () => {
492179
492523
  if (signal.aborted) throw new Error("QUEUE_STEER_CANCELLED");
492180
492524
  };
@@ -492188,7 +492532,8 @@ async function deliverQueueSteer(sender, input, expectedTurnId, signal, onAccept
492188
492532
  check();
492189
492533
  };
492190
492534
  if (typeof sender.getPromptAdmissionScope !== "function" || typeof sender.steerActiveWithReceipt !== "function" || typeof sender.getSteerAdmissionReceipt !== "function") throw new Error("STEER_RECEIPTS_UNAVAILABLE");
492191
- let identity;
492535
+ let identity = state?.identity;
492536
+ const resuming = identity !== void 0;
492192
492537
  while (identity === void 0) {
492193
492538
  check();
492194
492539
  try {
@@ -492199,19 +492544,22 @@ async function deliverQueueSteer(sender, input, expectedTurnId, signal, onAccept
492199
492544
  requestId: randomUUID(),
492200
492545
  expectedTurnId
492201
492546
  };
492547
+ if (state !== void 0) state.identity = identity;
492202
492548
  } catch (error) {
492203
492549
  check();
492204
492550
  if (isPromptAdmissionProtocolFailure(error)) throw error;
492205
492551
  await wait();
492206
492552
  }
492207
492553
  }
492208
- let submit = true;
492554
+ let submit = !resuming;
492209
492555
  let accepted = false;
492210
492556
  const markAccepted = () => {
492211
492557
  if (accepted) return;
492212
492558
  accepted = true;
492559
+ if (state !== void 0) state.accepted = true;
492213
492560
  onAccepted?.();
492214
492561
  };
492562
+ if (state?.accepted) markAccepted();
492215
492563
  for (;;) {
492216
492564
  check();
492217
492565
  if (submit) {
@@ -499549,6 +499897,12 @@ var init_telegram_channel_copy = __esmMin((() => {
499549
499897
  });
499550
499898
  }));
499551
499899
  var SESSION_QUEUE_READ_BYTES;
499900
+ function isChannelStop(envelope) {
499901
+ 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;
499902
+ const match = /^\/stop(?:@([A-Za-z0-9_]+))?$/i.exec(envelope.text.trim());
499903
+ return match !== null && (match[1] === void 0 || match[1].toLowerCase() === envelope.meta["bot_username"]?.toLowerCase());
499904
+ }
499905
+ var init_channel_control = __esmMin((() => {}));
499552
499906
  var init_telegram_session_queue$1 = __esmMin((() => {
499553
499907
  SESSION_QUEUE_READ_BYTES = 65536;
499554
499908
  }));
@@ -499803,11 +500157,13 @@ var init_telegram_session_queue_delivery = __esmMin((() => {
499803
500157
  init_channel_injection();
499804
500158
  init_telegram_session_queue();
499805
500159
  init_telegram_session_queue_store();
499806
- SessionQueueDelivery = class {
500160
+ init_channel_control();
500161
+ SessionQueueDelivery = class {
499807
500162
  host;
499808
500163
  boundSessionId;
499809
500164
  inFlight = /* @__PURE__ */ new Set();
499810
- queueFile;
500165
+ controlsInFlight = /* @__PURE__ */ new Set();
500166
+ queueFile;
499811
500167
  stateFile;
499812
500168
  constructor(dir, host) {
499813
500169
  this.host = host;
@@ -499842,15 +500198,41 @@ var init_telegram_session_queue_delivery = __esmMin((() => {
499842
500198
  if (state === void 0) throw new Error("Telegram session queue checkpoint is missing");
499843
500199
  state = observeSessionQueue(state, position);
499844
500200
  if (JSON.stringify(state) !== before) writeSessionQueue(this.stateFile, state);
499845
- if (rebind) this.inFlight.clear();
500201
+ if (rebind) {
500202
+ this.inFlight.clear();
500203
+ this.controlsInFlight.clear();
500204
+ }
499846
500205
  this.boundSessionId = scope.sessionId;
499847
500206
  if (!deliver) return;
499848
- if (this.inFlight.size >= 16) return;
500207
+ for (const pending of pendingSessionQueue(state, scope.sessionId)) for (const line of readLines(this.queueFile, pending)) {
500208
+ if (!this.host.ownsChannel() || this.host.currentSessionId() !== scope.sessionId) return;
500209
+ const envelope = parseChannelEnvelope(line.text);
500210
+ if (envelope === void 0 || !isChannelStop(envelope)) continue;
500211
+ const key = `${line.range.fileId}:${line.range.start}:${line.range.end}`;
500212
+ if (this.controlsInFlight.has(key)) continue;
500213
+ this.controlsInFlight.add(key);
500214
+ const scopedEnvelope = {
500215
+ ...envelope,
500216
+ meta: {
500217
+ ...envelope.meta,
500218
+ queue_file_id: line.range.fileId,
500219
+ queue_start: String(line.range.start),
500220
+ queue_end: String(line.range.end)
500221
+ }
500222
+ };
500223
+ this.host.inject(scopedEnvelope, () => {
500224
+ if (!this.host.ownsChannel()) return;
500225
+ const current = readSessionQueue(this.stateFile);
500226
+ if (current === void 0) throw new Error("Telegram session queue checkpoint is missing");
500227
+ writeSessionQueue(this.stateFile, acknowledgeSessionQueue(current, scope.sessionId, line.range));
500228
+ this.controlsInFlight.delete(key);
500229
+ });
500230
+ }
499849
500231
  let delivered = 0;
499850
500232
  for (const pending of pendingSessionQueue(state, scope.sessionId)) for (const line of readLines(this.queueFile, pending)) {
499851
500233
  if (!this.host.ownsChannel() || this.host.currentSessionId() !== scope.sessionId) return;
499852
500234
  const key = `${line.range.fileId}:${line.range.start}:${line.range.end}`;
499853
- if (this.inFlight.has(key)) continue;
500235
+ if (this.inFlight.has(key) || this.controlsInFlight.has(key)) continue;
499854
500236
  const acknowledge = () => {
499855
500237
  if (!this.host.ownsChannel()) return;
499856
500238
  const current = readSessionQueue(this.stateFile);
@@ -499861,9 +500243,20 @@ var init_telegram_session_queue_delivery = __esmMin((() => {
499861
500243
  this.inFlight.add(key);
499862
500244
  const envelope = parseChannelEnvelope(line.text);
499863
500245
  if (envelope === void 0) acknowledge();
499864
- else this.host.inject(envelope, acknowledge);
500246
+ else if (isChannelStop(envelope)) {
500247
+ this.inFlight.delete(key);
500248
+ continue;
500249
+ } else this.host.inject({
500250
+ ...envelope,
500251
+ meta: {
500252
+ ...envelope.meta,
500253
+ queue_file_id: line.range.fileId,
500254
+ queue_start: String(line.range.start),
500255
+ queue_end: String(line.range.end)
500256
+ }
500257
+ }, acknowledge);
499865
500258
  delivered += 1;
499866
- if (delivered >= 16 || this.inFlight.size >= 16) return;
500259
+ if (delivered >= 16) return;
499867
500260
  }
499868
500261
  }
499869
500262
  };
@@ -525368,7 +525761,306 @@ var init_web = __esmMin((() => {
525368
525761
  WEB_CONFIRM = "confirm";
525369
525762
  WEB_CANCEL = "cancel";
525370
525763
  }));
525764
+ var session_search_exports = /* @__PURE__ */ __exportAll({
525765
+ SEARCH_LIMITS: () => SEARCH_LIMITS,
525766
+ handleSessionSearchCommand: () => handleSessionSearchCommand,
525767
+ searchSessionMessages: () => searchSessionMessages
525768
+ });
525769
+ async function searchSessionMessages(input) {
525770
+ const result = {
525771
+ scope: input.all ? "all" : "cwd",
525772
+ hits: [],
525773
+ partial: false,
525774
+ reasons: [],
525775
+ bytesRead: 0,
525776
+ sessionsScanned: 0,
525777
+ rejected: 0,
525778
+ malformed: 0
525779
+ };
525780
+ const reason = (value) => {
525781
+ result.partial = true;
525782
+ if (!result.reasons.includes(value)) result.reasons.push(value);
525783
+ };
525784
+ if (typeof input.query !== "string" || !input.query.trim() || input.query.length > 256) throw new Error("query-length");
525785
+ if (!isAbsolute(input.homeDir) || !isAbsolute(input.workDir)) throw new Error("absolute-scope-required");
525786
+ const limits = { ...SEARCH_LIMITS };
525787
+ for (const key of Object.keys(limits)) {
525788
+ const value = input.limits?.[key];
525789
+ if (value !== void 0) {
525790
+ if (!Number.isSafeInteger(value) || value < 1 || value > SEARCH_LIMITS[key]) throw new Error("invalid-budget");
525791
+ limits[key] = value;
525792
+ }
525793
+ }
525794
+ const start = performance$1.now(), home = resolve(input.homeDir), sessions = join(home, "sessions");
525795
+ const check = () => {
525796
+ if (input.signal?.aborted || input.isCurrent?.() === false) throw new SearchStop("cancelled");
525797
+ if (performance$1.now() - start >= limits.milliseconds) throw new SearchStop("time-limit");
525798
+ };
525799
+ const owner = typeof process.getuid === "function" ? process.getuid() : void 0;
525800
+ const identity = async (file) => lstat(file, { bigint: true });
525801
+ 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;
525802
+ 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);
525803
+ async function safePath(file, bounded = true) {
525804
+ if (bounded) check();
525805
+ if (!inside(home, file) || await realpath(home) !== home) throw new Error("unsafe-path");
525806
+ let current = home;
525807
+ const parts = relative(home, file).split(sep), ancestors = [];
525808
+ for (let i = -1; i < parts.length; i++) {
525809
+ if (i >= 0) current = join(current, parts[i]);
525810
+ const st = await identity(current);
525811
+ if (!valid(st, i < parts.length - 1)) throw new Error("unsafe-owner-path");
525812
+ ancestors.push(st);
525813
+ }
525814
+ if (await realpath(file) !== file) throw new Error("unsafe-path");
525815
+ const leaf = await identity(file);
525816
+ if (!valid(leaf, false) || !same(leaf, ancestors.at(-1))) throw new Error("file-changed");
525817
+ if (bounded) check();
525818
+ return {
525819
+ leaf,
525820
+ ancestors
525821
+ };
525822
+ }
525823
+ 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);
525824
+ async function* lines(file, byteLimit, label) {
525825
+ const before = await safePath(file);
525826
+ const handle = await open(file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
525827
+ try {
525828
+ const opened = await handle.stat({ bigint: true });
525829
+ if (!valid(opened, false) || !same(opened, before.leaf)) throw new Error("file-changed");
525830
+ const bound = await safePath(file);
525831
+ if (!samePath(before, bound) || !same(opened, bound.leaf)) throw new Error("file-changed");
525832
+ const openedSize = Number(opened.size), end = Math.min(openedSize, byteLimit);
525833
+ if (openedSize > end) reason(label);
525834
+ const validateFinish = async () => {
525835
+ const after = await handle.stat({ bigint: true });
525836
+ const finalPath = await safePath(file, false);
525837
+ 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");
525838
+ };
525839
+ try {
525840
+ let position = 0, line = 1, offset = 0, pending = Buffer.alloc(0), oversized = false;
525841
+ while (position < end) {
525842
+ check();
525843
+ if (result.bytesRead >= limits.totalBytes) throw new SearchStop("total-byte-limit");
525844
+ const size = Math.min(32768, end - position, limits.totalBytes - result.bytesRead);
525845
+ const buffer = Buffer.allocUnsafe(size);
525846
+ const read = await handle.read(buffer, 0, size, position);
525847
+ result.bytesRead += read.bytesRead;
525848
+ check();
525849
+ if (read.bytesRead === 0) throw new Error("file-changed");
525850
+ position += read.bytesRead;
525851
+ const chunk = buffer.subarray(0, read.bytesRead);
525852
+ let at = 0;
525853
+ while (at < chunk.length) {
525854
+ check();
525855
+ const newline = chunk.indexOf(10, at), stop = newline < 0 ? chunk.length : newline;
525856
+ if (!oversized) if (pending.length + stop - at > limits.lineBytes) {
525857
+ pending = Buffer.alloc(0);
525858
+ oversized = true;
525859
+ reason("line-limit");
525860
+ } else pending = Buffer.concat([pending, chunk.subarray(at, stop)]);
525861
+ if (newline < 0) break;
525862
+ if (!oversized) yield {
525863
+ raw: pending,
525864
+ line,
525865
+ offset
525866
+ };
525867
+ offset = position - chunk.length + newline + 1;
525868
+ line++;
525869
+ pending = Buffer.alloc(0);
525870
+ oversized = false;
525871
+ at = newline + 1;
525872
+ }
525873
+ }
525874
+ if (pending.length && !oversized && position === openedSize) yield {
525875
+ raw: pending,
525876
+ line,
525877
+ offset
525878
+ };
525879
+ } finally {
525880
+ await validateFinish();
525881
+ }
525882
+ } finally {
525883
+ await handle.close();
525884
+ }
525885
+ }
525886
+ const parse = (raw) => {
525887
+ if (raw.length === 0 || raw.toString("utf8").trim() === "") return void 0;
525888
+ try {
525889
+ if (!isUtf8(raw)) throw new Error("utf8");
525890
+ return JSON.parse(raw.toString("utf8"));
525891
+ } catch {
525892
+ result.malformed++;
525893
+ reason("malformed-record");
525894
+ return;
525895
+ }
525896
+ };
525897
+ try {
525898
+ check();
525899
+ const entries = /* @__PURE__ */ new Map();
525900
+ try {
525901
+ const stagedEntries = /* @__PURE__ */ new Map();
525902
+ for await (const row of lines(join(home, "session_index.jsonl"), limits.indexBytes, "index-byte-limit")) {
525903
+ const e = parse(row.raw);
525904
+ 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)) {
525905
+ if (e !== void 0) {
525906
+ result.rejected++;
525907
+ reason("rejected-index-entry");
525908
+ }
525909
+ continue;
525910
+ }
525911
+ if (!stagedEntries.has(e.sessionId) && stagedEntries.size >= limits.sessions) {
525912
+ reason("session-limit");
525913
+ break;
525914
+ }
525915
+ stagedEntries.set(e.sessionId, {
525916
+ id: e.sessionId,
525917
+ dir: resolve(e.sessionDir),
525918
+ workDir: resolve(e.workDir)
525919
+ });
525920
+ }
525921
+ for (const [id, entry] of stagedEntries) entries.set(id, entry);
525922
+ } catch (error) {
525923
+ if (error instanceof SearchStop) throw error;
525924
+ result.rejected++;
525925
+ reason("index-unavailable");
525926
+ if (error instanceof Error && error.message === "file-changed") reason("file-changed");
525927
+ }
525928
+ for (const entry of entries.values()) {
525929
+ if (!input.all && entry.workDir !== resolve(input.workDir)) continue;
525930
+ check();
525931
+ const wire = join(entry.dir, "agents", "main", "wire.jsonl");
525932
+ result.sessionsScanned++;
525933
+ try {
525934
+ const stagedHits = [];
525935
+ let hitLimit = false;
525936
+ rows: for await (const row of lines(wire, limits.fileBytes, "file-byte-limit")) {
525937
+ const record = parse(row.raw);
525938
+ const message = record?.type === "context.append_message" ? record.message : void 0;
525939
+ if (!message || message.role !== "user" && message.role !== "assistant" || !Array.isArray(message.content)) continue;
525940
+ const origin = message.origin;
525941
+ if (origin !== void 0 && (origin === null || typeof origin !== "object" || Array.isArray(origin) || typeof origin.kind !== "string")) {
525942
+ result.malformed++;
525943
+ reason("malformed-record");
525944
+ continue;
525945
+ }
525946
+ try {
525947
+ if (input.isInternalMessage(message)) continue;
525948
+ } catch {
525949
+ result.malformed++;
525950
+ reason("malformed-record");
525951
+ continue;
525952
+ }
525953
+ for (let partIndex = 0; partIndex < message.content.length; partIndex++) {
525954
+ const part = message.content[partIndex];
525955
+ if (part?.type !== "text" || typeof part.text !== "string") continue;
525956
+ for (let from = 0; from <= part.text.length - input.query.length;) {
525957
+ check();
525958
+ const found = part.text.indexOf(input.query, from);
525959
+ if (found < 0) break;
525960
+ stagedHits.push({
525961
+ sessionId: entry.id,
525962
+ wire: "agents/main/wire.jsonl",
525963
+ line: row.line,
525964
+ recordByteOffset: row.offset,
525965
+ partIndex,
525966
+ utf16Offset: found,
525967
+ utf16Length: input.query.length,
525968
+ role: message.role,
525969
+ preview: part.text.slice(Math.max(0, found - 60), found + input.query.length + 60)
525970
+ });
525971
+ if (result.hits.length + stagedHits.length >= limits.hits) {
525972
+ hitLimit = true;
525973
+ break rows;
525974
+ }
525975
+ from = found + 1;
525976
+ }
525977
+ }
525978
+ }
525979
+ result.hits.push(...stagedHits);
525980
+ if (hitLimit) throw new SearchStop("hit-limit");
525981
+ } catch (error) {
525982
+ if (error instanceof SearchStop) throw error;
525983
+ result.rejected++;
525984
+ reason("wire-unavailable");
525985
+ if (error instanceof Error && error.message === "file-changed") reason("file-changed");
525986
+ }
525987
+ }
525988
+ } catch (error) {
525989
+ if (!(error instanceof SearchStop)) throw error;
525990
+ reason(error.message);
525991
+ }
525992
+ return result;
525993
+ }
525994
+ async function handleSessionSearchCommand(host, args, isInternalMessage, requestController) {
525995
+ if (requestController?.signal.aborted) return;
525996
+ const text = args.trim();
525997
+ if (host.getChannelCommandContext?.() !== void 0 || host.session?.connectionKind === "gateway") {
525998
+ host.showError("local-console-only");
525999
+ return;
526000
+ }
526001
+ if (text === "--cancel") {
526002
+ active.get(host)?.abort();
526003
+ active.delete(host);
526004
+ return;
526005
+ }
526006
+ const all = text.startsWith("--all "), query = all ? text.slice(6).trim() : text;
526007
+ if (!query || query.length > 256 || query.startsWith("--")) {
526008
+ host.showStatus(JSON.stringify({
526009
+ format: "blun-session-search-json-v1",
526010
+ usage: "/sessions search [--all] <text> | /sessions search --cancel"
526011
+ }));
526012
+ return;
526013
+ }
526014
+ active.get(host)?.abort();
526015
+ const controller = requestController ?? new AbortController();
526016
+ active.set(host, controller);
526017
+ const session = host.session, workDir = host.state.appState.workDir, sessionId = host.state.appState.sessionId;
526018
+ const harness = host.harness, homeDir = harness.homeDir;
526019
+ 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;
526020
+ try {
526021
+ const result = await searchSessionMessages({
526022
+ homeDir,
526023
+ workDir,
526024
+ query,
526025
+ all,
526026
+ signal: controller.signal,
526027
+ isCurrent: current,
526028
+ isInternalMessage
526029
+ });
526030
+ if (current()) host.showStatus(JSON.stringify({
526031
+ format: "blun-session-search-json-v1",
526032
+ ...result
526033
+ }, null, 2).replace(/[\u007f-\u009f\u202a-\u202e\u2066-\u2069]/g, (char) => `\\u${char.charCodeAt(0).toString(16).padStart(4, "0")}`));
526034
+ } catch (error) {
526035
+ if (current()) host.showError(error instanceof Error ? error.message : "search-failed");
526036
+ } finally {
526037
+ if (active.get(host) === controller) active.delete(host);
526038
+ }
526039
+ }
526040
+ var init_session_search = __esmMin((() => {
526041
+ SEARCH_LIMITS = Object.freeze({
526042
+ indexBytes: 1024 * 1024,
526043
+ fileBytes: 4 * 1024 * 1024,
526044
+ totalBytes: 16 * 1024 * 1024,
526045
+ lineBytes: 256 * 1024,
526046
+ sessions: 128,
526047
+ hits: 100,
526048
+ milliseconds: 1500
526049
+ });
526050
+ SearchStop = class extends Error {};
526051
+ active = /* @__PURE__ */ new WeakMap();
526052
+ inside = (root, child) => {
526053
+ const rel = relative(root, child);
526054
+ return rel !== "" && !isAbsolute(rel) && rel !== ".." && !rel.startsWith(`..${sep}`);
526055
+ };
526056
+ }));
526057
+ function tryCancelSessionSearchInput(host, text) {
526058
+ if (!/^\/sessions[ \t]+search[ \t]+--cancel$/.test(text.trim()) || host.getChannelCommandContext?.() !== void 0 || host.session?.connectionKind === "gateway") return false;
526059
+ sessionSearchRequests.get(host)?.abort();
526060
+ return true;
526061
+ }
525371
526062
  function dispatchInput(host, text) {
526063
+ if (tryCancelSessionSearchInput(host, text)) return Promise.resolve();
525372
526064
  if (isExperimentalFlagEnabled("multiline_chat_input") && isMultilineChatInput(text)) {
525373
526065
  host.sendNormalUserInput(text);
525374
526066
  return Promise.resolve();
@@ -525511,6 +526203,24 @@ async function handleBuiltInSlashCommand(host, name, args, invokedName = name) {
525511
526203
  host.state.ui.requestRender();
525512
526204
  return;
525513
526205
  case "sessions":
526206
+ if (/^search(?:\s|$)/.test(args.trim())) {
526207
+ const searchOwner = host.session;
526208
+ const searchWorkDir = host.state.appState.workDir;
526209
+ const searchSessionId = host.state.appState.sessionId;
526210
+ const searchHarness = host.harness;
526211
+ const searchHomeDir = searchHarness.homeDir;
526212
+ sessionSearchRequests.get(host)?.abort();
526213
+ const searchController = new AbortController();
526214
+ sessionSearchRequests.set(host, searchController);
526215
+ try {
526216
+ const { handleSessionSearchCommand } = await Promise.resolve().then(() => (init_session_search(), session_search_exports));
526217
+ 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;
526218
+ await handleSessionSearchCommand(host, args.trim().slice(6), isInternalMessage, searchController);
526219
+ } finally {
526220
+ if (sessionSearchRequests.get(host) === searchController) sessionSearchRequests.delete(host);
526221
+ }
526222
+ return;
526223
+ }
525514
526224
  if ((host.session?.connectionKind === "gateway" || isExperimentalFlagEnabled("session_references")) && args.trim().length > 0) await host.showSessionPicker(args.trim());
525515
526225
  else await host.showSessionPicker();
525516
526226
  return;
@@ -525689,6 +526399,7 @@ async function handleBuiltInSlashCommand(host, name, args, invokedName = name) {
525689
526399
  }
525690
526400
  }
525691
526401
  var init_dispatch = __esmMin((() => {
526402
+ init_export_markdown();
525692
526403
  init_dispatch_swarm_copy();
525693
526404
  init_activation();
525694
526405
  init_elevated();
@@ -525727,6 +526438,7 @@ var init_dispatch = __esmMin((() => {
525727
526438
  init_telegram_access();
525728
526439
  init_undo();
525729
526440
  init_web();
526441
+ sessionSearchRequests = /* @__PURE__ */ new WeakMap();
525730
526442
  }));
525731
526443
  var init_commands = __esmMin((() => {
525732
526444
  init_experimental_flags();
@@ -527856,7 +528568,7 @@ function singleLine$1(text) {
527856
528568
  return sanitizeTerminalText(text).replaceAll(/\s+/g, " ").trim();
527857
528569
  }
527858
528570
  function sessionSearchText(session) {
527859
- return singleLine$1(`${session.id} ${session.title ?? ""}`);
528571
+ return singleLine$1(`${session.id} ${session.title ?? ""} ${session.work_dir ?? ""} ${session.last_prompt ?? ""}`);
527860
528572
  }
527861
528573
  var ELLIPSIS$3, SessionPickerComponent;
527862
528574
  var init_session_picker$1 = __esmMin((() => {
@@ -530711,16 +531423,22 @@ var init_channel_queue_deadline = __esmMin((() => {
530711
531423
  deliveryInFlight = false;
530712
531424
  pendingReleaseCount = 0;
530713
531425
  disposed = false;
530714
- constructor(host) {
531426
+ scope;
531427
+ constructor(host) {
530715
531428
  this.host = host;
531429
+ this.scope = host.deliveryScope?.();
531430
+ }
531431
+ sync() {
531432
+ this.refreshScope();
530716
531433
  }
530717
- sync() {}
530718
531434
  requestDeliveryAtSafePoint() {
531435
+ this.refreshScope();
530719
531436
  if (this.retainReleaseWhileDeliveryIsInFlight()) return;
530720
531437
  if (this.host.hasWaitingWork() && !this.host.canDeliverWork()) return;
530721
531438
  this.requestDelivery();
530722
531439
  }
530723
531440
  requestDeliveryNow() {
531441
+ this.refreshScope();
530724
531442
  if (this.retainReleaseWhileDeliveryIsInFlight()) return;
530725
531443
  if (this.host.hasWaitingWork() && !this.host.canDeliverWork()) return;
530726
531444
  this.requestDelivery();
@@ -530739,7 +531457,14 @@ var init_channel_queue_deadline = __esmMin((() => {
530739
531457
  this.pendingReleaseCount += 1;
530740
531458
  this.pumpDelivery();
530741
531459
  }
530742
- pumpDelivery() {
531460
+ refreshScope() {
531461
+ const scope = this.host.deliveryScope?.();
531462
+ if (scope === this.scope) return;
531463
+ this.scope = scope;
531464
+ this.pendingReleaseCount = 0;
531465
+ }
531466
+ pumpDelivery() {
531467
+ this.refreshScope();
530743
531468
  if (this.disposed || this.deliveryInFlight || this.pendingReleaseCount === 0) return;
530744
531469
  if (!this.host.hasWaitingWork() || !this.host.canDeliverWork()) {
530745
531470
  this.pendingReleaseCount = 0;
@@ -530747,7 +531472,8 @@ var init_channel_queue_deadline = __esmMin((() => {
530747
531472
  }
530748
531473
  this.pendingReleaseCount -= 1;
530749
531474
  this.deliveryInFlight = true;
530750
- Promise.resolve().then(() => this.host.deliverOne()).catch(() => false).finally(() => {
531475
+ const scope = this.host.deliveryScope?.();
531476
+ Promise.resolve().then(() => this.disposed || scope !== this.host.deliveryScope?.() || !this.host.hasWaitingWork() || !this.host.canDeliverWork() ? false : this.host.deliverOne()).catch(() => false).finally(() => {
530751
531477
  this.deliveryInFlight = false;
530752
531478
  this.pumpDelivery();
530753
531479
  });
@@ -530755,6 +531481,81 @@ var init_channel_queue_deadline = __esmMin((() => {
530755
531481
  };
530756
531482
  }));
530757
531483
  var REMOTE_COMMANDS, REMOTE_COMMAND_LIST;
531484
+ var init_active_input_delivery = __esmMin((() => {
531485
+ ActiveInputDelivery = class {
531486
+ host;
531487
+ attempts = /* @__PURE__ */ new Map();
531488
+ pumping = false;
531489
+ dirty = false;
531490
+ ended = false;
531491
+ constructor(host) {
531492
+ this.host = host;
531493
+ }
531494
+ has(item) {
531495
+ return item !== void 0 && this.attempts.has(item);
531496
+ }
531497
+ endTurn() {
531498
+ this.ended = true;
531499
+ for (const [item, attempt] of this.attempts) if (attempt.terminal) this.attempts.delete(item);
531500
+ this.host.retry();
531501
+ }
531502
+ cancel() {
531503
+ for (const attempt of this.attempts.values()) attempt.abort.abort();
531504
+ this.attempts.clear();
531505
+ }
531506
+ request() {
531507
+ if (this.ended) return;
531508
+ this.dirty = true;
531509
+ if (this.pumping) return;
531510
+ this.pumping = true;
531511
+ this.pump().finally(() => {
531512
+ this.pumping = false;
531513
+ if (this.dirty) this.request();
531514
+ });
531515
+ }
531516
+ async pump() {
531517
+ do {
531518
+ this.dirty = false;
531519
+ for (const item of this.host.items()) {
531520
+ const prior = this.attempts.get(item);
531521
+ if (prior !== void 0) {
531522
+ if (!prior.accepted) return;
531523
+ continue;
531524
+ }
531525
+ const attempt = {
531526
+ accepted: false,
531527
+ terminal: false,
531528
+ abort: new AbortController()
531529
+ };
531530
+ this.attempts.set(item, attempt);
531531
+ let admitted;
531532
+ const acceptance = new Promise((resolve) => {
531533
+ admitted = resolve;
531534
+ });
531535
+ this.host.send(item, attempt.abort.signal, () => {
531536
+ attempt.accepted = true;
531537
+ admitted();
531538
+ }).then((disposition) => {
531539
+ if (attempt.abort.signal.aborted || this.attempts.get(item) !== attempt) return;
531540
+ attempt.terminal = true;
531541
+ if (disposition === "context") {
531542
+ this.attempts.delete(item);
531543
+ this.host.commit(item);
531544
+ }
531545
+ if (disposition !== "context" && this.ended) {
531546
+ this.attempts.delete(item);
531547
+ this.host.retry();
531548
+ }
531549
+ }).catch((error) => {
531550
+ if (!attempt.abort.signal.aborted) this.host.error(error);
531551
+ }).finally(admitted);
531552
+ await acceptance;
531553
+ if (attempt.abort.signal.aborted || !attempt.accepted) return;
531554
+ }
531555
+ } while (this.dirty);
531556
+ }
531557
+ };
531558
+ }));
530758
531559
  var init_channel_command$1 = __esmMin((() => {
530759
531560
  REMOTE_COMMANDS = new Set([
530760
531561
  "loop",
@@ -530770,6 +531571,7 @@ var init_channel_command$1 = __esmMin((() => {
530770
531571
  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";
530771
531572
  }));
530772
531573
  function channelCommandInput(envelope) {
531574
+ if (isChannelStop(envelope)) return "/stop";
530773
531575
  if (!channelMessageAddressed(envelope) || envelope.meta["addressed"]?.trim().toLowerCase() === "semantic") return void 0;
530774
531576
  const parsed = parseSlashInput(envelope.text.trim());
530775
531577
  if (parsed === null) return void 0;
@@ -530778,6 +531580,7 @@ function channelCommandInput(envelope) {
530778
531580
  return parsed.args.length === 0 ? `/${name}` : `/${name} ${parsed.args}`;
530779
531581
  }
530780
531582
  function channelCommandCanInterrupt(input) {
531583
+ if (input.trim() === "/stop") return true;
530781
531584
  const parsed = parseSlashInput(input);
530782
531585
  if (parsed?.name === "befehle") return true;
530783
531586
  if (parsed === null) return false;
@@ -530800,7 +531603,8 @@ var init_channel_command = __esmMin((() => {
530800
531603
  init_channel_command$1();
530801
531604
  init_channel_injection();
530802
531605
  init_event_payload();
530803
- ChannelCommandController = class {
531606
+ init_channel_control();
531607
+ ChannelCommandController = class {
530804
531608
  host;
530805
531609
  execution = new AsyncLocalStorage();
530806
531610
  constructor(host) {
@@ -530810,7 +531614,8 @@ var init_channel_command = __esmMin((() => {
530810
531614
  const execution = this.execution.getStore();
530811
531615
  return execution?.active ? {
530812
531616
  input: execution.input,
530813
- chatId: execution.envelope.meta.chat_id
531617
+ chatId: execution.envelope.meta.chat_id,
531618
+ envelope: execution.envelope
530814
531619
  } : void 0;
530815
531620
  }
530816
531621
  commit() {
@@ -536499,7 +537304,11 @@ var init_session_event_handler = __esmMin((() => {
536499
537304
  });
536500
537305
  this.host.resetLivePane();
536501
537306
  this.host.requestQueueDrain();
536502
- } else { this.host.setAppState({ isCompacting: false }); this.host.steerQueueFlushPrefix(); }
537307
+ } else {
537308
+ this.host.setAppState({ isCompacting: false });
537309
+ this.host.steerQueueFlushPrefix();
537310
+ }
537311
+ this.host.releaseChannelQueueAtSafePoint();
536503
537312
  }
536504
537313
  handleBackgroundTaskEvent(event) {
536505
537314
  const { state } = this.host;
@@ -544343,7 +545152,10 @@ var init_blun_tui = __esmMin((() => {
544343
545152
  init_transcript_id();
544344
545153
  init_blun_tui_copy();
544345
545154
  DETACH_HINT_DISPLAY_MS = 4e3;
544346
- BlunTUI = class {
545155
+ init_queue_deadline_watchdog();
545156
+ init_stopped_input_scopes();
545157
+ init_active_input_delivery();
545158
+ BlunTUI = class {
544347
545159
  gatewayStartup;
544348
545160
  localHarness;
544349
545161
  gatewayLifetime = new AbortController();
@@ -544432,7 +545244,12 @@ var init_blun_tui = __esmMin((() => {
544432
545244
  telegramSessionScope;
544433
545245
  channelPreamble = createChannelPreambleState();
544434
545246
  channelQueueDeadline;
544435
- activeApprovalPanel;
545247
+ queueDeadlineWatchdog;
545248
+ queueDeadlineStatus;
545249
+ getQueueDeadlineStatus() {
545250
+ return this.queueDeadlineStatus;
545251
+ }
545252
+ activeApprovalPanel;
544436
545253
  approvalPreview;
544437
545254
  onExit;
544438
545255
  setupHandoff;
@@ -544518,10 +545335,19 @@ var init_blun_tui = __esmMin((() => {
544518
545335
  this.appearanceBasePalette = currentTheme.palette;
544519
545336
  this.resolvedAutoTheme = currentTheme.palette === lightColors ? "light" : "dark";
544520
545337
  currentTheme.setPalette(applyAppearanceToPalette(currentTheme.palette, initialAppState.appearance));
545338
+ this.queueDeadlineWatchdog = new QueueDeadlineWatchdog(() => ({
545339
+ owner: this.session,
545340
+ entries: [...this.queueSteerInFlight?.items ?? [], ...this.state.queuedMessages],
545341
+ reason: this.queueDeadlineBlockingReason()
545342
+ }), (status) => {
545343
+ this.queueDeadlineStatus = status;
545344
+ this.state.ui.requestRender();
545345
+ });
544521
545346
  this.channelQueueDeadline = new ChannelQueueDeadlineController({
544522
545347
  hasWaitingWork: () => this.hasWaitingChannelMessage(),
544523
545348
  canDeliverWork: () => this.canDeliverQueuedChannelHead(),
544524
- deliverOne: () => this.deliverQueuedChannelHead()
545349
+ deliverOne: () => this.deliverQueuedChannelHead(),
545350
+ deliveryScope: () => this.session
544525
545351
  });
544526
545352
  this.managedQuotaWarningController = new ManagedQuotaWarningController({ onChange: (warning) => {
544527
545353
  this.state.quotaWarning.setMessage(warning === void 0 ? void 0 : formatManagedQuotaWarning(warning));
@@ -545264,6 +546090,7 @@ var init_blun_tui = __esmMin((() => {
545264
546090
  }
545265
546091
  this.loopCountdown.dispose();
545266
546092
  this.channelQueueDeadline?.dispose();
546093
+ this.queueDeadlineWatchdog?.dispose();
545267
546094
  try {
545268
546095
  await this.telegramChannel?.stop();
545269
546096
  } catch (error) {
@@ -545352,6 +546179,7 @@ var init_blun_tui = __esmMin((() => {
545352
546179
  this.isShuttingDown = true;
545353
546180
  this.unregisterSignalHandlers();
545354
546181
  this.channelQueueDeadline?.dispose();
546182
+ this.queueDeadlineWatchdog?.dispose();
545355
546183
  this.telegramChannel?.stopNow();
545356
546184
  this.telegramChannel = void 0;
545357
546185
  restoreTerminalModes();
@@ -545418,6 +546246,7 @@ var init_blun_tui = __esmMin((() => {
545418
546246
  }
545419
546247
  const historyText = wasBashMode ? `!${text}` : text;
545420
546248
  this.persistInputHistory(historyText);
546249
+ if (!wasBashMode && tryCancelSessionSearchInput(this, text)) return;
545421
546250
  if (this.editorReplacementActive || this.queueCommandRunning || this.localShellConsentRequest !== void 0) {
545422
546251
  if (wasBashMode) this.enqueueMessage(text, void 0, "bash");
545423
546252
  else if (text.trimStart().startsWith("/") && !(isExperimentalFlagEnabled("multiline_chat_input") && isMultilineChatInput(text))) {
@@ -545581,6 +546410,7 @@ var init_blun_tui = __esmMin((() => {
545581
546410
  const stream = this.shellOutputStreams.get(event.commandId);
545582
546411
  if (stream === void 0) return;
545583
546412
  stream.taskId = event.taskId;
546413
+ toolLiveness642.yieldRequestedLocalShell(this, event.commandId, stream);
545584
546414
  }
545585
546415
  cancelRunningShellCommand() {
545586
546416
  const session = this.session;
@@ -545609,7 +546439,11 @@ var init_blun_tui = __esmMin((() => {
545609
546439
  finishShellOutput(commandId, stdout, stderr, isError, backgrounded) {
545610
546440
  const stream = this.shellOutputStreams.get(commandId);
545611
546441
  if (stream === void 0) return;
545612
- if (backgrounded === true) return;
546442
+ if (backgrounded === true) {
546443
+ toolLiveness642.releaseLocalShell(this, commandId, stream,
546444
+ uiText("blunTui.detach.movedTranscript"));
546445
+ return;
546446
+ }
545613
546447
  stream.component.finish(stdout, stderr, isError);
545614
546448
  stream.entry.content = formatBashOutputForDisplay(stdout, stderr, isError);
545615
546449
  this.shellOutputStreams.delete(commandId);
@@ -545639,13 +546473,17 @@ var init_blun_tui = __esmMin((() => {
545639
546473
  return this.state.queuedMessages.some((item) => item.mode === "channel");
545640
546474
  }
545641
546475
  canInterruptForQueuedChannel() {
546476
+ 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;
545642
546477
  if (this.hasPendingQueueCommandCancellation()) return false;
545643
546478
  const item = this.state.queuedMessages[0];
545644
546479
  if (/^[1-9]\d*$/u.test(this.pendingChannelReplyGuard?.chatId ?? "") && item?.channelChatId?.startsWith("-") === true) return false;
545645
546480
  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();
545646
546481
  }
545647
546482
  canDeliverQueuedChannelHead() {
546483
+ 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;
546484
+ if (this.activeInputDelivery?.has(this.state.queuedMessages[0])) return false;
545648
546485
  if (this.hasPendingQueueCommandCancellation()) return false;
546486
+ if (this.state.appState.isCompacting || this.shellOutputStreams.size > 0 || this.state.appState.streamingPhase === "shell") return false;
545649
546487
  const item = this.state.queuedMessages[0];
545650
546488
  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;
545651
546489
  const guard = this.pendingChannelReplyGuard;
@@ -545688,6 +546526,7 @@ var init_blun_tui = __esmMin((() => {
545688
546526
  ...item,
545689
546527
  channelTranscriptRendered: transcriptRendered
545690
546528
  };
546529
+ this.queueDeadlineWatchdog?.transfer(item, queuedItem);
545691
546530
  const previousGuard = this.pendingChannelReplyGuard;
545692
546531
  let installedGuard;
545693
546532
  if (previousGuard === void 0 && item.channelChatId !== void 0) {
@@ -545753,6 +546592,11 @@ var init_blun_tui = __esmMin((() => {
545753
546592
  this.commitQueuedSteerIfReady(inFlight);
545754
546593
  }
545755
546594
  restoreQueuedSteerAtTurnEnd(turnId) {
546595
+ if (this.activeInputScope === JSON.stringify([
546596
+ this.session?.id,
546597
+ this.interactiveAgentId,
546598
+ String(turnId)
546599
+ ])) this.activeInputDelivery?.endTurn();
545756
546600
  const inFlight = this.queueSteerInFlight;
545757
546601
  if (inFlight === void 0 || inFlight.turnId !== String(turnId)) return;
545758
546602
  inFlight.turnEnded = true;
@@ -545781,15 +546625,177 @@ var init_blun_tui = __esmMin((() => {
545781
546625
  return false;
545782
546626
  }
545783
546627
  syncChannelQueueDeadline() {
546628
+ this.admitActiveQueuedInputs();
545784
546629
  this.channelQueueDeadline?.sync();
546630
+ this.queueDeadlineWatchdog?.sync();
546631
+ }
546632
+ queueDeadlineBlockingReason() {
546633
+ if (this.isShuttingDown) return "shutdown";
546634
+ if (this.session === void 0) return "no_session";
546635
+ if (this.state.appState.isCompacting) return "compaction";
546636
+ if (this.streamingUI.hasActiveToolCalls() || this.shellOutputStreams.size > 0 || this.state.appState.streamingPhase === "shell") return "tool_or_shell";
546637
+ if (this.activeInputDelivery?.has(this.state.queuedMessages[0]) || this.queueSteerInFlight !== void 0 || this.manualPromptInFlight !== void 0) return "receipt_pending";
546638
+ if (this.deferUserMessages || this.queueCommandRunning || this.localShellConsentRequest !== void 0 || this.editorReplacementActive || this.hasPendingQueueCommandCancellation()) return "admission_barrier";
546639
+ const item = this.state.queuedMessages[0];
546640
+ if (this.pendingChannelReplyGuard !== void 0 && (item?.mode !== "channel" || item.channelChatId !== this.pendingChannelReplyGuard.chatId)) return "chat_boundary";
546641
+ if (this.state.appState.model.trim().length === 0) return "no_model";
546642
+ if (item?.mode === "command" || item?.mode === "bash" || item !== void 0 && item.mode !== "channel" && queueSteerPrefixLength([item], this.interactiveAgentId, 1) === 0) return "fifo_barrier";
546643
+ return this.state.appState.streamingPhase === "idle" ? "idle_admission_pending" : "model_step_or_safe_point";
546644
+ }
546645
+ stoppedInputScopes;
546646
+ get stoppedInputSession() {
546647
+ const session = this.session;
546648
+ return session !== void 0 && this.stoppedInputScopes?.get(session, this.interactiveAgentId) !== void 0 ? session : void 0;
546649
+ }
546650
+ set stoppedInputSession(session) {
546651
+ if (session === void 0) {
546652
+ if (this.session !== void 0) this.stoppedInputScopes?.clear(this.session, this.interactiveAgentId);
546653
+ return;
546654
+ }
546655
+ const turnId = this.streamingUI.getTurnContext().turnId;
546656
+ const agentId = this.interactiveAgentId;
546657
+ const command = this.channelCommands?.context;
546658
+ const activeChat = this.activeInputScope === JSON.stringify([
546659
+ session.id,
546660
+ agentId,
546661
+ turnId
546662
+ ]) ? this.activeInputChat : void 0;
546663
+ this.stoppedInputScopes ??= new StoppedInputScopes();
546664
+ this.stoppedInputScopes.stop(session, {
546665
+ sessionId: session.id,
546666
+ agentId,
546667
+ turnId,
546668
+ chatId: command?.input === "/stop" ? command.chatId : this.pendingChannelReplyGuard?.chatId ?? activeChat,
546669
+ runtimeScope: this.gatewayResetTurn?.session === session ? this.gatewayResetTurn.scope : void 0
546670
+ });
546671
+ }
546672
+ get stoppedQueueBoundary() {
546673
+ return this.session === void 0 ? void 0 : this.stoppedInputScopes?.get(this.session, this.interactiveAgentId)?.boundary;
545785
546674
  }
545786
- releaseChannelQueueAtSafePoint() {
545787
- this.channelQueueDeadline.requestDeliveryAtSafePoint();
546675
+ set stoppedQueueBoundary(boundary) {
546676
+ const scope = this.session === void 0 ? void 0 : this.stoppedInputScopes?.get(this.session, this.interactiveAgentId);
546677
+ if (scope !== void 0) scope.boundary = boundary;
546678
+ }
546679
+ channelOwnsStoppedInput(chatId) {
546680
+ const scope = this.session === void 0 ? void 0 : this.stoppedInputScopes?.get(this.session, this.interactiveAgentId);
546681
+ return scope === void 0 || scope.chatId === chatId;
546682
+ }
546683
+ activeInputRequests;
546684
+ activeInputDelivery;
546685
+ activeInputScope;
546686
+ activeInputChat;
546687
+ admitActiveQueuedInputs() {
546688
+ const session = this.session;
546689
+ 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;
546690
+ const turn = this.streamingUI.getTurnContext().turnId;
546691
+ if (turn === void 0 || !/^\d+$/.test(turn) || !Number.isSafeInteger(Number(turn))) return false;
546692
+ const agentId = this.interactiveAgentId;
546693
+ const scope = JSON.stringify([
546694
+ session.id,
546695
+ agentId,
546696
+ turn
546697
+ ]);
546698
+ if (this.activeInputScope !== scope) {
546699
+ this.activeInputDelivery?.cancel();
546700
+ this.activeInputScope = scope;
546701
+ this.activeInputChat = this.pendingChannelReplyGuard?.chatId;
546702
+ const current = () => this.session === session && this.activeInputScope === scope && this.interactiveAgentId === agentId;
546703
+ this.activeInputDelivery = new ActiveInputDelivery({
546704
+ items: () => {
546705
+ if (!current()) return [];
546706
+ const result = [];
546707
+ for (const item of this.state.queuedMessages) {
546708
+ if ((item.agentId ?? "main") !== agentId) break;
546709
+ if (this.activeInputDelivery?.has(item)) {
546710
+ result.push(item);
546711
+ continue;
546712
+ }
546713
+ if (item.mode === "channel") {
546714
+ if (this.activeInputChat === void 0) this.activeInputChat = item.channelChatId;
546715
+ if (item.channelContextOnly === true || this.activeInputChat !== void 0 && this.activeInputChat !== item.channelChatId || this.pendingChannelReplyGuard !== void 0 && this.pendingChannelReplyGuard.chatId !== item.channelChatId) break;
546716
+ } else if (item.mode !== void 0 && item.mode !== "prompt") break;
546717
+ result.push(item);
546718
+ }
546719
+ return result;
546720
+ },
546721
+ send: (item, signal, accepted) => {
546722
+ this.activeInputRequests ??= /* @__PURE__ */ new WeakMap();
546723
+ let request = this.activeInputRequests.get(item) ?? {};
546724
+ this.activeInputRequests.set(item, request);
546725
+ const image = item.channelImagePath === void 0 ? void 0 : buildChannelImagePart(item.channelImagePath);
546726
+ const input = item.parts !== void 0 ? [...item.parts] : image !== void 0 && this.canReadImages() ? [{
546727
+ type: "text",
546728
+ text: item.text.trim()
546729
+ }, image] : item.text.trim();
546730
+ return this.withInteractiveAgent(agentId, async () => {
546731
+ const originalTurn = request.identity?.expectedTurnId;
546732
+ let disposition = await deliverQueueSteer(session, input, Number(turn), signal, () => {
546733
+ if (request.identity?.expectedTurnId === Number(turn)) accepted();
546734
+ }, request);
546735
+ if (originalTurn !== void 0 && originalTurn !== Number(turn) && disposition !== "context") {
546736
+ request = {};
546737
+ this.activeInputRequests.set(item, request);
546738
+ disposition = await deliverQueueSteer(session, input, Number(turn), signal, accepted, request);
546739
+ }
546740
+ if (disposition !== "context") this.activeInputRequests?.delete(item);
546741
+ return disposition;
546742
+ });
546743
+ },
546744
+ commit: (item) => {
546745
+ if (!current() || !this.state.queuedMessages.includes(item)) return;
546746
+ this.activeInputRequests?.delete(item);
546747
+ this.state.queuedMessages = this.state.queuedMessages.filter((entry) => entry !== item);
546748
+ if (!(item.transcriptRendered || item.channelTranscriptRendered)) this.appendTranscriptEntry({
546749
+ id: nextTranscriptId(),
546750
+ kind: "user",
546751
+ turnId: turn,
546752
+ renderMode: "plain",
546753
+ content: item.displayText ?? item.text.trim(),
546754
+ origin: item.origin,
546755
+ imageAttachmentIds: item.imageAttachmentIds
546756
+ });
546757
+ item.channelAcknowledge?.();
546758
+ this.updateQueueDisplay();
546759
+ this.state.ui.requestRender();
546760
+ },
546761
+ error: (error) => {
546762
+ if (current()) this.showError(formatErrorMessage$2(error));
546763
+ },
546764
+ retry: () => {
546765
+ if (current()) this.scheduleQueueDrain();
546766
+ }
546767
+ });
546768
+ }
546769
+ this.activeInputDelivery.request();
546770
+ return true;
546771
+ }
546772
+ releaseChannelQueueAtSafePoint() {
546773
+ if (this.session !== void 0 && (this.stoppedInputSession === this.session || this.stoppedInputScopes?.get(this.session, this.state.queuedMessages[0]?.agentId ?? this.interactiveAgentId) !== void 0)) return;
546774
+ if (this.admitActiveQueuedInputs()) return;
546775
+ this.syncChannelQueueDeadline();
546776
+ if (this.state.appState.isCompacting || this.streamingUI.hasActiveToolCalls() || this.shellOutputStreams.size > 0 || this.state.appState.streamingPhase === "shell") return;
546777
+ if (this.state.appState.streamingPhase === "idle") {
546778
+ this.scheduleQueueDrain();
546779
+ return;
546780
+ }
546781
+ if (this.state.queuedMessages[0]?.mode === "channel") {
546782
+ this.channelQueueDeadline.requestDeliveryAtSafePoint();
546783
+ return;
546784
+ }
546785
+ 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;
546786
+ this.automaticSteerBatch = true;
546787
+ this.queueFlushBatchRemaining = Math.max(1, this.queueFlushBatchRemaining);
546788
+ this.steerQueueFlushPrefix();
545788
546789
  }
545789
546790
  canDrainQueue() {
545790
546791
  if (this.gatewayStartup && !this.gatewayViewReady) return false;
546792
+ if (this.session !== void 0 && this.stoppedInputSession === this.session) return false;
545791
546793
  if (this.queueInterruptCancellations.size > 0) return false;
545792
546794
  const head = this.state.queuedMessages[0];
546795
+ if (this.session !== void 0 && this.stoppedInputScopes?.get(this.session, head?.agentId ?? this.interactiveAgentId) !== void 0) return false;
546796
+ if (this.activeInputDelivery?.has(head)) return false;
546797
+ if (head?.text === "/stop" && head.channelCommandEnvelope !== void 0 && this.activeInputChat !== void 0 && head.channelChatId !== this.activeInputChat) return false;
546798
+ if (head?.text === "/stop" && head.channelCommandEnvelope !== void 0 && this.pendingChannelReplyGuard !== void 0 && head.channelChatId !== this.pendingChannelReplyGuard.chatId) return false;
545793
546799
  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;
545794
546800
  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;
545795
546801
  if ((head?.mode === void 0 || head.mode === "prompt") && this.session !== void 0 && this.queuePolicyBlocksInput(this.session)) return false;
@@ -545797,6 +546803,7 @@ var init_blun_tui = __esmMin((() => {
545797
546803
  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);
545798
546804
  }
545799
546805
  scheduleQueueDrain(minimumDelay = 0) {
546806
+ if (this.admitActiveQueuedInputs()) return;
545800
546807
  if (!this.canDrainQueue()) return;
545801
546808
  if (this.queueDrainTimer !== void 0) {
545802
546809
  if (minimumDelay <= 0) return;
@@ -545898,6 +546905,8 @@ var init_blun_tui = __esmMin((() => {
545898
546905
  const inFlightCount = this.queueSteerInFlight?.items.length ?? 0;
545899
546906
  this.queueFlushBatchRemaining = inFlightCount + this.state.queuedMessages.length;
545900
546907
  if (this.manualPromptInFlight !== void 0) this.manualPromptInFlight.flushRequested = this.queueFlushBatchRemaining > 0;
546908
+ if (this.queueFlushBatchRemaining > 0 && this.state.appState.streamingPhase === "shell")
546909
+ toolLiveness642.yieldLocalShellsForInput(this, true);
545901
546910
  this.steerQueueFlushPrefix();
545902
546911
  this.scheduleQueueDrain();
545903
546912
  }
@@ -545996,6 +547005,8 @@ var init_blun_tui = __esmMin((() => {
545996
547005
  const session = this.session;
545997
547006
  if (session === void 0) return;
545998
547007
  const head = this.state.queuedMessages[0];
547008
+ if (this.activeInputDelivery?.has(head)) return;
547009
+ if (head?.text === "/stop" && head.channelCommandEnvelope !== void 0 && this.pendingChannelReplyGuard !== void 0 && head.channelChatId !== this.pendingChannelReplyGuard.chatId) return;
545999
547010
  if (isExperimentalFlagEnabled("queue_policies") && (head?.mode === void 0 || head.mode === "prompt")) {
546000
547011
  const agentId = head?.agentId ?? this.interactiveAgentId;
546001
547012
  const key = JSON.stringify([session.id, agentId]);
@@ -546109,8 +547120,12 @@ var init_blun_tui = __esmMin((() => {
546109
547120
  channelCommandEnvelope: envelope,
546110
547121
  channelAcknowledge: acknowledge
546111
547122
  };
547123
+ 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)) {
547124
+ this.runChannelCommand(item, envelope);
547125
+ return;
547126
+ }
546112
547127
  const busy = this.state.queuedMessages.length > 0 || this.queueSteerInFlight !== void 0 || this.manualPromptInFlight !== void 0 || this.state.appState.streamingPhase !== "idle" || this.state.appState.isCompacting;
546113
- if (this.session === void 0 || this.deferUserMessages || this.queueCommandRunning || this.localShellConsentRequest !== void 0 || this.editorReplacementActive || busy && !channelCommandCanInterrupt(command)) {
547128
+ 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)) {
546114
547129
  this.state.queuedMessages.push(item);
546115
547130
  this.scheduleQueueDrain();
546116
547131
  this.updateQueueDisplay();
@@ -546121,11 +547136,13 @@ var init_blun_tui = __esmMin((() => {
546121
547136
  injectChannelEnvelope({
546122
547137
  activationMode: () => !isExperimentalFlagEnabled("session_activation") ? void 0 : this.session !== void 0 && this.state.sessionActivation?.sessionId === this.session.id ? this.state.sessionActivation.mode ?? void 0 : "mention",
546123
547138
  canDeliver: () => this.session !== void 0 && this.state.appState.model.trim().length > 0,
546124
- 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,
547139
+ 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,
546125
547140
  deliverNow: (modelInput, displayText, origin, contextOnly) => {
546126
547141
  this.sendChannelMessageInternal(this.requireSession(), modelInput, displayText, origin, envelope.meta.chat_id, envelope.meta["image_path"], contextOnly, false, acknowledge);
546127
547142
  },
546128
547143
  enqueue: (modelInput, displayText, origin, contextOnly) => {
547144
+ const session = this.session;
547145
+ 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);
546129
547146
  this.state.queuedMessages.push({
546130
547147
  text: modelInput,
546131
547148
  displayText,
@@ -546420,6 +547437,7 @@ var init_blun_tui = __esmMin((() => {
546420
547437
  return last;
546421
547438
  }
546422
547439
  enqueueMessage(text, options, mode) {
547440
+ this.stoppedInputSession = void 0;
546423
547441
  const parts = options?.parts === void 0 ? void 0 : structuredClone(options.parts);
546424
547442
  const imageAttachmentIds = options?.imageAttachmentIds?.slice();
546425
547443
  const policy = this.queuePolicyForSession(this.session);
@@ -546460,6 +547478,7 @@ var init_blun_tui = __esmMin((() => {
546460
547478
  mode,
546461
547479
  transcriptRendered: options?.transcriptRendered
546462
547480
  });
547481
+ this.syncChannelQueueDeadline();
546463
547482
  this.track("input_queue");
546464
547483
  }
546465
547484
  enqueueSlashCommand(text) {
@@ -546864,7 +547883,41 @@ var init_blun_tui = __esmMin((() => {
546864
547883
  return this.captureObservedTurnCancellation(session, agentId, turnId);
546865
547884
  }
546866
547885
  async executeSessionStopCommand(args) {
546867
- return this.executeSessionCancellationCommand(args, true);
547886
+ if (!isExperimentalFlagEnabled("queue_policies")) throw new Error("QUEUE_POLICIES_DISABLED");
547887
+ if (args.trim() !== "") throw new Error("STOP_ARGUMENTS_UNSUPPORTED");
547888
+ const session = this.session;
547889
+ if (session === void 0) return;
547890
+ const command = this.channelCommands?.context;
547891
+ if (command?.input === "/stop" && !this.channelOwnsStoppedInput(command.chatId)) return;
547892
+ const previous = this.stoppedInputScopes?.get(session, this.interactiveAgentId);
547893
+ if (command?.input === "/stop" && previous?.boundary !== void 0 && previous.boundary !== "absent") {
547894
+ const fileId = command.envelope.meta["queue_file_id"];
547895
+ const end = command.envelope.meta["queue_end"];
547896
+ if (fileId !== previous.boundary.fileId || end === void 0 || !/^\d+$/.test(end) || !Number.isSafeInteger(Number(end)) || Number(end) <= previous.boundary.frontier) return;
547897
+ }
547898
+ this.stoppedInputSession = session;
547899
+ if (command?.input === "/stop") {
547900
+ const fileId = command.envelope.meta["queue_file_id"];
547901
+ const rawEnd = command.envelope.meta["queue_end"];
547902
+ const end = Number(rawEnd);
547903
+ this.stoppedQueueBoundary = fileId !== void 0 && rawEnd !== void 0 && /^\d+$/.test(rawEnd) && Number.isSafeInteger(end) ? {
547904
+ fileId,
547905
+ frontier: end
547906
+ } : void 0;
547907
+ } else this.stoppedQueueBoundary = this.telegramChannel === void 0 ? void 0 : this.captureTelegramQueueBoundary();
547908
+ this.activeInputDelivery?.cancel();
547909
+ const turn = this.streamingUI.getTurnContext().turnId;
547910
+ if (turn === void 0 || !/^\d+$/.test(turn)) return;
547911
+ const turnId = Number(turn);
547912
+ if (!Number.isSafeInteger(turnId)) throw new Error("ACTIVE_TURN_ID_UNAVAILABLE");
547913
+ const agentId = this.interactiveAgentId;
547914
+ let scope;
547915
+ if (session.connectionKind === "gateway") {
547916
+ const observed = this.gatewayResetTurn;
547917
+ if (agentId !== "main" || observed?.session !== session || observed.turnId !== turnId) throw new Error("RESET_CONTEXT_SCOPE_UNAVAILABLE");
547918
+ scope = observed.scope;
547919
+ }
547920
+ await this.withInteractiveAgent(agentId, () => session.cancelTurn(turnId, scope, true));
546868
547921
  }
546869
547922
  async executeSessionAbortCommand(args) {
546870
547923
  return this.executeSessionCancellationCommand(args, false);
@@ -546982,6 +548035,22 @@ var init_blun_tui = __esmMin((() => {
546982
548035
  this.enqueueMessage(input, options);
546983
548036
  return;
546984
548037
  }
548038
+ if (isExperimentalFlagEnabled("queue_policies") && this.session === session && this.state.appState.streamingPhase !== "idle" && this.state.appState.streamingPhase !== "shell") {
548039
+ this.stoppedInputSession = void 0;
548040
+ this.state.queuedMessages.push({
548041
+ text: input,
548042
+ agentId: this.interactiveAgentId,
548043
+ parts: options?.parts === void 0 ? void 0 : structuredClone(options.parts),
548044
+ imageAttachmentIds: options?.imageAttachmentIds?.slice(),
548045
+ transcriptRendered: options?.transcriptRendered
548046
+ });
548047
+ this.syncChannelQueueDeadline();
548048
+ this.track("input_queue");
548049
+ this.updateQueueDisplay();
548050
+ this.state.ui.requestRender();
548051
+ this.scheduleQueueDrain();
548052
+ return;
548053
+ }
546985
548054
  const policy = this.queuePolicyForSession(session);
546986
548055
  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);
546987
548056
  if (timedSteer) {
@@ -547102,6 +548171,8 @@ var init_blun_tui = __esmMin((() => {
547102
548171
  }
547103
548172
  clearQueuedMessages(preserveCancellations = false) {
547104
548173
  if (!preserveCancellations) this.queueInterruptCancellations.clear();
548174
+ this.activeInputDelivery?.cancel();
548175
+ this.activeInputScope = void 0;
547105
548176
  this.queueSteerInFlight?.receiptAbort?.abort();
547106
548177
  if (this.manualPromptInFlight?.promptAbort !== void 0 && !this.manualPromptInFlight.promptSubmitted && this.state.appState.streamingPhase === "waiting" && !this.streamingUI.hasActiveTurn()) {
547107
548178
  this.setAppState({ streamingPhase: "idle" });
@@ -547483,6 +548554,8 @@ var init_blun_tui = __esmMin((() => {
547483
548554
  this.sessionBindingRequest = void 0;
547484
548555
  const previous = this.session;
547485
548556
  this.queueInterruptCancellations.clear();
548557
+ this.activeInputDelivery?.cancel();
548558
+ this.activeInputScope = void 0;
547486
548559
  this.queueSteerInFlight?.receiptAbort?.abort();
547487
548560
  this.manualPromptInFlight?.promptAbort?.abort();
547488
548561
  this.managedQuotaWarningController.dismiss();
@@ -547569,7 +548642,11 @@ var init_blun_tui = __esmMin((() => {
547569
548642
  this.localShellConsentRequest = void 0;
547570
548643
  if (this.session !== void 0) this.localShellConsent.invalidate(this.session);
547571
548644
  if (!this.preserveQueueAcrossSessionReset) this.queueInterruptCancellations.clear();
547572
- if (!this.preserveQueueAcrossSessionReset) this.queueSteerInFlight?.receiptAbort?.abort();
548645
+ if (!this.preserveQueueAcrossSessionReset) {
548646
+ this.activeInputDelivery?.cancel();
548647
+ this.activeInputScope = void 0;
548648
+ this.queueSteerInFlight?.receiptAbort?.abort();
548649
+ }
547573
548650
  this.manualPromptInFlight?.promptAbort?.abort();
547574
548651
  for (const recovery of this.queueReplayRecoveries.values()) recovery.cancel();
547575
548652
  this.queueReplayRecoveries.clear();
@@ -548475,6 +549552,8 @@ var init_blun_tui = __esmMin((() => {
548475
549552
  return this.state.livePane.mode;
548476
549553
  }
548477
549554
  updateQueueDisplay() {
549555
+ (this.queueDeliveryNudge642 ??= new toolLiveness642.QueueDeliveryNudge(this)).sync();
549556
+ this.syncChannelQueueDeadline();
548478
549557
  this.state.queueContainer.clear();
548479
549558
  const queued = [...this.queueSteerInFlight?.items ?? [], ...this.state.queuedMessages];
548480
549559
  if (queued.length === 0) return;
@@ -548540,9 +549619,8 @@ var init_blun_tui = __esmMin((() => {
548540
549619
  this.showError(uiText("blunTui.detach.moveFailed", { error: formatErrorMessage$2(error) }));
548541
549620
  return;
548542
549621
  }
548543
- stream.component.finishBackgrounded();
548544
- stream.entry.content = uiText("blunTui.detach.movedTranscript");
548545
- this.shellOutputStreams.delete(commandId);
549622
+ toolLiveness642.releaseLocalShell(this, commandId, stream,
549623
+ uiText("blunTui.detach.movedTranscript"));
548546
549624
  this.showDetachHint(uiText("blunTui.detach.movedView"));
548547
549625
  }
548548
549626
  async detachCurrentForegroundTask() {