blun-king-cli 9.1.641 → 9.1.642

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/blun.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- // BLUN_BUILD_INPUT_SHA256:d4df2815be55011d12f15cf3f9b01e9c4c1ba80d84ef9322ad9e8fd20b13e018
2
+ // BLUN_BUILD_INPUT_SHA256:e50c78300e52dc6fc7d8003478fe2fa01fe7fdff8b1a749e108e6627de244e7e
3
3
  /*! wasm-webp 0.1.0
4
4
  MIT License
5
5
 
@@ -21190,6 +21190,7 @@ var init_commands$1 = __esmMin((() => {
21190
21190
  }));
21191
21191
  var init_types$20 = __esmMin((() => {}));
21192
21192
  var FLAG_DEFINITIONS;
21193
+ var InputControl, controls, CHANNEL_QUEUE_DEADLINE_MS, QueueDeadlineWatchdog, StoppedInputScopes, SEARCH_LIMITS, SearchStop, active, inside, sessionSearchRequests, ActiveInputDelivery;
21193
21194
  var init_registry$4 = __esmMin((() => {
21194
21195
  FLAG_DEFINITIONS = [
21195
21196
  {
@@ -21533,7 +21534,7 @@ var init_registry$4 = __esmMin((() => {
21533
21534
  title: "Session queue policies",
21534
21535
  description: "Apply explicitly persisted session queue admission rules.",
21535
21536
  env: "BLUN_EXPERIMENTAL_QUEUE_POLICIES",
21536
- default: false,
21537
+ default: true,
21537
21538
  surface: "core"
21538
21539
  },
21539
21540
  {
@@ -29909,6 +29910,62 @@ var init_task$3 = __esmMin((() => {
29909
29910
  ]);
29910
29911
  }));
29911
29912
  var DenyAllPermissionPolicy;
29913
+ function inputControl(signal) {
29914
+ let control = controls.get(signal);
29915
+ if (control === void 0) {
29916
+ control = new InputControl();
29917
+ controls.set(signal, control);
29918
+ }
29919
+ return control;
29920
+ }
29921
+ function inheritInputControl(signal, control) {
29922
+ if (control !== void 0) controls.set(signal, control);
29923
+ }
29924
+ var init_input_control = __esmMin((() => {
29925
+ init_abort();
29926
+ InputControl = class {
29927
+ epoch = 0;
29928
+ stopped = false;
29929
+ provider;
29930
+ preparations = /* @__PURE__ */ new Set();
29931
+ listeners = /* @__PURE__ */ new Set();
29932
+ onChange(listener) {
29933
+ this.listeners.add(listener);
29934
+ return () => {
29935
+ this.listeners.delete(listener);
29936
+ };
29937
+ }
29938
+ changed(stop = false) {
29939
+ this.epoch++;
29940
+ this.stopped ||= stop;
29941
+ this.provider?.abort(new DOMException("INPUT_SUPERSEDED", "AbortError"));
29942
+ for (const controller of this.preparations) controller.abort(new DOMException("INPUT_SUPERSEDED", "AbortError"));
29943
+ for (const listener of this.listeners) listener();
29944
+ }
29945
+ async prepare(signal, operation) {
29946
+ const controller = new AbortController();
29947
+ this.preparations.add(controller);
29948
+ const preparationSignal = AbortSignal.any([signal, controller.signal]);
29949
+ try {
29950
+ return await abortable(Promise.resolve().then(() => {
29951
+ preparationSignal.throwIfAborted();
29952
+ return operation(preparationSignal);
29953
+ }), preparationSignal);
29954
+ } finally {
29955
+ this.preparations.delete(controller);
29956
+ }
29957
+ }
29958
+ beginProvider() {
29959
+ const controller = new AbortController();
29960
+ this.provider = controller;
29961
+ return controller;
29962
+ }
29963
+ endProvider(controller) {
29964
+ if (this.provider === controller) this.provider = void 0;
29965
+ }
29966
+ };
29967
+ controls = /* @__PURE__ */ new WeakMap();
29968
+ }));
29912
29969
  var init_deny_all = __esmMin((() => {
29913
29970
  DenyAllPermissionPolicy = class {
29914
29971
  message;
@@ -30235,8 +30292,11 @@ var init_persistence$1 = __esmMin((() => {
30235
30292
  this.shouldClear = false;
30236
30293
  const content = (this.options.blobStore !== void 0 ? await Promise.all(batch.map((record) => this.options.blobStore.offload(record))) : batch).map((e) => JSON.stringify(e) + "\n").join("");
30237
30294
  const directory = dirname$3(this.filePath);
30238
- await mkdir(directory, { recursive: true });
30239
- const fh = await open(this.filePath, shouldClear ? "w" : "a");
30295
+ await mkdir(directory, {
30296
+ recursive: true,
30297
+ mode: 448
30298
+ });
30299
+ const fh = await open(this.filePath, shouldClear ? "w" : "a", 384);
30240
30300
  try {
30241
30301
  const before = await fh.stat();
30242
30302
  if (shouldClear || before.size === 0) this.persistedRecordCount = 0;
@@ -183784,10 +183844,17 @@ IMPORTANT:
183784
183844
  - If you do not know the answer, say so directly.
183785
183845
  `;
183786
183846
  nativeExecutionCompletions = /* @__PURE__ */ new WeakMap();
183787
- SessionSubagentHost = class {
183847
+ init_input_control();
183848
+ SessionSubagentHost = class {
183788
183849
  session;
183789
183850
  ownerAgentId;
183790
- admissionClosed = false;
183851
+ inputLeases = /* @__PURE__ */ new WeakMap();
183852
+ assertInputLease(options) {
183853
+ const lease = this.inputLeases.get(options);
183854
+ if (lease?.active?.runInBackground) return;
183855
+ if (lease !== void 0 && (lease.control.stopped || lease.control.epoch !== lease.epoch)) throw new DOMException("INPUT_SUPERSEDED", "AbortError");
183856
+ }
183857
+ admissionClosed = false;
183791
183858
  operations = new ExecutionLedger();
183792
183859
  childExecutions = new ExecutionLedger();
183793
183860
  preparedDisposers = /* @__PURE__ */ new Set();
@@ -183822,8 +183889,16 @@ IMPORTANT:
183822
183889
  assertAdmissionOpen() {
183823
183890
  if (this.admissionClosed) throw new Error("Subagent admission is closed for quiescence");
183824
183891
  }
183825
- runOperation(id, operation) {
183892
+ runOperation(id, operation, input) {
183826
183893
  this.assertAdmissionOpen();
183894
+ if (input !== void 0) {
183895
+ const control = inputControl(input.signal);
183896
+ this.inputLeases.set(input, {
183897
+ control,
183898
+ epoch: control.epoch
183899
+ });
183900
+ this.assertInputLease(input);
183901
+ }
183827
183902
  const completion = operation();
183828
183903
  this.operations.track(id, completion);
183829
183904
  return completion;
@@ -183857,7 +183932,7 @@ IMPORTANT:
183857
183932
  return this.session.getReadyAgent(currentId);
183858
183933
  }
183859
183934
  async spawn(options) {
183860
- return this.runOperation("spawn", () => this.spawnInner(options));
183935
+ return this.runOperation("spawn", () => this.spawnInner(options), options);
183861
183936
  }
183862
183937
  async spawnInner(options) {
183863
183938
  options.signal.throwIfAborted();
@@ -183889,7 +183964,7 @@ IMPORTANT:
183889
183964
  });
183890
183965
  }
183891
183966
  async resume(agentId, options) {
183892
- return this.runOperation("resume", () => this.resumeInner(agentId, options));
183967
+ return this.runOperation("resume", () => this.resumeInner(agentId, options), options);
183893
183968
  }
183894
183969
  async resumeInner(agentId, options) {
183895
183970
  options.signal.throwIfAborted();
@@ -183916,7 +183991,7 @@ IMPORTANT:
183916
183991
  });
183917
183992
  }
183918
183993
  async retry(agentId, options) {
183919
- return this.runOperation("retry", () => this.retryInner(agentId, options));
183994
+ return this.runOperation("retry", () => this.retryInner(agentId, options), options);
183920
183995
  }
183921
183996
  async retryInner(agentId, options) {
183922
183997
  options.signal.throwIfAborted();
@@ -183928,6 +184003,7 @@ IMPORTANT:
183928
184003
  modelAlias: parent.config.modelAlias,
183929
184004
  actionStyle: parent.config.actionStyle
183930
184005
  });
184006
+ this.assertInputLease(runOptions);
183931
184007
  this.emitSubagentStarted(parent, agentId);
183932
184008
  if (child.turn.retry("agent-host") === null) throw new Error(`Agent instance "${agentId}" could not start a retry turn`);
183933
184009
  this.observeFirstRequest(child, runOptions);
@@ -184042,7 +184118,7 @@ IMPORTANT:
184042
184118
  completion,
184043
184119
  update: (message) => this.updateActiveRun(agentId, completion, message)
184044
184120
  });
184045
- })
184121
+ }, options)
184046
184122
  };
184047
184123
  } catch (error) {
184048
184124
  await dispose();
@@ -184130,6 +184206,7 @@ IMPORTANT:
184130
184206
  }
184131
184207
  runWithActiveChild(childId, options, run) {
184132
184208
  this.assertAdmissionOpen();
184209
+ this.assertInputLease(options);
184133
184210
  if (this.activeChildren.has(childId)) throw new Error(`Agent instance "${childId}" is already running`);
184134
184211
  const controller = new AbortController();
184135
184212
  const unlinkAbortSignal = linkAbortSignal(options.signal, controller);
@@ -184138,10 +184215,22 @@ IMPORTANT:
184138
184215
  runInBackground: options.runInBackground
184139
184216
  };
184140
184217
  this.activeChildren.set(childId, active);
184141
- const completion = run({
184218
+ const runOptions = {
184142
184219
  ...options,
184143
184220
  signal: controller.signal
184144
- }).finally(() => {
184221
+ };
184222
+ const lease = this.inputLeases.get(options);
184223
+ if (lease !== void 0) {
184224
+ lease.active = active;
184225
+ this.inputLeases.set(runOptions, lease);
184226
+ }
184227
+ const unlinkInput = lease?.control.onChange(() => {
184228
+ if (active.runInBackground) return;
184229
+ const child = this.session.getReadyAgent(childId);
184230
+ if (child !== void 0) child.turn.stop(child.turn.currentId);
184231
+ });
184232
+ const completion = run(runOptions).finally(() => {
184233
+ unlinkInput?.();
184145
184234
  unlinkAbortSignal();
184146
184235
  if (this.activeChildren.get(childId) === active) this.activeChildren.delete(childId);
184147
184236
  });
@@ -184167,6 +184256,7 @@ IMPORTANT:
184167
184256
  }
184168
184257
  async runPromptTurn(parent, childId, child, profileName, options) {
184169
184258
  options.signal.throwIfAborted();
184259
+ this.assertInputLease(options);
184170
184260
  await this.triggerSubagentStart(parent, profileName, options.prompt, options.signal);
184171
184261
  options.signal.throwIfAborted();
184172
184262
  let childPrompt = options.prompt;
@@ -184174,6 +184264,7 @@ IMPORTANT:
184174
184264
  const gitContext = await collectGitContext(child.kaos, child.config.cwd);
184175
184265
  if (gitContext) childPrompt = `${gitContext}\n\n${childPrompt}`;
184176
184266
  }
184267
+ this.assertInputLease(options);
184177
184268
  this.emitSubagentStarted(parent, childId);
184178
184269
  if (child.turn.prompt([{
184179
184270
  type: "text",
@@ -184189,6 +184280,7 @@ IMPORTANT:
184189
184280
  while (remainingContinuations > 0 && result.length < SUMMARY_MIN_LENGTH) {
184190
184281
  remainingContinuations -= 1;
184191
184282
  options.signal.throwIfAborted();
184283
+ this.assertInputLease(options);
184192
184284
  child.turn.prompt([{
184193
184285
  type: "text",
184194
184286
  text: summary_continuation_default
@@ -248678,6 +248770,11 @@ async function prepareSkippedToolCall(step, call) {
248678
248770
  await dispatchToolCall(step, call, call.args);
248679
248771
  return makeResolvedToolCallTask(makeErrorToolResult(call, call.args, output));
248680
248772
  }
248773
+ function waitForPreparationBoundary(step, operation) {
248774
+ if (step.canStart?.() === false) return Promise.reject(new DOMException("INPUT_SUPERSEDED", "AbortError"));
248775
+ if (step.inputControl === void 0) return waitForToolBoundary(step, () => operation(step.signal));
248776
+ return step.inputControl.prepare(step.signal, (signal) => operation(signal));
248777
+ }
248681
248778
  function waitForToolBoundary(step, operation) {
248682
248779
  if (step.programmaticParentCallId === void 0) return Promise.resolve(operation());
248683
248780
  step.signal.throwIfAborted();
@@ -248705,6 +248802,11 @@ function makeResolvedToolCallTask(result) {
248705
248802
  async function runPrepareToolExecutionHook(step, call) {
248706
248803
  const { hooks, signal, turnId, currentStep, llm } = step;
248707
248804
  const { toolCall, args } = call;
248805
+ if (step.canStart?.() === false) return {
248806
+ kind: "blocked",
248807
+ args,
248808
+ output: "INPUT_SUPERSEDED"
248809
+ };
248708
248810
  const hook = hooks?.prepareToolExecution;
248709
248811
  if (hook === void 0) return {
248710
248812
  kind: "allowed",
@@ -248756,7 +248858,7 @@ async function runAuthorizeToolExecutionHook(step, call, args, execution) {
248756
248858
  const hook = hooks?.authorizeToolExecution;
248757
248859
  if (hook === void 0) return void 0;
248758
248860
  try {
248759
- return await waitForToolBoundary(step, () => hook({
248861
+ return await waitForPreparationBoundary(step, (preparationSignal) => hook({
248760
248862
  toolCall: call.toolCall,
248761
248863
  toolCalls: step.toolCalls,
248762
248864
  tool: call.tool,
@@ -248764,7 +248866,7 @@ async function runAuthorizeToolExecutionHook(step, call, args, execution) {
248764
248866
  execution,
248765
248867
  turnId,
248766
248868
  stepNumber: currentStep,
248767
- signal,
248869
+ signal: preparationSignal,
248768
248870
  llm
248769
248871
  }));
248770
248872
  } catch (error) {
@@ -248818,6 +248920,7 @@ async function runRunnableToolCall(step, call, effectiveArgs, metadata, executio
248818
248920
  function createNestedToolInvoker(step, parent) {
248819
248921
  const controller = new AbortController();
248820
248922
  const parentSignal = AbortSignal.any([step.signal, controller.signal]);
248923
+ inheritInputControl(parentSignal, step.inputControl);
248821
248924
  let accepting = true;
248822
248925
  let stopped = false;
248823
248926
  let sequence = 0;
@@ -248844,6 +248947,7 @@ function createNestedToolInvoker(step, parent) {
248844
248947
  while (reservedIds.has(id));
248845
248948
  reservedIds.add(id);
248846
248949
  const signal = input.signal === void 0 ? parentSignal : AbortSignal.any([parentSignal, input.signal]);
248950
+ inheritInputControl(signal, step.inputControl);
248847
248951
  const run = async () => {
248848
248952
  if (stopped) throw new Error("A nested tool stopped the turn.");
248849
248953
  signal.throwIfAborted();
@@ -248933,6 +249037,10 @@ async function finalizePendingToolResult(step, pendingResult) {
248933
249037
  async function executeTool(step, execution, toolCall, toolName, metadata, invokeTool) {
248934
249038
  const { dispatchEvent, signal, turnId } = step;
248935
249039
  signal.throwIfAborted();
249040
+ if (step.canStart?.() === false) return {
249041
+ output: "INPUT_SUPERSEDED",
249042
+ isError: true
249043
+ };
248936
249044
  const executePromise = execution.execute({
248937
249045
  turnId,
248938
249046
  toolCallId: toolCall.id,
@@ -249082,6 +249190,7 @@ var init_tool_call$1 = __esmMin((() => {
249082
249190
  init_path_access();
249083
249191
  init_abort();
249084
249192
  init_errors$5();
249193
+ init_input_control();
249085
249194
  init_execution_observer();
249086
249195
  init_tool_args_parse();
249087
249196
  init_tool_access();
@@ -249101,6 +249210,8 @@ var init_tool_call$1 = __esmMin((() => {
249101
249210
  */
249102
249211
  async function executeLoopStep(deps) {
249103
249212
  const { turnId, signal, buildMessages, buildMessagesStrict, dispatchEvent, llm, tools, hooks, executionObserver, log, currentStep, maxRetryAttempts, checkpointBeforeRetry, recordUsage, onStepStarted } = deps;
249213
+ const control = inputControl(signal);
249214
+ const inputEpoch = control.epoch;
249104
249215
  if (hooks?.beforeStep !== void 0) {
249105
249216
  const beforeStep = await hooks.beforeStep({
249106
249217
  turnId,
@@ -249119,10 +249230,13 @@ async function executeLoopStep(deps) {
249119
249230
  turnId,
249120
249231
  currentStep,
249121
249232
  stepUuid,
249122
- onStepStarted
249233
+ onStepStarted,
249234
+ acceptOutput: () => !control.stopped && control.epoch === inputEpoch
249123
249235
  });
249124
249236
  const prepareRequestBoundary = llm.prepareRequestBoundary?.bind(llm);
249125
249237
  const step = {
249238
+ inputControl: control,
249239
+ canStart: () => !control.stopped && control.epoch === inputEpoch,
249126
249240
  tools,
249127
249241
  hooks,
249128
249242
  executionObserver,
@@ -249138,6 +249252,7 @@ async function executeLoopStep(deps) {
249138
249252
  messages,
249139
249253
  tools: tools ?? [],
249140
249254
  signal,
249255
+ boundarySignal: signal,
249141
249256
  ...stepEvents.callbacks
249142
249257
  };
249143
249258
  if (prepareRequestBoundary === void 0) await stepEvents.start();
@@ -249187,6 +249302,12 @@ async function executeLoopStep(deps) {
249187
249302
  log
249188
249303
  };
249189
249304
  let response;
249305
+ const provider = control.beginProvider();
249306
+ chatParams = {
249307
+ ...chatParams,
249308
+ signal: AbortSignal.any([signal, provider.signal])
249309
+ };
249310
+ if (control.stopped || control.epoch !== inputEpoch) provider.abort();
249190
249311
  try {
249191
249312
  response = await chatWithRetry({
249192
249313
  ...retryInput,
@@ -249194,35 +249315,50 @@ async function executeLoopStep(deps) {
249194
249315
  });
249195
249316
  } catch (error) {
249196
249317
  await stepEvents.drain();
249197
- if (buildMessagesStrict === void 0 || !isRecoverableRequestStructureError(error) || prepareRequestBoundary !== void 0 && stepEvents.hasOutput) throw error;
249198
- signal.throwIfAborted();
249199
- log?.warn("provider rejected request structure; resending with strict projection", {
249200
- turnStep: `${turnId}.${String(currentStep)}`,
249201
- model: llm.modelName
249202
- });
249203
- const strictMessages = await buildMessagesStrict();
249204
- signal.throwIfAborted();
249205
- let strictParams = {
249206
- ...chatParams,
249207
- messages: strictMessages
249318
+ if (provider.signal.aborted && !signal.aborted) response = {
249319
+ toolCalls: [],
249320
+ usage: emptyUsage()
249208
249321
  };
249209
- if (prepareRequestBoundary !== void 0) strictParams = await prepareRequestBoundary(strictParams, buildMessagesStrict);
249210
- signal.throwIfAborted();
249211
- try {
249212
- response = await chatWithRetry({
249213
- ...retryInput,
249214
- params: strictParams
249215
- });
249216
- } catch (strictError) {
249217
- log?.error("strict resend still rejected by provider; request remains wire-invalid", {
249322
+ else if (buildMessagesStrict === void 0 || !isRecoverableRequestStructureError(error) || prepareRequestBoundary !== void 0 && stepEvents.hasOutput) throw error;
249323
+ else try {
249324
+ signal.throwIfAborted();
249325
+ log?.warn("provider rejected request structure; resending with strict projection", {
249218
249326
  turnStep: `${turnId}.${String(currentStep)}`,
249219
- model: llm.modelName,
249220
- originalError: errorMessage$13(error),
249221
- strictError: errorMessage$13(strictError)
249327
+ model: llm.modelName
249222
249328
  });
249223
- throw strictError;
249329
+ const strictMessages = await buildMessagesStrict();
249330
+ signal.throwIfAborted();
249331
+ let strictParams = {
249332
+ ...chatParams,
249333
+ messages: strictMessages
249334
+ };
249335
+ if (prepareRequestBoundary !== void 0) strictParams = await prepareRequestBoundary(strictParams, buildMessagesStrict);
249336
+ signal.throwIfAborted();
249337
+ try {
249338
+ response = await chatWithRetry({
249339
+ ...retryInput,
249340
+ params: strictParams
249341
+ });
249342
+ } catch (strictError) {
249343
+ if (provider.signal.aborted) throw strictError;
249344
+ log?.error("strict resend still rejected by provider; request remains wire-invalid", {
249345
+ turnStep: `${turnId}.${String(currentStep)}`,
249346
+ model: llm.modelName,
249347
+ originalError: errorMessage$13(error),
249348
+ strictError: errorMessage$13(strictError)
249349
+ });
249350
+ throw strictError;
249351
+ }
249352
+ log?.info("recovered after strict resend", { turnStep: `${turnId}.${String(currentStep)}` });
249353
+ } catch (strictBoundaryError) {
249354
+ if (!provider.signal.aborted || signal.aborted) throw strictBoundaryError;
249355
+ response = {
249356
+ toolCalls: [],
249357
+ usage: emptyUsage()
249358
+ };
249224
249359
  }
249225
- log?.info("recovered after strict resend", { turnStep: `${turnId}.${String(currentStep)}` });
249360
+ } finally {
249361
+ control.endProvider(provider);
249226
249362
  }
249227
249363
  await stepEvents.start();
249228
249364
  await stepEvents.drain();
@@ -249233,6 +249369,7 @@ async function executeLoopStep(deps) {
249233
249369
  if (effectiveStopReason === "tool_use") {
249234
249370
  if ((await runToolCallBatch(step, response)).stopTurn) effectiveStopReason = "end_turn";
249235
249371
  }
249372
+ if (control.epoch !== inputEpoch) effectiveStopReason = control.stopped ? "end_turn" : "tool_use";
249236
249373
  signal.throwIfAborted();
249237
249374
  await dispatchEvent({
249238
249375
  type: "step.end",
@@ -249343,8 +249480,10 @@ function createStepEventGate(deps) {
249343
249480
  return startPromise;
249344
249481
  };
249345
249482
  const enqueue = (dispatch) => {
249483
+ if (!deps.acceptOutput()) return Promise.resolve();
249346
249484
  hasOutput = true;
249347
249485
  const queued = eventQueue.then(async () => {
249486
+ if (!deps.acceptOutput()) return;
249348
249487
  await start();
249349
249488
  await dispatch();
249350
249489
  });
@@ -249427,6 +249566,7 @@ function createStepEventGate(deps) {
249427
249566
  }
249428
249567
  var init_turn_step = __esmMin((() => {
249429
249568
  init_src$8();
249569
+ init_input_control();
249430
249570
  init_errors$5();
249431
249571
  init_execution_observer();
249432
249572
  init_retry();
@@ -249449,6 +249589,10 @@ async function runTurn(input) {
249449
249589
  try {
249450
249590
  while (true) {
249451
249591
  signal.throwIfAborted();
249592
+ if (inputControl(signal).stopped) {
249593
+ stopReason = "aborted";
249594
+ break;
249595
+ }
249452
249596
  if (maxSteps !== void 0 && maxSteps > 0 && steps >= maxSteps) throw createMaxStepsExceededError(maxSteps);
249453
249597
  steps += 1;
249454
249598
  const stepNumber = steps;
@@ -249470,6 +249614,10 @@ async function runTurn(input) {
249470
249614
  onStepStarted: setActiveStep.bind(void 0, stepNumber)
249471
249615
  });
249472
249616
  activeStep = void 0;
249617
+ if (inputControl(signal).stopped) {
249618
+ stopReason = "aborted";
249619
+ break;
249620
+ }
249473
249621
  if (stepResult.stopReason === "tool_use") continue;
249474
249622
  const terminalStopReason = stepResult.stopReason;
249475
249623
  stopReason = terminalStopReason;
@@ -249513,6 +249661,7 @@ var init_run_turn = __esmMin((() => {
249513
249661
  init_src$8();
249514
249662
  init_errors$5();
249515
249663
  init_turn_step();
249664
+ init_input_control();
249516
249665
  }));
249517
249666
  var init_loop$1 = __esmMin((() => {
249518
249667
  init_tool_access();
@@ -250173,7 +250322,8 @@ var init_prompt$1 = __esmMin((() => {
250173
250322
  sessionAdmissionSteerRequestSchema = admissionReadIdentitySchema.omit({ timeout_ms: true }).extend({ expected_turn_id: admissionTurnSchema });
250174
250323
  sessionAdmissionCancelRequestSchema = object$1({
250175
250324
  scope: admissionIdentitySchema,
250176
- turn_id: admissionTurnSchema
250325
+ turn_id: admissionTurnSchema,
250326
+ graceful: boolean$1().optional()
250177
250327
  }).strict();
250178
250328
  sessionAdmissionCancelResponseSchema = sessionAdmissionCancelRequestSchema.extend({
250179
250329
  session_id: string().min(1),
@@ -265881,7 +266031,8 @@ var init_turn = __esmMin((() => {
265881
266031
  "Otherwise keep going — use the existing conversation context and your tools,",
265882
266032
  "and do not ask the user for input unless a real blocker prevents progress."
265883
266033
  ].join(" ");
265884
- TurnFlow = class {
266034
+ init_input_control();
266035
+ TurnFlow = class {
265885
266036
  agent;
265886
266037
  admissionClosed = false;
265887
266038
  loadedToolNames = /* @__PURE__ */ new Set();
@@ -265958,6 +266109,7 @@ var init_turn = __esmMin((() => {
265958
266109
  if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 2147483647) throw new Error("INVALID_PROMPT_TIMEOUT");
265959
266110
  }
265960
266111
  this.assertAdmissionOpen();
266112
+ this.stopRequested = false;
265961
266113
  this.agent.records.logRecord({
265962
266114
  type: "turn.prompt",
265963
266115
  input,
@@ -265974,6 +266126,7 @@ var init_turn = __esmMin((() => {
265974
266126
  }
265975
266127
  steer(input, origin = USER_PROMPT_ORIGIN) {
265976
266128
  this.assertAdmissionOpen();
266129
+ this.stopRequested = false;
265977
266130
  this.agent.records.logRecord({
265978
266131
  type: "turn.steer",
265979
266132
  input,
@@ -265987,7 +266140,7 @@ var init_turn = __esmMin((() => {
265987
266140
  }
265988
266141
  /** Buffer only into the currently active turn; never launch from an idle state. */
265989
266142
  steerActive(input, expectedTurnId, origin = USER_PROMPT_ORIGIN, onDisposition) {
265990
- if (this.admissionClosed) return null;
266143
+ if (this.admissionClosed || this.stopRequested) return null;
265991
266144
  const active = this.activeTurn;
265992
266145
  if (active === null || active === "resuming" || !active.acceptingSteers || expectedTurnId !== void 0 && expectedTurnId !== this.currentId) return null;
265993
266146
  this.agent.records.logRecord({
@@ -266078,7 +266231,19 @@ var init_turn = __esmMin((() => {
266078
266231
  this.turnId += 1;
266079
266232
  this.activeTurn = "resuming";
266080
266233
  }
266081
- cancel(turnId, reason) {
266234
+ stopRequested = false;
266235
+ stop(turnId) {
266236
+ const active = this.activeTurn;
266237
+ if (turnId !== this.currentId) return;
266238
+ this.stopRequested = true;
266239
+ if (active === null || active === "resuming") return;
266240
+ this.agent.records.logRecord({
266241
+ type: "turn.cancel",
266242
+ turnId
266243
+ });
266244
+ inputControl(active.controller.signal).changed(true);
266245
+ }
266246
+ cancel(turnId, reason) {
266082
266247
  this.agent.records.logRecord({
266083
266248
  type: "turn.cancel",
266084
266249
  turnId
@@ -266149,6 +266314,8 @@ var init_turn = __esmMin((() => {
266149
266314
  timeoutMs
266150
266315
  });
266151
266316
  this.nextSteerSequence += 1;
266317
+ const active = this.activeTurn;
266318
+ if (origin.kind !== "background_task" && active !== null && active !== "resuming") inputControl(active.controller.signal).changed();
266152
266319
  }
266153
266320
  flushSteerBuffer(turnId = this.currentId, throughSequence = Number.POSITIVE_INFINITY) {
266154
266321
  if (this.steerBuffer.length === 0) return false;
@@ -266209,7 +266376,7 @@ var init_turn = __esmMin((() => {
266209
266376
  * draining into it via `flushSteerBuffer`.
266210
266377
  */
266211
266378
  onCompactionFinished() {
266212
- if (this.admissionClosed) return;
266379
+ if (this.admissionClosed || this.stopRequested) return;
266213
266380
  if (this.steerBuffer.length === 0) return;
266214
266381
  if (this.activeTurn !== null) return;
266215
266382
  const next = this.steerBuffer.shift();
@@ -266238,7 +266405,7 @@ var init_turn = __esmMin((() => {
266238
266405
  try {
266239
266406
  if (this.agent.goal.getGoal().goal?.status === "active") return finish(await this.driveGoal(firstTurnId, input, origin, signal));
266240
266407
  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(), [{
266408
+ if (this.agent.goal.getGoal().goal?.status === "active" && !inputControl(signal).stopped && end.event.reason !== "cancelled" && end.event.reason !== "failed" && end.event.reason !== "filtered") return finish(await this.driveGoal(this.allocateTurnId(), [{
266242
266409
  type: "text",
266243
266410
  text: GOAL_CONTINUATION_PROMPT
266244
266411
  }], goalContinuationOrigin(origin), signal));
@@ -266276,6 +266443,11 @@ var init_turn = __esmMin((() => {
266276
266443
  let turnInput = input;
266277
266444
  let turnOrigin = origin;
266278
266445
  while (true) {
266446
+ if (inputControl(signal).stopped) return { event: {
266447
+ type: "turn.ended",
266448
+ turnId,
266449
+ reason: "cancelled"
266450
+ } };
266279
266451
  const goalBeforeTurn = this.agent.goal.getGoal().goal;
266280
266452
  if (goalBeforeTurn?.status === "active" && goalBeforeTurn.budget.overBudget) {
266281
266453
  await this.agent.goal.markBlocked({ reason: "A configured budget was reached" });
@@ -266365,7 +266537,13 @@ var init_turn = __esmMin((() => {
266365
266537
  let completedResponse;
266366
266538
  let errorEvent;
266367
266539
  try {
266540
+ const checkStop = () => {
266541
+ signal.throwIfAborted();
266542
+ if (inputControl(signal).stopped) throw new DOMException("INPUT_STOPPED", "AbortError");
266543
+ };
266544
+ checkStop();
266368
266545
  const promptHookEnded = await this.applyUserPromptHook(turnId, input, origin, signal, startedAt);
266546
+ checkStop();
266369
266547
  if (promptHookEnded !== void 0) {
266370
266548
  ended = promptHookEnded.event;
266371
266549
  blockedByUserPromptHook = promptHookEnded.blocked;
@@ -266384,6 +266562,7 @@ var init_turn = __esmMin((() => {
266384
266562
  this.agent.log.warn("Turn-start observation failed");
266385
266563
  }
266386
266564
  signal.throwIfAborted();
266565
+ checkStop();
266387
266566
  const stopReason = await this.runStepLoop(turnId, signal, input, origin, (response) => {
266388
266567
  completedResponse = response;
266389
266568
  });
@@ -266636,7 +266815,7 @@ var init_turn = __esmMin((() => {
266636
266815
  },
266637
266816
  settleStep: async ({ signal: stepSignal }) => {
266638
266817
  if (stopForGoalBudget) this.setActiveSteerAcceptance(turnId, false);
266639
- await this.agent.fullCompaction.afterStep(stepSignal);
266818
+ if (!inputControl(stepSignal).stopped) await this.agent.fullCompaction.afterStep(stepSignal);
266640
266819
  },
266641
266820
  afterStep: async () => {
266642
266821
  deduper.endStep();
@@ -270664,7 +270843,7 @@ var init_agent = __esmMin((() => {
270664
270843
  messages: await rebuildMessages()
270665
270844
  };
270666
270845
  let systemPrompt = this.effectiveSystemPrompt;
270667
- const compacted = await this.fullCompaction.beforeStep(params.signal, {
270846
+ const compacted = await this.fullCompaction.beforeStep(params.boundarySignal ?? params.signal, {
270668
270847
  messages: params.messages,
270669
270848
  additionalMessages: steers.messages,
270670
270849
  rebuildMessages,
@@ -270829,6 +271008,12 @@ var init_agent = __esmMin((() => {
270829
271008
  };
270830
271009
  },
270831
271010
  cancel: (payload) => {
271011
+ if (payload.graceful === true) {
271012
+ if (payload.turnId === void 0) throw new Error("STOP_TURN_REQUIRED");
271013
+ if (payload.turnId !== this.turn.currentId) return;
271014
+ this.turn.stop(payload.turnId);
271015
+ return Promise.all([this.turn.waitForExecutionEnd(), this.fullCompaction.waitForExecutionEnd()]).then(() => void 0);
271016
+ }
270832
271017
  const waitForExecution = this.experimentalFlags.enabled("queue_policies") && payload.turnId !== void 0 && payload.turnId === this.turn.currentId;
270833
271018
  if (this.turn.hasActiveTurn) this.telemetry.track("cancel", { from: "streaming" });
270834
271019
  this.turn.cancel(payload.turnId, payload.cancellationReason === "timeout" ? new DOMException("Prompt execution timed out", "TimeoutError") : void 0);
@@ -337000,7 +337185,10 @@ async function appendSessionIndexEntry(homeDir, entry) {
337000
337185
  recursive: true,
337001
337186
  mode: 448
337002
337187
  });
337003
- await appendFile(indexPath, `${JSON.stringify(entry)}\n`, "utf-8");
337188
+ await appendFile(indexPath, `${JSON.stringify(entry)}\n`, {
337189
+ encoding: "utf-8",
337190
+ mode: 384
337191
+ });
337004
337192
  }
337005
337193
  async function readSessionIndex$1(homeDir, sessionsDir) {
337006
337194
  let raw;
@@ -346253,12 +346441,14 @@ var init_sessionService = __esmMin((() => {
346253
346441
  sessionId: id,
346254
346442
  agentId: "main",
346255
346443
  expectedScope: request.scope,
346256
- turnId: request.turn_id
346444
+ turnId: request.turn_id,
346445
+ graceful: request.graceful
346257
346446
  });
346258
346447
  return {
346259
346448
  session_id: id,
346260
346449
  scope: request.scope,
346261
346450
  turn_id: request.turn_id,
346451
+ graceful: request.graceful,
346262
346452
  settled: true
346263
346453
  };
346264
346454
  }
@@ -349409,13 +349599,14 @@ var init_session$1 = __esmMin((() => {
349409
349599
  this.ensureOpen();
349410
349600
  await this.trackLocalInputRequest(() => this.rpc.cancel({ sessionId: this.id }));
349411
349601
  }
349412
- async cancelTurn(turnId, expectedScope) {
349602
+ async cancelTurn(turnId, expectedScope, graceful) {
349413
349603
  this.ensureOpen();
349414
349604
  if (!Number.isSafeInteger(turnId) || turnId < 0) throw new Error("INVALID_TURN_ID");
349415
349605
  await this.trackLocalInputRequest(() => this.rpc.cancelTurn({
349416
349606
  sessionId: this.id,
349417
349607
  turnId,
349418
- expectedScope
349608
+ expectedScope,
349609
+ graceful
349419
349610
  }));
349420
349611
  }
349421
349612
  async setModel(model, options) {
@@ -350847,7 +351038,8 @@ var init_rpc = __esmMin((() => {
350847
351038
  sessionId: input.sessionId,
350848
351039
  agentId,
350849
351040
  turnId: input.turnId,
350850
- expectedScope: input.expectedScope
351041
+ expectedScope: input.expectedScope,
351042
+ graceful: input.graceful
350851
351043
  });
350852
351044
  }
350853
351045
  async registerTool(input) {
@@ -353012,7 +353204,7 @@ var init_gateway_session_client = __esmMin((() => {
353012
353204
  if ((await this.metadata(owner)).capabilities.admission_cancel !== true) throw new GatewayCommandError("GATEWAY_CAPABILITY_UNAVAILABLE");
353013
353205
  owner?.throwIfAborted();
353014
353206
  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");
353207
+ if (response.session_id !== sessionId || response.scope !== request.scope || response.turn_id !== request.turn_id || response.graceful !== request.graceful) throw new GatewayCommandError("GATEWAY_COMMAND_OUTCOME_UNKNOWN");
353016
353208
  return response;
353017
353209
  }
353018
353210
  async steerWithReceipt(sessionId, input, owner) {
@@ -353447,7 +353639,8 @@ var init_gateway_session_rpc = __esmMin((() => {
353447
353639
  if (this.interactiveAgentId !== "main" || !input.expectedScope) throw new GatewayRpcError("GATEWAY_RPC_CAPABILITY_UNAVAILABLE");
353448
353640
  await this.client.cancelAdmissionTurn(this.sessionId, {
353449
353641
  scope: input.expectedScope,
353450
- turn_id: input.turnId
353642
+ turn_id: input.turnId,
353643
+ graceful: input.graceful
353451
353644
  }, this.lifetime.signal);
353452
353645
  this.assertScope(input);
353453
353646
  if (this.interactiveAgentId !== "main") throw new GatewayRpcError("GATEWAY_RPC_CAPABILITY_UNAVAILABLE");
@@ -368431,7 +368624,7 @@ function optionalBuildString(value) {
368431
368624
  var BLUN_BUILD_INFO;
368432
368625
  var init_build_info = __esmMin((() => {
368433
368626
  BLUN_BUILD_INFO = {
368434
- version: optionalBuildString("9.1.640"),
368627
+ version: optionalBuildString("9.1.642"),
368435
368628
  channel: typeof __BLUN_CHANNEL__ === "string" ? optionalBuildString(__BLUN_CHANNEL__) : void 0,
368436
368629
  commit: typeof __BLUN_COMMIT__ === "string" ? optionalBuildString(__BLUN_COMMIT__) : void 0,
368437
368630
  buildTarget: typeof __BLUN_BUILD_TARGET__ === "string" ? optionalBuildString(__BLUN_BUILD_TARGET__) : void 0
@@ -491743,6 +491936,117 @@ var init_rendering = __esmMin((() => {
491743
491936
  THINKING_WORD_INTERVAL_MS = 3e3;
491744
491937
  }));
491745
491938
  /** The caller supplies the authoritative, workspace-scoped inventory. */
491939
+ var init_channel_queue = __esmMin((() => {
491940
+ CHANNEL_QUEUE_DEADLINE_MS = 3e4;
491941
+ }));
491942
+ var init_queue_deadline_watchdog = __esmMin((() => {
491943
+ init_channel_queue();
491944
+ QueueDeadlineWatchdog = class {
491945
+ snapshot;
491946
+ onStatus;
491947
+ now;
491948
+ owner;
491949
+ observed = /* @__PURE__ */ new WeakMap();
491950
+ statusHead;
491951
+ status;
491952
+ timer;
491953
+ disposed = false;
491954
+ generation = 0;
491955
+ constructor(snapshot, onStatus, now = () => performance.now()) {
491956
+ this.snapshot = snapshot;
491957
+ this.onStatus = onStatus;
491958
+ this.now = now;
491959
+ }
491960
+ /** Steer restoration may copy an entry; keep its original monotonic age. */
491961
+ transfer(from, to) {
491962
+ const started = this.observed.get(from);
491963
+ if (started !== void 0) this.observed.set(to, started);
491964
+ if (this.statusHead === from) this.statusHead = to;
491965
+ }
491966
+ sync() {
491967
+ if (this.disposed) return;
491968
+ this.clearTimer();
491969
+ const snapshot = this.snapshot();
491970
+ if (snapshot.owner !== this.owner) {
491971
+ this.owner = snapshot.owner;
491972
+ this.observed = /* @__PURE__ */ new WeakMap();
491973
+ this.statusHead = void 0;
491974
+ this.publish(void 0);
491975
+ }
491976
+ const now = this.now();
491977
+ for (const entry of snapshot.entries) if (!this.observed.has(entry)) this.observed.set(entry, now);
491978
+ const head = snapshot.entries[0];
491979
+ if (head === void 0) {
491980
+ this.publish(void 0);
491981
+ return;
491982
+ }
491983
+ const elapsedMs = Math.max(0, now - this.observed.get(head));
491984
+ if (elapsedMs >= 3e4) {
491985
+ const status = {
491986
+ code: "QUEUE_DEADLINE_EXCEEDED",
491987
+ deadlineMs: CHANNEL_QUEUE_DEADLINE_MS,
491988
+ elapsedMs,
491989
+ reason: snapshot.reason
491990
+ };
491991
+ this.publish(status, head);
491992
+ return;
491993
+ }
491994
+ this.publish(void 0);
491995
+ const generation = this.generation;
491996
+ this.timer = setTimeout(() => {
491997
+ if (this.disposed || generation !== this.generation) return;
491998
+ this.timer = void 0;
491999
+ this.sync();
492000
+ }, CHANNEL_QUEUE_DEADLINE_MS - elapsedMs);
492001
+ this.timer.unref?.();
492002
+ }
492003
+ dispose() {
492004
+ this.disposed = true;
492005
+ this.clearTimer();
492006
+ this.publish(void 0);
492007
+ }
492008
+ publish(status, head) {
492009
+ if (this.statusHead === head && this.status?.reason === status?.reason && this.status === void 0 === (status === void 0)) return;
492010
+ this.statusHead = head;
492011
+ this.status = status;
492012
+ this.onStatus(status);
492013
+ }
492014
+ clearTimer() {
492015
+ this.generation += 1;
492016
+ if (this.timer !== void 0) clearTimeout(this.timer);
492017
+ this.timer = void 0;
492018
+ }
492019
+ };
492020
+ }));
492021
+ var init_stopped_input_scopes = __esmMin((() => {
492022
+ StoppedInputScopes = class {
492023
+ owners = /* @__PURE__ */ new WeakMap();
492024
+ stop(owner, scope) {
492025
+ let agents = this.owners.get(owner);
492026
+ if (agents === void 0) {
492027
+ agents = /* @__PURE__ */ new Map();
492028
+ this.owners.set(owner, agents);
492029
+ }
492030
+ agents.set(scope.agentId, scope);
492031
+ }
492032
+ get(owner, agentId) {
492033
+ const scope = this.owners.get(owner)?.get(agentId);
492034
+ return scope?.sessionId === owner.id ? scope : void 0;
492035
+ }
492036
+ clear(owner, agentId, expected = this.get(owner, agentId)) {
492037
+ if (expected !== void 0 && this.get(owner, agentId) === expected) this.owners.get(owner)?.delete(agentId);
492038
+ }
492039
+ resumeChannel(owner, agentId, envelope, turnId, runtimeScope) {
492040
+ const scope = this.get(owner, agentId);
492041
+ if (scope === void 0) return false;
492042
+ const boundary = scope.boundary;
492043
+ const start = envelope.meta["queue_start"];
492044
+ if (scope.chatId === void 0 || scope.chatId !== envelope.meta.chat_id || envelope.meta["control_authorized"] !== "true" || !/^\d+$/.test(envelope.meta["user_id"] ?? "") || !/^-?\d+$/.test(envelope.meta.chat_id) || !["true", "1"].includes(envelope.meta["addressed"] ?? "") || turnId !== void 0 && scope.turnId !== turnId || runtimeScope !== scope.runtimeScope || boundary === void 0 || boundary === "absent" || envelope.meta["queue_file_id"] !== boundary.fileId || start === void 0 || !/^\d+$/.test(start) || !Number.isSafeInteger(Number(start)) || Number(start) < boundary.frontier) return false;
492045
+ this.clear(owner, agentId, scope);
492046
+ return true;
492047
+ }
492048
+ };
492049
+ }));
491746
492050
  function resolveSessionReference(sessions, reference) {
491747
492051
  const value = reference.trim();
491748
492052
  if (value.length === 0) return { kind: "missing" };
@@ -492172,9 +492476,10 @@ var init_queue_prompt_delivery = __esmMin((() => {
492172
492476
  init_queue_overflow_delivery();
492173
492477
  }));
492174
492478
  /** Resolves only from request-specific evidence, never from UI step/turn events. */
492175
- async function deliverQueueSteer(sender, input, expectedTurnId, signal, onAccepted) {
492479
+ async function deliverQueueSteer(sender, input, expectedTurnId, signal, onAccepted, state) {
492176
492480
  if (!Number.isSafeInteger(expectedTurnId) || expectedTurnId < 0) throw new Error("INVALID_STEER_RECEIPT_TURN");
492177
- const payload = structuredClone(input);
492481
+ const payload = state?.payload ?? structuredClone(input);
492482
+ if (state !== void 0) state.payload = payload;
492178
492483
  const check = () => {
492179
492484
  if (signal.aborted) throw new Error("QUEUE_STEER_CANCELLED");
492180
492485
  };
@@ -492188,7 +492493,8 @@ async function deliverQueueSteer(sender, input, expectedTurnId, signal, onAccept
492188
492493
  check();
492189
492494
  };
492190
492495
  if (typeof sender.getPromptAdmissionScope !== "function" || typeof sender.steerActiveWithReceipt !== "function" || typeof sender.getSteerAdmissionReceipt !== "function") throw new Error("STEER_RECEIPTS_UNAVAILABLE");
492191
- let identity;
492496
+ let identity = state?.identity;
492497
+ const resuming = identity !== void 0;
492192
492498
  while (identity === void 0) {
492193
492499
  check();
492194
492500
  try {
@@ -492199,19 +492505,22 @@ async function deliverQueueSteer(sender, input, expectedTurnId, signal, onAccept
492199
492505
  requestId: randomUUID(),
492200
492506
  expectedTurnId
492201
492507
  };
492508
+ if (state !== void 0) state.identity = identity;
492202
492509
  } catch (error) {
492203
492510
  check();
492204
492511
  if (isPromptAdmissionProtocolFailure(error)) throw error;
492205
492512
  await wait();
492206
492513
  }
492207
492514
  }
492208
- let submit = true;
492515
+ let submit = !resuming;
492209
492516
  let accepted = false;
492210
492517
  const markAccepted = () => {
492211
492518
  if (accepted) return;
492212
492519
  accepted = true;
492520
+ if (state !== void 0) state.accepted = true;
492213
492521
  onAccepted?.();
492214
492522
  };
492523
+ if (state?.accepted) markAccepted();
492215
492524
  for (;;) {
492216
492525
  check();
492217
492526
  if (submit) {
@@ -499549,6 +499858,12 @@ var init_telegram_channel_copy = __esmMin((() => {
499549
499858
  });
499550
499859
  }));
499551
499860
  var SESSION_QUEUE_READ_BYTES;
499861
+ function isChannelStop(envelope) {
499862
+ if (envelope.meta["control_authorized"] !== "true" || !/^\d+$/.test(envelope.meta["user_id"] ?? "") || !/^-?\d+$/.test(envelope.meta.chat_id) || !["true", "1"].includes(envelope.meta["addressed"] ?? "")) return false;
499863
+ const match = /^\/stop(?:@([A-Za-z0-9_]+))?$/i.exec(envelope.text.trim());
499864
+ return match !== null && (match[1] === void 0 || match[1].toLowerCase() === envelope.meta["bot_username"]?.toLowerCase());
499865
+ }
499866
+ var init_channel_control = __esmMin((() => {}));
499552
499867
  var init_telegram_session_queue$1 = __esmMin((() => {
499553
499868
  SESSION_QUEUE_READ_BYTES = 65536;
499554
499869
  }));
@@ -499803,11 +500118,13 @@ var init_telegram_session_queue_delivery = __esmMin((() => {
499803
500118
  init_channel_injection();
499804
500119
  init_telegram_session_queue();
499805
500120
  init_telegram_session_queue_store();
499806
- SessionQueueDelivery = class {
500121
+ init_channel_control();
500122
+ SessionQueueDelivery = class {
499807
500123
  host;
499808
500124
  boundSessionId;
499809
500125
  inFlight = /* @__PURE__ */ new Set();
499810
- queueFile;
500126
+ controlsInFlight = /* @__PURE__ */ new Set();
500127
+ queueFile;
499811
500128
  stateFile;
499812
500129
  constructor(dir, host) {
499813
500130
  this.host = host;
@@ -499842,15 +500159,41 @@ var init_telegram_session_queue_delivery = __esmMin((() => {
499842
500159
  if (state === void 0) throw new Error("Telegram session queue checkpoint is missing");
499843
500160
  state = observeSessionQueue(state, position);
499844
500161
  if (JSON.stringify(state) !== before) writeSessionQueue(this.stateFile, state);
499845
- if (rebind) this.inFlight.clear();
500162
+ if (rebind) {
500163
+ this.inFlight.clear();
500164
+ this.controlsInFlight.clear();
500165
+ }
499846
500166
  this.boundSessionId = scope.sessionId;
499847
500167
  if (!deliver) return;
499848
- if (this.inFlight.size >= 16) return;
500168
+ for (const pending of pendingSessionQueue(state, scope.sessionId)) for (const line of readLines(this.queueFile, pending)) {
500169
+ if (!this.host.ownsChannel() || this.host.currentSessionId() !== scope.sessionId) return;
500170
+ const envelope = parseChannelEnvelope(line.text);
500171
+ if (envelope === void 0 || !isChannelStop(envelope)) continue;
500172
+ const key = `${line.range.fileId}:${line.range.start}:${line.range.end}`;
500173
+ if (this.controlsInFlight.has(key)) continue;
500174
+ this.controlsInFlight.add(key);
500175
+ const scopedEnvelope = {
500176
+ ...envelope,
500177
+ meta: {
500178
+ ...envelope.meta,
500179
+ queue_file_id: line.range.fileId,
500180
+ queue_start: String(line.range.start),
500181
+ queue_end: String(line.range.end)
500182
+ }
500183
+ };
500184
+ this.host.inject(scopedEnvelope, () => {
500185
+ if (!this.host.ownsChannel()) return;
500186
+ const current = readSessionQueue(this.stateFile);
500187
+ if (current === void 0) throw new Error("Telegram session queue checkpoint is missing");
500188
+ writeSessionQueue(this.stateFile, acknowledgeSessionQueue(current, scope.sessionId, line.range));
500189
+ this.controlsInFlight.delete(key);
500190
+ });
500191
+ }
499849
500192
  let delivered = 0;
499850
500193
  for (const pending of pendingSessionQueue(state, scope.sessionId)) for (const line of readLines(this.queueFile, pending)) {
499851
500194
  if (!this.host.ownsChannel() || this.host.currentSessionId() !== scope.sessionId) return;
499852
500195
  const key = `${line.range.fileId}:${line.range.start}:${line.range.end}`;
499853
- if (this.inFlight.has(key)) continue;
500196
+ if (this.inFlight.has(key) || this.controlsInFlight.has(key)) continue;
499854
500197
  const acknowledge = () => {
499855
500198
  if (!this.host.ownsChannel()) return;
499856
500199
  const current = readSessionQueue(this.stateFile);
@@ -499861,9 +500204,20 @@ var init_telegram_session_queue_delivery = __esmMin((() => {
499861
500204
  this.inFlight.add(key);
499862
500205
  const envelope = parseChannelEnvelope(line.text);
499863
500206
  if (envelope === void 0) acknowledge();
499864
- else this.host.inject(envelope, acknowledge);
500207
+ else if (isChannelStop(envelope)) {
500208
+ this.inFlight.delete(key);
500209
+ continue;
500210
+ } else this.host.inject({
500211
+ ...envelope,
500212
+ meta: {
500213
+ ...envelope.meta,
500214
+ queue_file_id: line.range.fileId,
500215
+ queue_start: String(line.range.start),
500216
+ queue_end: String(line.range.end)
500217
+ }
500218
+ }, acknowledge);
499865
500219
  delivered += 1;
499866
- if (delivered >= 16 || this.inFlight.size >= 16) return;
500220
+ if (delivered >= 16) return;
499867
500221
  }
499868
500222
  }
499869
500223
  };
@@ -525368,7 +525722,306 @@ var init_web = __esmMin((() => {
525368
525722
  WEB_CONFIRM = "confirm";
525369
525723
  WEB_CANCEL = "cancel";
525370
525724
  }));
525725
+ var session_search_exports = /* @__PURE__ */ __exportAll({
525726
+ SEARCH_LIMITS: () => SEARCH_LIMITS,
525727
+ handleSessionSearchCommand: () => handleSessionSearchCommand,
525728
+ searchSessionMessages: () => searchSessionMessages
525729
+ });
525730
+ async function searchSessionMessages(input) {
525731
+ const result = {
525732
+ scope: input.all ? "all" : "cwd",
525733
+ hits: [],
525734
+ partial: false,
525735
+ reasons: [],
525736
+ bytesRead: 0,
525737
+ sessionsScanned: 0,
525738
+ rejected: 0,
525739
+ malformed: 0
525740
+ };
525741
+ const reason = (value) => {
525742
+ result.partial = true;
525743
+ if (!result.reasons.includes(value)) result.reasons.push(value);
525744
+ };
525745
+ if (typeof input.query !== "string" || !input.query.trim() || input.query.length > 256) throw new Error("query-length");
525746
+ if (!isAbsolute(input.homeDir) || !isAbsolute(input.workDir)) throw new Error("absolute-scope-required");
525747
+ const limits = { ...SEARCH_LIMITS };
525748
+ for (const key of Object.keys(limits)) {
525749
+ const value = input.limits?.[key];
525750
+ if (value !== void 0) {
525751
+ if (!Number.isSafeInteger(value) || value < 1 || value > SEARCH_LIMITS[key]) throw new Error("invalid-budget");
525752
+ limits[key] = value;
525753
+ }
525754
+ }
525755
+ const start = performance$1.now(), home = resolve(input.homeDir), sessions = join(home, "sessions");
525756
+ const check = () => {
525757
+ if (input.signal?.aborted || input.isCurrent?.() === false) throw new SearchStop("cancelled");
525758
+ if (performance$1.now() - start >= limits.milliseconds) throw new SearchStop("time-limit");
525759
+ };
525760
+ const owner = typeof process.getuid === "function" ? process.getuid() : void 0;
525761
+ const identity = async (file) => lstat(file, { bigint: true });
525762
+ const same = (a, b) => String(a.dev) === String(b.dev) && String(a.ino) === String(b.ino) && a.mode === b.mode && a.uid === b.uid && a.gid === b.gid && a.nlink === b.nlink;
525763
+ const valid = (st, directory) => !st.isSymbolicLink() && (directory ? st.isDirectory() : st.isFile()) && (owner === void 0 || Number(st.uid) === owner && (Number(st.mode) & 18) === 0) && (directory || Number(st.nlink) === 1);
525764
+ async function safePath(file, bounded = true) {
525765
+ if (bounded) check();
525766
+ if (!inside(home, file) || await realpath(home) !== home) throw new Error("unsafe-path");
525767
+ let current = home;
525768
+ const parts = relative(home, file).split(sep), ancestors = [];
525769
+ for (let i = -1; i < parts.length; i++) {
525770
+ if (i >= 0) current = join(current, parts[i]);
525771
+ const st = await identity(current);
525772
+ if (!valid(st, i < parts.length - 1)) throw new Error("unsafe-owner-path");
525773
+ ancestors.push(st);
525774
+ }
525775
+ if (await realpath(file) !== file) throw new Error("unsafe-path");
525776
+ const leaf = await identity(file);
525777
+ if (!valid(leaf, false) || !same(leaf, ancestors.at(-1))) throw new Error("file-changed");
525778
+ if (bounded) check();
525779
+ return {
525780
+ leaf,
525781
+ ancestors
525782
+ };
525783
+ }
525784
+ const samePath = (a, b) => a.ancestors.length === b.ancestors.length && a.ancestors.every((st, i) => same(st, b.ancestors[i])) && same(a.leaf, b.leaf);
525785
+ async function* lines(file, byteLimit, label) {
525786
+ const before = await safePath(file);
525787
+ const handle = await open(file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
525788
+ try {
525789
+ const opened = await handle.stat({ bigint: true });
525790
+ if (!valid(opened, false) || !same(opened, before.leaf)) throw new Error("file-changed");
525791
+ const bound = await safePath(file);
525792
+ if (!samePath(before, bound) || !same(opened, bound.leaf)) throw new Error("file-changed");
525793
+ const openedSize = Number(opened.size), end = Math.min(openedSize, byteLimit);
525794
+ if (openedSize > end) reason(label);
525795
+ const validateFinish = async () => {
525796
+ const after = await handle.stat({ bigint: true });
525797
+ const finalPath = await safePath(file, false);
525798
+ if (!valid(after, false) || !same(opened, after) || !samePath(bound, finalPath) || !same(after, finalPath.leaf) || after.size !== opened.size || after.mtimeNs !== opened.mtimeNs || after.ctimeNs !== opened.ctimeNs) throw new Error("file-changed");
525799
+ };
525800
+ try {
525801
+ let position = 0, line = 1, offset = 0, pending = Buffer.alloc(0), oversized = false;
525802
+ while (position < end) {
525803
+ check();
525804
+ if (result.bytesRead >= limits.totalBytes) throw new SearchStop("total-byte-limit");
525805
+ const size = Math.min(32768, end - position, limits.totalBytes - result.bytesRead);
525806
+ const buffer = Buffer.allocUnsafe(size);
525807
+ const read = await handle.read(buffer, 0, size, position);
525808
+ result.bytesRead += read.bytesRead;
525809
+ check();
525810
+ if (read.bytesRead === 0) throw new Error("file-changed");
525811
+ position += read.bytesRead;
525812
+ const chunk = buffer.subarray(0, read.bytesRead);
525813
+ let at = 0;
525814
+ while (at < chunk.length) {
525815
+ check();
525816
+ const newline = chunk.indexOf(10, at), stop = newline < 0 ? chunk.length : newline;
525817
+ if (!oversized) if (pending.length + stop - at > limits.lineBytes) {
525818
+ pending = Buffer.alloc(0);
525819
+ oversized = true;
525820
+ reason("line-limit");
525821
+ } else pending = Buffer.concat([pending, chunk.subarray(at, stop)]);
525822
+ if (newline < 0) break;
525823
+ if (!oversized) yield {
525824
+ raw: pending,
525825
+ line,
525826
+ offset
525827
+ };
525828
+ offset = position - chunk.length + newline + 1;
525829
+ line++;
525830
+ pending = Buffer.alloc(0);
525831
+ oversized = false;
525832
+ at = newline + 1;
525833
+ }
525834
+ }
525835
+ if (pending.length && !oversized && position === openedSize) yield {
525836
+ raw: pending,
525837
+ line,
525838
+ offset
525839
+ };
525840
+ } finally {
525841
+ await validateFinish();
525842
+ }
525843
+ } finally {
525844
+ await handle.close();
525845
+ }
525846
+ }
525847
+ const parse = (raw) => {
525848
+ if (raw.length === 0 || raw.toString("utf8").trim() === "") return void 0;
525849
+ try {
525850
+ if (!isUtf8(raw)) throw new Error("utf8");
525851
+ return JSON.parse(raw.toString("utf8"));
525852
+ } catch {
525853
+ result.malformed++;
525854
+ reason("malformed-record");
525855
+ return;
525856
+ }
525857
+ };
525858
+ try {
525859
+ check();
525860
+ const entries = /* @__PURE__ */ new Map();
525861
+ try {
525862
+ const stagedEntries = /* @__PURE__ */ new Map();
525863
+ for await (const row of lines(join(home, "session_index.jsonl"), limits.indexBytes, "index-byte-limit")) {
525864
+ const e = parse(row.raw);
525865
+ if (!e || typeof e.sessionId !== "string" || typeof e.sessionDir !== "string" || typeof e.workDir !== "string" || !isAbsolute(e.sessionDir) || !isAbsolute(e.workDir) || !inside(sessions, resolve(e.sessionDir)) || basename(resolve(e.sessionDir)) !== e.sessionId || !/^[a-zA-Z0-9_-]+$/.test(e.sessionId)) {
525866
+ if (e !== void 0) {
525867
+ result.rejected++;
525868
+ reason("rejected-index-entry");
525869
+ }
525870
+ continue;
525871
+ }
525872
+ if (!stagedEntries.has(e.sessionId) && stagedEntries.size >= limits.sessions) {
525873
+ reason("session-limit");
525874
+ break;
525875
+ }
525876
+ stagedEntries.set(e.sessionId, {
525877
+ id: e.sessionId,
525878
+ dir: resolve(e.sessionDir),
525879
+ workDir: resolve(e.workDir)
525880
+ });
525881
+ }
525882
+ for (const [id, entry] of stagedEntries) entries.set(id, entry);
525883
+ } catch (error) {
525884
+ if (error instanceof SearchStop) throw error;
525885
+ result.rejected++;
525886
+ reason("index-unavailable");
525887
+ if (error instanceof Error && error.message === "file-changed") reason("file-changed");
525888
+ }
525889
+ for (const entry of entries.values()) {
525890
+ if (!input.all && entry.workDir !== resolve(input.workDir)) continue;
525891
+ check();
525892
+ const wire = join(entry.dir, "agents", "main", "wire.jsonl");
525893
+ result.sessionsScanned++;
525894
+ try {
525895
+ const stagedHits = [];
525896
+ let hitLimit = false;
525897
+ rows: for await (const row of lines(wire, limits.fileBytes, "file-byte-limit")) {
525898
+ const record = parse(row.raw);
525899
+ const message = record?.type === "context.append_message" ? record.message : void 0;
525900
+ if (!message || message.role !== "user" && message.role !== "assistant" || !Array.isArray(message.content)) continue;
525901
+ const origin = message.origin;
525902
+ if (origin !== void 0 && (origin === null || typeof origin !== "object" || Array.isArray(origin) || typeof origin.kind !== "string")) {
525903
+ result.malformed++;
525904
+ reason("malformed-record");
525905
+ continue;
525906
+ }
525907
+ try {
525908
+ if (input.isInternalMessage(message)) continue;
525909
+ } catch {
525910
+ result.malformed++;
525911
+ reason("malformed-record");
525912
+ continue;
525913
+ }
525914
+ for (let partIndex = 0; partIndex < message.content.length; partIndex++) {
525915
+ const part = message.content[partIndex];
525916
+ if (part?.type !== "text" || typeof part.text !== "string") continue;
525917
+ for (let from = 0; from <= part.text.length - input.query.length;) {
525918
+ check();
525919
+ const found = part.text.indexOf(input.query, from);
525920
+ if (found < 0) break;
525921
+ stagedHits.push({
525922
+ sessionId: entry.id,
525923
+ wire: "agents/main/wire.jsonl",
525924
+ line: row.line,
525925
+ recordByteOffset: row.offset,
525926
+ partIndex,
525927
+ utf16Offset: found,
525928
+ utf16Length: input.query.length,
525929
+ role: message.role,
525930
+ preview: part.text.slice(Math.max(0, found - 60), found + input.query.length + 60)
525931
+ });
525932
+ if (result.hits.length + stagedHits.length >= limits.hits) {
525933
+ hitLimit = true;
525934
+ break rows;
525935
+ }
525936
+ from = found + 1;
525937
+ }
525938
+ }
525939
+ }
525940
+ result.hits.push(...stagedHits);
525941
+ if (hitLimit) throw new SearchStop("hit-limit");
525942
+ } catch (error) {
525943
+ if (error instanceof SearchStop) throw error;
525944
+ result.rejected++;
525945
+ reason("wire-unavailable");
525946
+ if (error instanceof Error && error.message === "file-changed") reason("file-changed");
525947
+ }
525948
+ }
525949
+ } catch (error) {
525950
+ if (!(error instanceof SearchStop)) throw error;
525951
+ reason(error.message);
525952
+ }
525953
+ return result;
525954
+ }
525955
+ async function handleSessionSearchCommand(host, args, isInternalMessage, requestController) {
525956
+ if (requestController?.signal.aborted) return;
525957
+ const text = args.trim();
525958
+ if (host.getChannelCommandContext?.() !== void 0 || host.session?.connectionKind === "gateway") {
525959
+ host.showError("local-console-only");
525960
+ return;
525961
+ }
525962
+ if (text === "--cancel") {
525963
+ active.get(host)?.abort();
525964
+ active.delete(host);
525965
+ return;
525966
+ }
525967
+ const all = text.startsWith("--all "), query = all ? text.slice(6).trim() : text;
525968
+ if (!query || query.length > 256 || query.startsWith("--")) {
525969
+ host.showStatus(JSON.stringify({
525970
+ format: "blun-session-search-json-v1",
525971
+ usage: "/sessions search [--all] <text> | /sessions search --cancel"
525972
+ }));
525973
+ return;
525974
+ }
525975
+ active.get(host)?.abort();
525976
+ const controller = requestController ?? new AbortController();
525977
+ active.set(host, controller);
525978
+ const session = host.session, workDir = host.state.appState.workDir, sessionId = host.state.appState.sessionId;
525979
+ const harness = host.harness, homeDir = harness.homeDir;
525980
+ const current = () => !host.aborted && !controller.signal.aborted && active.get(host) === controller && host.session === session && host.session?.connectionKind !== "gateway" && host.harness === harness && host.harness.homeDir === homeDir && host.state.appState.workDir === workDir && host.state.appState.sessionId === sessionId && host.getChannelCommandContext?.() === void 0;
525981
+ try {
525982
+ const result = await searchSessionMessages({
525983
+ homeDir,
525984
+ workDir,
525985
+ query,
525986
+ all,
525987
+ signal: controller.signal,
525988
+ isCurrent: current,
525989
+ isInternalMessage
525990
+ });
525991
+ if (current()) host.showStatus(JSON.stringify({
525992
+ format: "blun-session-search-json-v1",
525993
+ ...result
525994
+ }, null, 2).replace(/[\u007f-\u009f\u202a-\u202e\u2066-\u2069]/g, (char) => `\\u${char.charCodeAt(0).toString(16).padStart(4, "0")}`));
525995
+ } catch (error) {
525996
+ if (current()) host.showError(error instanceof Error ? error.message : "search-failed");
525997
+ } finally {
525998
+ if (active.get(host) === controller) active.delete(host);
525999
+ }
526000
+ }
526001
+ var init_session_search = __esmMin((() => {
526002
+ SEARCH_LIMITS = Object.freeze({
526003
+ indexBytes: 1024 * 1024,
526004
+ fileBytes: 4 * 1024 * 1024,
526005
+ totalBytes: 16 * 1024 * 1024,
526006
+ lineBytes: 256 * 1024,
526007
+ sessions: 128,
526008
+ hits: 100,
526009
+ milliseconds: 1500
526010
+ });
526011
+ SearchStop = class extends Error {};
526012
+ active = /* @__PURE__ */ new WeakMap();
526013
+ inside = (root, child) => {
526014
+ const rel = relative(root, child);
526015
+ return rel !== "" && !isAbsolute(rel) && rel !== ".." && !rel.startsWith(`..${sep}`);
526016
+ };
526017
+ }));
526018
+ function tryCancelSessionSearchInput(host, text) {
526019
+ if (!/^\/sessions[ \t]+search[ \t]+--cancel$/.test(text.trim()) || host.getChannelCommandContext?.() !== void 0 || host.session?.connectionKind === "gateway") return false;
526020
+ sessionSearchRequests.get(host)?.abort();
526021
+ return true;
526022
+ }
525371
526023
  function dispatchInput(host, text) {
526024
+ if (tryCancelSessionSearchInput(host, text)) return Promise.resolve();
525372
526025
  if (isExperimentalFlagEnabled("multiline_chat_input") && isMultilineChatInput(text)) {
525373
526026
  host.sendNormalUserInput(text);
525374
526027
  return Promise.resolve();
@@ -525511,6 +526164,24 @@ async function handleBuiltInSlashCommand(host, name, args, invokedName = name) {
525511
526164
  host.state.ui.requestRender();
525512
526165
  return;
525513
526166
  case "sessions":
526167
+ if (/^search(?:\s|$)/.test(args.trim())) {
526168
+ const searchOwner = host.session;
526169
+ const searchWorkDir = host.state.appState.workDir;
526170
+ const searchSessionId = host.state.appState.sessionId;
526171
+ const searchHarness = host.harness;
526172
+ const searchHomeDir = searchHarness.homeDir;
526173
+ sessionSearchRequests.get(host)?.abort();
526174
+ const searchController = new AbortController();
526175
+ sessionSearchRequests.set(host, searchController);
526176
+ try {
526177
+ const { handleSessionSearchCommand } = await Promise.resolve().then(() => (init_session_search(), session_search_exports));
526178
+ if (searchController.signal.aborted || sessionSearchRequests.get(host) !== searchController || host.aborted || host.session !== searchOwner || host.state.appState.workDir !== searchWorkDir || host.state.appState.sessionId !== searchSessionId || host.harness !== searchHarness || host.harness.homeDir !== searchHomeDir) return;
526179
+ await handleSessionSearchCommand(host, args.trim().slice(6), isInternalMessage, searchController);
526180
+ } finally {
526181
+ if (sessionSearchRequests.get(host) === searchController) sessionSearchRequests.delete(host);
526182
+ }
526183
+ return;
526184
+ }
525514
526185
  if ((host.session?.connectionKind === "gateway" || isExperimentalFlagEnabled("session_references")) && args.trim().length > 0) await host.showSessionPicker(args.trim());
525515
526186
  else await host.showSessionPicker();
525516
526187
  return;
@@ -525689,6 +526360,7 @@ async function handleBuiltInSlashCommand(host, name, args, invokedName = name) {
525689
526360
  }
525690
526361
  }
525691
526362
  var init_dispatch = __esmMin((() => {
526363
+ init_export_markdown();
525692
526364
  init_dispatch_swarm_copy();
525693
526365
  init_activation();
525694
526366
  init_elevated();
@@ -525727,6 +526399,7 @@ var init_dispatch = __esmMin((() => {
525727
526399
  init_telegram_access();
525728
526400
  init_undo();
525729
526401
  init_web();
526402
+ sessionSearchRequests = /* @__PURE__ */ new WeakMap();
525730
526403
  }));
525731
526404
  var init_commands = __esmMin((() => {
525732
526405
  init_experimental_flags();
@@ -527856,7 +528529,7 @@ function singleLine$1(text) {
527856
528529
  return sanitizeTerminalText(text).replaceAll(/\s+/g, " ").trim();
527857
528530
  }
527858
528531
  function sessionSearchText(session) {
527859
- return singleLine$1(`${session.id} ${session.title ?? ""}`);
528532
+ return singleLine$1(`${session.id} ${session.title ?? ""} ${session.work_dir ?? ""} ${session.last_prompt ?? ""}`);
527860
528533
  }
527861
528534
  var ELLIPSIS$3, SessionPickerComponent;
527862
528535
  var init_session_picker$1 = __esmMin((() => {
@@ -530711,16 +531384,22 @@ var init_channel_queue_deadline = __esmMin((() => {
530711
531384
  deliveryInFlight = false;
530712
531385
  pendingReleaseCount = 0;
530713
531386
  disposed = false;
530714
- constructor(host) {
531387
+ scope;
531388
+ constructor(host) {
530715
531389
  this.host = host;
531390
+ this.scope = host.deliveryScope?.();
531391
+ }
531392
+ sync() {
531393
+ this.refreshScope();
530716
531394
  }
530717
- sync() {}
530718
531395
  requestDeliveryAtSafePoint() {
531396
+ this.refreshScope();
530719
531397
  if (this.retainReleaseWhileDeliveryIsInFlight()) return;
530720
531398
  if (this.host.hasWaitingWork() && !this.host.canDeliverWork()) return;
530721
531399
  this.requestDelivery();
530722
531400
  }
530723
531401
  requestDeliveryNow() {
531402
+ this.refreshScope();
530724
531403
  if (this.retainReleaseWhileDeliveryIsInFlight()) return;
530725
531404
  if (this.host.hasWaitingWork() && !this.host.canDeliverWork()) return;
530726
531405
  this.requestDelivery();
@@ -530739,7 +531418,14 @@ var init_channel_queue_deadline = __esmMin((() => {
530739
531418
  this.pendingReleaseCount += 1;
530740
531419
  this.pumpDelivery();
530741
531420
  }
530742
- pumpDelivery() {
531421
+ refreshScope() {
531422
+ const scope = this.host.deliveryScope?.();
531423
+ if (scope === this.scope) return;
531424
+ this.scope = scope;
531425
+ this.pendingReleaseCount = 0;
531426
+ }
531427
+ pumpDelivery() {
531428
+ this.refreshScope();
530743
531429
  if (this.disposed || this.deliveryInFlight || this.pendingReleaseCount === 0) return;
530744
531430
  if (!this.host.hasWaitingWork() || !this.host.canDeliverWork()) {
530745
531431
  this.pendingReleaseCount = 0;
@@ -530747,7 +531433,8 @@ var init_channel_queue_deadline = __esmMin((() => {
530747
531433
  }
530748
531434
  this.pendingReleaseCount -= 1;
530749
531435
  this.deliveryInFlight = true;
530750
- Promise.resolve().then(() => this.host.deliverOne()).catch(() => false).finally(() => {
531436
+ const scope = this.host.deliveryScope?.();
531437
+ Promise.resolve().then(() => this.disposed || scope !== this.host.deliveryScope?.() || !this.host.hasWaitingWork() || !this.host.canDeliverWork() ? false : this.host.deliverOne()).catch(() => false).finally(() => {
530751
531438
  this.deliveryInFlight = false;
530752
531439
  this.pumpDelivery();
530753
531440
  });
@@ -530755,6 +531442,81 @@ var init_channel_queue_deadline = __esmMin((() => {
530755
531442
  };
530756
531443
  }));
530757
531444
  var REMOTE_COMMANDS, REMOTE_COMMAND_LIST;
531445
+ var init_active_input_delivery = __esmMin((() => {
531446
+ ActiveInputDelivery = class {
531447
+ host;
531448
+ attempts = /* @__PURE__ */ new Map();
531449
+ pumping = false;
531450
+ dirty = false;
531451
+ ended = false;
531452
+ constructor(host) {
531453
+ this.host = host;
531454
+ }
531455
+ has(item) {
531456
+ return item !== void 0 && this.attempts.has(item);
531457
+ }
531458
+ endTurn() {
531459
+ this.ended = true;
531460
+ for (const [item, attempt] of this.attempts) if (attempt.terminal) this.attempts.delete(item);
531461
+ this.host.retry();
531462
+ }
531463
+ cancel() {
531464
+ for (const attempt of this.attempts.values()) attempt.abort.abort();
531465
+ this.attempts.clear();
531466
+ }
531467
+ request() {
531468
+ if (this.ended) return;
531469
+ this.dirty = true;
531470
+ if (this.pumping) return;
531471
+ this.pumping = true;
531472
+ this.pump().finally(() => {
531473
+ this.pumping = false;
531474
+ if (this.dirty) this.request();
531475
+ });
531476
+ }
531477
+ async pump() {
531478
+ do {
531479
+ this.dirty = false;
531480
+ for (const item of this.host.items()) {
531481
+ const prior = this.attempts.get(item);
531482
+ if (prior !== void 0) {
531483
+ if (!prior.accepted) return;
531484
+ continue;
531485
+ }
531486
+ const attempt = {
531487
+ accepted: false,
531488
+ terminal: false,
531489
+ abort: new AbortController()
531490
+ };
531491
+ this.attempts.set(item, attempt);
531492
+ let admitted;
531493
+ const acceptance = new Promise((resolve) => {
531494
+ admitted = resolve;
531495
+ });
531496
+ this.host.send(item, attempt.abort.signal, () => {
531497
+ attempt.accepted = true;
531498
+ admitted();
531499
+ }).then((disposition) => {
531500
+ if (attempt.abort.signal.aborted || this.attempts.get(item) !== attempt) return;
531501
+ attempt.terminal = true;
531502
+ if (disposition === "context") {
531503
+ this.attempts.delete(item);
531504
+ this.host.commit(item);
531505
+ }
531506
+ if (disposition !== "context" && this.ended) {
531507
+ this.attempts.delete(item);
531508
+ this.host.retry();
531509
+ }
531510
+ }).catch((error) => {
531511
+ if (!attempt.abort.signal.aborted) this.host.error(error);
531512
+ }).finally(admitted);
531513
+ await acceptance;
531514
+ if (attempt.abort.signal.aborted || !attempt.accepted) return;
531515
+ }
531516
+ } while (this.dirty);
531517
+ }
531518
+ };
531519
+ }));
530758
531520
  var init_channel_command$1 = __esmMin((() => {
530759
531521
  REMOTE_COMMANDS = new Set([
530760
531522
  "loop",
@@ -530770,6 +531532,7 @@ var init_channel_command$1 = __esmMin((() => {
530770
531532
  REMOTE_COMMAND_LIST = "/loop [interval] [prompt]\n/loop status|pause|resume|stop\n/goal\n/idea\n/chancenradar\n/curiosity\n/scout\n/reload\n/memory status|on|off\n/befehle";
530771
531533
  }));
530772
531534
  function channelCommandInput(envelope) {
531535
+ if (isChannelStop(envelope)) return "/stop";
530773
531536
  if (!channelMessageAddressed(envelope) || envelope.meta["addressed"]?.trim().toLowerCase() === "semantic") return void 0;
530774
531537
  const parsed = parseSlashInput(envelope.text.trim());
530775
531538
  if (parsed === null) return void 0;
@@ -530778,6 +531541,7 @@ function channelCommandInput(envelope) {
530778
531541
  return parsed.args.length === 0 ? `/${name}` : `/${name} ${parsed.args}`;
530779
531542
  }
530780
531543
  function channelCommandCanInterrupt(input) {
531544
+ if (input.trim() === "/stop") return true;
530781
531545
  const parsed = parseSlashInput(input);
530782
531546
  if (parsed?.name === "befehle") return true;
530783
531547
  if (parsed === null) return false;
@@ -530800,7 +531564,8 @@ var init_channel_command = __esmMin((() => {
530800
531564
  init_channel_command$1();
530801
531565
  init_channel_injection();
530802
531566
  init_event_payload();
530803
- ChannelCommandController = class {
531567
+ init_channel_control();
531568
+ ChannelCommandController = class {
530804
531569
  host;
530805
531570
  execution = new AsyncLocalStorage();
530806
531571
  constructor(host) {
@@ -530810,7 +531575,8 @@ var init_channel_command = __esmMin((() => {
530810
531575
  const execution = this.execution.getStore();
530811
531576
  return execution?.active ? {
530812
531577
  input: execution.input,
530813
- chatId: execution.envelope.meta.chat_id
531578
+ chatId: execution.envelope.meta.chat_id,
531579
+ envelope: execution.envelope
530814
531580
  } : void 0;
530815
531581
  }
530816
531582
  commit() {
@@ -536499,7 +537265,11 @@ var init_session_event_handler = __esmMin((() => {
536499
537265
  });
536500
537266
  this.host.resetLivePane();
536501
537267
  this.host.requestQueueDrain();
536502
- } else { this.host.setAppState({ isCompacting: false }); this.host.steerQueueFlushPrefix(); }
537268
+ } else {
537269
+ this.host.setAppState({ isCompacting: false });
537270
+ this.host.steerQueueFlushPrefix();
537271
+ }
537272
+ this.host.releaseChannelQueueAtSafePoint();
536503
537273
  }
536504
537274
  handleBackgroundTaskEvent(event) {
536505
537275
  const { state } = this.host;
@@ -544343,7 +545113,10 @@ var init_blun_tui = __esmMin((() => {
544343
545113
  init_transcript_id();
544344
545114
  init_blun_tui_copy();
544345
545115
  DETACH_HINT_DISPLAY_MS = 4e3;
544346
- BlunTUI = class {
545116
+ init_queue_deadline_watchdog();
545117
+ init_stopped_input_scopes();
545118
+ init_active_input_delivery();
545119
+ BlunTUI = class {
544347
545120
  gatewayStartup;
544348
545121
  localHarness;
544349
545122
  gatewayLifetime = new AbortController();
@@ -544432,7 +545205,12 @@ var init_blun_tui = __esmMin((() => {
544432
545205
  telegramSessionScope;
544433
545206
  channelPreamble = createChannelPreambleState();
544434
545207
  channelQueueDeadline;
544435
- activeApprovalPanel;
545208
+ queueDeadlineWatchdog;
545209
+ queueDeadlineStatus;
545210
+ getQueueDeadlineStatus() {
545211
+ return this.queueDeadlineStatus;
545212
+ }
545213
+ activeApprovalPanel;
544436
545214
  approvalPreview;
544437
545215
  onExit;
544438
545216
  setupHandoff;
@@ -544518,10 +545296,19 @@ var init_blun_tui = __esmMin((() => {
544518
545296
  this.appearanceBasePalette = currentTheme.palette;
544519
545297
  this.resolvedAutoTheme = currentTheme.palette === lightColors ? "light" : "dark";
544520
545298
  currentTheme.setPalette(applyAppearanceToPalette(currentTheme.palette, initialAppState.appearance));
545299
+ this.queueDeadlineWatchdog = new QueueDeadlineWatchdog(() => ({
545300
+ owner: this.session,
545301
+ entries: [...this.queueSteerInFlight?.items ?? [], ...this.state.queuedMessages],
545302
+ reason: this.queueDeadlineBlockingReason()
545303
+ }), (status) => {
545304
+ this.queueDeadlineStatus = status;
545305
+ this.state.ui.requestRender();
545306
+ });
544521
545307
  this.channelQueueDeadline = new ChannelQueueDeadlineController({
544522
545308
  hasWaitingWork: () => this.hasWaitingChannelMessage(),
544523
545309
  canDeliverWork: () => this.canDeliverQueuedChannelHead(),
544524
- deliverOne: () => this.deliverQueuedChannelHead()
545310
+ deliverOne: () => this.deliverQueuedChannelHead(),
545311
+ deliveryScope: () => this.session
544525
545312
  });
544526
545313
  this.managedQuotaWarningController = new ManagedQuotaWarningController({ onChange: (warning) => {
544527
545314
  this.state.quotaWarning.setMessage(warning === void 0 ? void 0 : formatManagedQuotaWarning(warning));
@@ -545264,6 +546051,7 @@ var init_blun_tui = __esmMin((() => {
545264
546051
  }
545265
546052
  this.loopCountdown.dispose();
545266
546053
  this.channelQueueDeadline?.dispose();
546054
+ this.queueDeadlineWatchdog?.dispose();
545267
546055
  try {
545268
546056
  await this.telegramChannel?.stop();
545269
546057
  } catch (error) {
@@ -545352,6 +546140,7 @@ var init_blun_tui = __esmMin((() => {
545352
546140
  this.isShuttingDown = true;
545353
546141
  this.unregisterSignalHandlers();
545354
546142
  this.channelQueueDeadline?.dispose();
546143
+ this.queueDeadlineWatchdog?.dispose();
545355
546144
  this.telegramChannel?.stopNow();
545356
546145
  this.telegramChannel = void 0;
545357
546146
  restoreTerminalModes();
@@ -545418,6 +546207,7 @@ var init_blun_tui = __esmMin((() => {
545418
546207
  }
545419
546208
  const historyText = wasBashMode ? `!${text}` : text;
545420
546209
  this.persistInputHistory(historyText);
546210
+ if (!wasBashMode && tryCancelSessionSearchInput(this, text)) return;
545421
546211
  if (this.editorReplacementActive || this.queueCommandRunning || this.localShellConsentRequest !== void 0) {
545422
546212
  if (wasBashMode) this.enqueueMessage(text, void 0, "bash");
545423
546213
  else if (text.trimStart().startsWith("/") && !(isExperimentalFlagEnabled("multiline_chat_input") && isMultilineChatInput(text))) {
@@ -545639,13 +546429,17 @@ var init_blun_tui = __esmMin((() => {
545639
546429
  return this.state.queuedMessages.some((item) => item.mode === "channel");
545640
546430
  }
545641
546431
  canInterruptForQueuedChannel() {
546432
+ if (this.session !== void 0 && (this.stoppedInputSession === this.session || this.stoppedInputScopes?.get(this.session, this.state.queuedMessages[0]?.agentId ?? this.interactiveAgentId) !== void 0)) return false;
545642
546433
  if (this.hasPendingQueueCommandCancellation()) return false;
545643
546434
  const item = this.state.queuedMessages[0];
545644
546435
  if (/^[1-9]\d*$/u.test(this.pendingChannelReplyGuard?.chatId ?? "") && item?.channelChatId?.startsWith("-") === true) return false;
545645
546436
  return item?.mode === "channel" && item.channelContextOnly !== true && this.session !== void 0 && this.queueSteerInFlight === void 0 && this.manualPromptInFlight === void 0 && this.localShellConsentRequest === void 0 && !this.deferUserMessages && !this.state.appState.isCompacting && this.state.appState.streamingPhase !== "idle" && this.state.appState.streamingPhase !== "shell" && this.shellOutputStreams.size === 0 && !this.streamingUI.hasActiveToolCalls();
545646
546437
  }
545647
546438
  canDeliverQueuedChannelHead() {
546439
+ if (this.session !== void 0 && (this.stoppedInputSession === this.session || this.stoppedInputScopes?.get(this.session, this.state.queuedMessages[0]?.agentId ?? this.interactiveAgentId) !== void 0)) return false;
546440
+ if (this.activeInputDelivery?.has(this.state.queuedMessages[0])) return false;
545648
546441
  if (this.hasPendingQueueCommandCancellation()) return false;
546442
+ if (this.state.appState.isCompacting || this.streamingUI.hasActiveToolCalls() || this.shellOutputStreams.size > 0 || this.state.appState.streamingPhase === "shell") return false;
545649
546443
  const item = this.state.queuedMessages[0];
545650
546444
  if (this.isShuttingDown || this.queueCommandRunning || this.localShellConsentRequest !== void 0 || this.queueSteerInFlight !== void 0 || this.manualPromptInFlight !== void 0 || this.editorReplacementActive || this.deferUserMessages || this.session === void 0 || this.state.appState.model.trim().length === 0 || item?.mode !== "channel") return false;
545651
546445
  const guard = this.pendingChannelReplyGuard;
@@ -545688,6 +546482,7 @@ var init_blun_tui = __esmMin((() => {
545688
546482
  ...item,
545689
546483
  channelTranscriptRendered: transcriptRendered
545690
546484
  };
546485
+ this.queueDeadlineWatchdog?.transfer(item, queuedItem);
545691
546486
  const previousGuard = this.pendingChannelReplyGuard;
545692
546487
  let installedGuard;
545693
546488
  if (previousGuard === void 0 && item.channelChatId !== void 0) {
@@ -545753,6 +546548,11 @@ var init_blun_tui = __esmMin((() => {
545753
546548
  this.commitQueuedSteerIfReady(inFlight);
545754
546549
  }
545755
546550
  restoreQueuedSteerAtTurnEnd(turnId) {
546551
+ if (this.activeInputScope === JSON.stringify([
546552
+ this.session?.id,
546553
+ this.interactiveAgentId,
546554
+ String(turnId)
546555
+ ])) this.activeInputDelivery?.endTurn();
545756
546556
  const inFlight = this.queueSteerInFlight;
545757
546557
  if (inFlight === void 0 || inFlight.turnId !== String(turnId)) return;
545758
546558
  inFlight.turnEnded = true;
@@ -545781,15 +546581,177 @@ var init_blun_tui = __esmMin((() => {
545781
546581
  return false;
545782
546582
  }
545783
546583
  syncChannelQueueDeadline() {
546584
+ this.admitActiveQueuedInputs();
545784
546585
  this.channelQueueDeadline?.sync();
546586
+ this.queueDeadlineWatchdog?.sync();
546587
+ }
546588
+ queueDeadlineBlockingReason() {
546589
+ if (this.isShuttingDown) return "shutdown";
546590
+ if (this.session === void 0) return "no_session";
546591
+ if (this.state.appState.isCompacting) return "compaction";
546592
+ if (this.streamingUI.hasActiveToolCalls() || this.shellOutputStreams.size > 0 || this.state.appState.streamingPhase === "shell") return "tool_or_shell";
546593
+ if (this.activeInputDelivery?.has(this.state.queuedMessages[0]) || this.queueSteerInFlight !== void 0 || this.manualPromptInFlight !== void 0) return "receipt_pending";
546594
+ if (this.deferUserMessages || this.queueCommandRunning || this.localShellConsentRequest !== void 0 || this.editorReplacementActive || this.hasPendingQueueCommandCancellation()) return "admission_barrier";
546595
+ const item = this.state.queuedMessages[0];
546596
+ if (this.pendingChannelReplyGuard !== void 0 && (item?.mode !== "channel" || item.channelChatId !== this.pendingChannelReplyGuard.chatId)) return "chat_boundary";
546597
+ if (this.state.appState.model.trim().length === 0) return "no_model";
546598
+ if (item?.mode === "command" || item?.mode === "bash" || item !== void 0 && item.mode !== "channel" && queueSteerPrefixLength([item], this.interactiveAgentId, 1) === 0) return "fifo_barrier";
546599
+ return this.state.appState.streamingPhase === "idle" ? "idle_admission_pending" : "model_step_or_safe_point";
546600
+ }
546601
+ stoppedInputScopes;
546602
+ get stoppedInputSession() {
546603
+ const session = this.session;
546604
+ return session !== void 0 && this.stoppedInputScopes?.get(session, this.interactiveAgentId) !== void 0 ? session : void 0;
546605
+ }
546606
+ set stoppedInputSession(session) {
546607
+ if (session === void 0) {
546608
+ if (this.session !== void 0) this.stoppedInputScopes?.clear(this.session, this.interactiveAgentId);
546609
+ return;
546610
+ }
546611
+ const turnId = this.streamingUI.getTurnContext().turnId;
546612
+ const agentId = this.interactiveAgentId;
546613
+ const command = this.channelCommands?.context;
546614
+ const activeChat = this.activeInputScope === JSON.stringify([
546615
+ session.id,
546616
+ agentId,
546617
+ turnId
546618
+ ]) ? this.activeInputChat : void 0;
546619
+ this.stoppedInputScopes ??= new StoppedInputScopes();
546620
+ this.stoppedInputScopes.stop(session, {
546621
+ sessionId: session.id,
546622
+ agentId,
546623
+ turnId,
546624
+ chatId: command?.input === "/stop" ? command.chatId : this.pendingChannelReplyGuard?.chatId ?? activeChat,
546625
+ runtimeScope: this.gatewayResetTurn?.session === session ? this.gatewayResetTurn.scope : void 0
546626
+ });
546627
+ }
546628
+ get stoppedQueueBoundary() {
546629
+ return this.session === void 0 ? void 0 : this.stoppedInputScopes?.get(this.session, this.interactiveAgentId)?.boundary;
546630
+ }
546631
+ set stoppedQueueBoundary(boundary) {
546632
+ const scope = this.session === void 0 ? void 0 : this.stoppedInputScopes?.get(this.session, this.interactiveAgentId);
546633
+ if (scope !== void 0) scope.boundary = boundary;
546634
+ }
546635
+ channelOwnsStoppedInput(chatId) {
546636
+ const scope = this.session === void 0 ? void 0 : this.stoppedInputScopes?.get(this.session, this.interactiveAgentId);
546637
+ return scope === void 0 || scope.chatId === chatId;
546638
+ }
546639
+ activeInputRequests;
546640
+ activeInputDelivery;
546641
+ activeInputScope;
546642
+ activeInputChat;
546643
+ admitActiveQueuedInputs() {
546644
+ const session = this.session;
546645
+ if (!isExperimentalFlagEnabled("queue_policies") || session === void 0 || this.stoppedInputSession === session || this.isShuttingDown || this.state.appState.streamingPhase === "idle" || this.state.appState.streamingPhase === "shell" || this.queueSteerInFlight !== void 0 || this.manualPromptInFlight !== void 0 || this.deferUserMessages || this.queueCommandRunning || this.editorReplacementActive || this.localShellConsentRequest !== void 0 || this.hasPendingQueueCommandCancellation() || this.queuePolicyBlocksInput(session)) return false;
546646
+ const turn = this.streamingUI.getTurnContext().turnId;
546647
+ if (turn === void 0 || !/^\d+$/.test(turn) || !Number.isSafeInteger(Number(turn))) return false;
546648
+ const agentId = this.interactiveAgentId;
546649
+ const scope = JSON.stringify([
546650
+ session.id,
546651
+ agentId,
546652
+ turn
546653
+ ]);
546654
+ if (this.activeInputScope !== scope) {
546655
+ this.activeInputDelivery?.cancel();
546656
+ this.activeInputScope = scope;
546657
+ this.activeInputChat = this.pendingChannelReplyGuard?.chatId;
546658
+ const current = () => this.session === session && this.activeInputScope === scope && this.interactiveAgentId === agentId;
546659
+ this.activeInputDelivery = new ActiveInputDelivery({
546660
+ items: () => {
546661
+ if (!current()) return [];
546662
+ const result = [];
546663
+ for (const item of this.state.queuedMessages) {
546664
+ if ((item.agentId ?? "main") !== agentId) break;
546665
+ if (this.activeInputDelivery?.has(item)) {
546666
+ result.push(item);
546667
+ continue;
546668
+ }
546669
+ if (item.mode === "channel") {
546670
+ if (this.activeInputChat === void 0) this.activeInputChat = item.channelChatId;
546671
+ if (item.channelContextOnly === true || this.activeInputChat !== void 0 && this.activeInputChat !== item.channelChatId || this.pendingChannelReplyGuard !== void 0 && this.pendingChannelReplyGuard.chatId !== item.channelChatId) break;
546672
+ } else if (item.mode !== void 0 && item.mode !== "prompt") break;
546673
+ result.push(item);
546674
+ }
546675
+ return result;
546676
+ },
546677
+ send: (item, signal, accepted) => {
546678
+ this.activeInputRequests ??= /* @__PURE__ */ new WeakMap();
546679
+ let request = this.activeInputRequests.get(item) ?? {};
546680
+ this.activeInputRequests.set(item, request);
546681
+ const image = item.channelImagePath === void 0 ? void 0 : buildChannelImagePart(item.channelImagePath);
546682
+ const input = item.parts !== void 0 ? [...item.parts] : image !== void 0 && this.canReadImages() ? [{
546683
+ type: "text",
546684
+ text: item.text.trim()
546685
+ }, image] : item.text.trim();
546686
+ return this.withInteractiveAgent(agentId, async () => {
546687
+ const originalTurn = request.identity?.expectedTurnId;
546688
+ let disposition = await deliverQueueSteer(session, input, Number(turn), signal, () => {
546689
+ if (request.identity?.expectedTurnId === Number(turn)) accepted();
546690
+ }, request);
546691
+ if (originalTurn !== void 0 && originalTurn !== Number(turn) && disposition !== "context") {
546692
+ request = {};
546693
+ this.activeInputRequests.set(item, request);
546694
+ disposition = await deliverQueueSteer(session, input, Number(turn), signal, accepted, request);
546695
+ }
546696
+ if (disposition !== "context") this.activeInputRequests?.delete(item);
546697
+ return disposition;
546698
+ });
546699
+ },
546700
+ commit: (item) => {
546701
+ if (!current() || !this.state.queuedMessages.includes(item)) return;
546702
+ this.activeInputRequests?.delete(item);
546703
+ this.state.queuedMessages = this.state.queuedMessages.filter((entry) => entry !== item);
546704
+ if (!(item.transcriptRendered || item.channelTranscriptRendered)) this.appendTranscriptEntry({
546705
+ id: nextTranscriptId(),
546706
+ kind: "user",
546707
+ turnId: turn,
546708
+ renderMode: "plain",
546709
+ content: item.displayText ?? item.text.trim(),
546710
+ origin: item.origin,
546711
+ imageAttachmentIds: item.imageAttachmentIds
546712
+ });
546713
+ item.channelAcknowledge?.();
546714
+ this.updateQueueDisplay();
546715
+ this.state.ui.requestRender();
546716
+ },
546717
+ error: (error) => {
546718
+ if (current()) this.showError(formatErrorMessage$2(error));
546719
+ },
546720
+ retry: () => {
546721
+ if (current()) this.scheduleQueueDrain();
546722
+ }
546723
+ });
546724
+ }
546725
+ this.activeInputDelivery.request();
546726
+ return true;
545785
546727
  }
545786
- releaseChannelQueueAtSafePoint() {
545787
- this.channelQueueDeadline.requestDeliveryAtSafePoint();
546728
+ releaseChannelQueueAtSafePoint() {
546729
+ if (this.session !== void 0 && (this.stoppedInputSession === this.session || this.stoppedInputScopes?.get(this.session, this.state.queuedMessages[0]?.agentId ?? this.interactiveAgentId) !== void 0)) return;
546730
+ if (this.admitActiveQueuedInputs()) return;
546731
+ this.syncChannelQueueDeadline();
546732
+ if (this.state.appState.isCompacting || this.streamingUI.hasActiveToolCalls() || this.shellOutputStreams.size > 0 || this.state.appState.streamingPhase === "shell") return;
546733
+ if (this.state.appState.streamingPhase === "idle") {
546734
+ this.scheduleQueueDrain();
546735
+ return;
546736
+ }
546737
+ if (this.state.queuedMessages[0]?.mode === "channel") {
546738
+ this.channelQueueDeadline.requestDeliveryAtSafePoint();
546739
+ return;
546740
+ }
546741
+ if (this.pendingChannelReplyGuard !== void 0 || this.queueSteerInFlight !== void 0 || this.manualPromptInFlight !== void 0 || this.deferUserMessages || this.queueCommandRunning || this.localShellConsentRequest !== void 0 || this.editorReplacementActive || this.hasPendingQueueCommandCancellation() || queueSteerPrefixLength(this.state.queuedMessages, this.interactiveAgentId, 1) === 0) return;
546742
+ this.automaticSteerBatch = true;
546743
+ this.queueFlushBatchRemaining = Math.max(1, this.queueFlushBatchRemaining);
546744
+ this.steerQueueFlushPrefix();
545788
546745
  }
545789
546746
  canDrainQueue() {
545790
546747
  if (this.gatewayStartup && !this.gatewayViewReady) return false;
546748
+ if (this.session !== void 0 && this.stoppedInputSession === this.session) return false;
545791
546749
  if (this.queueInterruptCancellations.size > 0) return false;
545792
546750
  const head = this.state.queuedMessages[0];
546751
+ if (this.session !== void 0 && this.stoppedInputScopes?.get(this.session, head?.agentId ?? this.interactiveAgentId) !== void 0) return false;
546752
+ if (this.activeInputDelivery?.has(head)) return false;
546753
+ if (head?.text === "/stop" && head.channelCommandEnvelope !== void 0 && this.activeInputChat !== void 0 && head.channelChatId !== this.activeInputChat) return false;
546754
+ if (head?.text === "/stop" && head.channelCommandEnvelope !== void 0 && this.pendingChannelReplyGuard !== void 0 && head.channelChatId !== this.pendingChannelReplyGuard.chatId) return false;
545793
546755
  if (isExperimentalFlagEnabled("queue_policies") && (head?.mode === void 0 || head.mode === "prompt") && this.session !== void 0 && (this.queueReplayRecoveries.has(JSON.stringify([this.session.id, head?.agentId ?? this.interactiveAgentId])) || this.contextResetRecoveries.has(JSON.stringify([this.session.id, head?.agentId ?? this.interactiveAgentId])))) return false;
545794
546756
  if (isExperimentalFlagEnabled("queue_policies") && (head?.mode === void 0 || head.mode === "prompt") && this.session !== void 0 && this.queueOverflowAdmissionFailures.has(JSON.stringify([this.session.id, head?.agentId ?? this.interactiveAgentId]))) return false;
545795
546757
  if ((head?.mode === void 0 || head.mode === "prompt") && this.session !== void 0 && this.queuePolicyBlocksInput(this.session)) return false;
@@ -545797,6 +546759,7 @@ var init_blun_tui = __esmMin((() => {
545797
546759
  return !this.isShuttingDown && !this.queueCommandRunning && this.queueSteerInFlight === void 0 && this.manualPromptInFlight === void 0 && !this.editorReplacementActive && !this.deferUserMessages && (remoteControl || this.state.appState.streamingPhase === "idle" && !this.state.appState.isCompacting);
545798
546760
  }
545799
546761
  scheduleQueueDrain(minimumDelay = 0) {
546762
+ if (this.admitActiveQueuedInputs()) return;
545800
546763
  if (!this.canDrainQueue()) return;
545801
546764
  if (this.queueDrainTimer !== void 0) {
545802
546765
  if (minimumDelay <= 0) return;
@@ -545996,6 +546959,8 @@ var init_blun_tui = __esmMin((() => {
545996
546959
  const session = this.session;
545997
546960
  if (session === void 0) return;
545998
546961
  const head = this.state.queuedMessages[0];
546962
+ if (this.activeInputDelivery?.has(head)) return;
546963
+ if (head?.text === "/stop" && head.channelCommandEnvelope !== void 0 && this.pendingChannelReplyGuard !== void 0 && head.channelChatId !== this.pendingChannelReplyGuard.chatId) return;
545999
546964
  if (isExperimentalFlagEnabled("queue_policies") && (head?.mode === void 0 || head.mode === "prompt")) {
546000
546965
  const agentId = head?.agentId ?? this.interactiveAgentId;
546001
546966
  const key = JSON.stringify([session.id, agentId]);
@@ -546109,8 +547074,12 @@ var init_blun_tui = __esmMin((() => {
546109
547074
  channelCommandEnvelope: envelope,
546110
547075
  channelAcknowledge: acknowledge
546111
547076
  };
547077
+ if (command === "/stop" && this.session !== void 0 && !this.isShuttingDown && this.channelOwnsStoppedInput(envelope.meta.chat_id) && (this.activeInputChat === void 0 || this.activeInputChat === envelope.meta.chat_id) && (this.pendingChannelReplyGuard === void 0 || this.pendingChannelReplyGuard.chatId === envelope.meta.chat_id)) {
547078
+ this.runChannelCommand(item, envelope);
547079
+ return;
547080
+ }
546112
547081
  const busy = this.state.queuedMessages.length > 0 || this.queueSteerInFlight !== void 0 || this.manualPromptInFlight !== void 0 || this.state.appState.streamingPhase !== "idle" || this.state.appState.isCompacting;
546113
- if (this.session === void 0 || this.deferUserMessages || this.queueCommandRunning || this.localShellConsentRequest !== void 0 || this.editorReplacementActive || busy && !channelCommandCanInterrupt(command)) {
547082
+ if (this.session === void 0 || this.deferUserMessages || this.queueCommandRunning || this.localShellConsentRequest !== void 0 || this.editorReplacementActive || command === "/stop" && !this.channelOwnsStoppedInput(envelope.meta.chat_id) || command === "/stop" && this.activeInputChat !== void 0 && this.activeInputChat !== envelope.meta.chat_id || command === "/stop" && this.pendingChannelReplyGuard !== void 0 && this.pendingChannelReplyGuard.chatId !== envelope.meta.chat_id || busy && !channelCommandCanInterrupt(command)) {
546114
547083
  this.state.queuedMessages.push(item);
546115
547084
  this.scheduleQueueDrain();
546116
547085
  this.updateQueueDisplay();
@@ -546121,11 +547090,13 @@ var init_blun_tui = __esmMin((() => {
546121
547090
  injectChannelEnvelope({
546122
547091
  activationMode: () => !isExperimentalFlagEnabled("session_activation") ? void 0 : this.session !== void 0 && this.state.sessionActivation?.sessionId === this.session.id ? this.state.sessionActivation.mode ?? void 0 : "mention",
546123
547092
  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,
547093
+ isBusy: () => this.stoppedInputSession === this.session || this.queueCommandRunning || this.localShellConsentRequest !== void 0 || this.state.queuedMessages.length > 0 || this.queueSteerInFlight !== void 0 || this.manualPromptInFlight !== void 0 || this.deferUserMessages || this.state.appState.streamingPhase !== "idle" || this.state.appState.isCompacting,
546125
547094
  deliverNow: (modelInput, displayText, origin, contextOnly) => {
546126
547095
  this.sendChannelMessageInternal(this.requireSession(), modelInput, displayText, origin, envelope.meta.chat_id, envelope.meta["image_path"], contextOnly, false, acknowledge);
546127
547096
  },
546128
547097
  enqueue: (modelInput, displayText, origin, contextOnly) => {
547098
+ const session = this.session;
547099
+ if (session !== void 0) this.stoppedInputScopes?.resumeChannel(session, this.interactiveAgentId, envelope, this.state.appState.streamingPhase === "idle" ? void 0 : this.streamingUI.getTurnContext().turnId ?? "", this.gatewayResetTurn?.session === session ? this.gatewayResetTurn.scope : void 0);
546129
547100
  this.state.queuedMessages.push({
546130
547101
  text: modelInput,
546131
547102
  displayText,
@@ -546420,6 +547391,7 @@ var init_blun_tui = __esmMin((() => {
546420
547391
  return last;
546421
547392
  }
546422
547393
  enqueueMessage(text, options, mode) {
547394
+ this.stoppedInputSession = void 0;
546423
547395
  const parts = options?.parts === void 0 ? void 0 : structuredClone(options.parts);
546424
547396
  const imageAttachmentIds = options?.imageAttachmentIds?.slice();
546425
547397
  const policy = this.queuePolicyForSession(this.session);
@@ -546460,6 +547432,7 @@ var init_blun_tui = __esmMin((() => {
546460
547432
  mode,
546461
547433
  transcriptRendered: options?.transcriptRendered
546462
547434
  });
547435
+ this.syncChannelQueueDeadline();
546463
547436
  this.track("input_queue");
546464
547437
  }
546465
547438
  enqueueSlashCommand(text) {
@@ -546864,7 +547837,41 @@ var init_blun_tui = __esmMin((() => {
546864
547837
  return this.captureObservedTurnCancellation(session, agentId, turnId);
546865
547838
  }
546866
547839
  async executeSessionStopCommand(args) {
546867
- return this.executeSessionCancellationCommand(args, true);
547840
+ if (!isExperimentalFlagEnabled("queue_policies")) throw new Error("QUEUE_POLICIES_DISABLED");
547841
+ if (args.trim() !== "") throw new Error("STOP_ARGUMENTS_UNSUPPORTED");
547842
+ const session = this.session;
547843
+ if (session === void 0) return;
547844
+ const command = this.channelCommands?.context;
547845
+ if (command?.input === "/stop" && !this.channelOwnsStoppedInput(command.chatId)) return;
547846
+ const previous = this.stoppedInputScopes?.get(session, this.interactiveAgentId);
547847
+ if (command?.input === "/stop" && previous?.boundary !== void 0 && previous.boundary !== "absent") {
547848
+ const fileId = command.envelope.meta["queue_file_id"];
547849
+ const end = command.envelope.meta["queue_end"];
547850
+ if (fileId !== previous.boundary.fileId || end === void 0 || !/^\d+$/.test(end) || !Number.isSafeInteger(Number(end)) || Number(end) <= previous.boundary.frontier) return;
547851
+ }
547852
+ this.stoppedInputSession = session;
547853
+ if (command?.input === "/stop") {
547854
+ const fileId = command.envelope.meta["queue_file_id"];
547855
+ const rawEnd = command.envelope.meta["queue_end"];
547856
+ const end = Number(rawEnd);
547857
+ this.stoppedQueueBoundary = fileId !== void 0 && rawEnd !== void 0 && /^\d+$/.test(rawEnd) && Number.isSafeInteger(end) ? {
547858
+ fileId,
547859
+ frontier: end
547860
+ } : void 0;
547861
+ } else this.stoppedQueueBoundary = this.telegramChannel === void 0 ? void 0 : this.captureTelegramQueueBoundary();
547862
+ this.activeInputDelivery?.cancel();
547863
+ const turn = this.streamingUI.getTurnContext().turnId;
547864
+ if (turn === void 0 || !/^\d+$/.test(turn)) return;
547865
+ const turnId = Number(turn);
547866
+ if (!Number.isSafeInteger(turnId)) throw new Error("ACTIVE_TURN_ID_UNAVAILABLE");
547867
+ const agentId = this.interactiveAgentId;
547868
+ let scope;
547869
+ if (session.connectionKind === "gateway") {
547870
+ const observed = this.gatewayResetTurn;
547871
+ if (agentId !== "main" || observed?.session !== session || observed.turnId !== turnId) throw new Error("RESET_CONTEXT_SCOPE_UNAVAILABLE");
547872
+ scope = observed.scope;
547873
+ }
547874
+ await this.withInteractiveAgent(agentId, () => session.cancelTurn(turnId, scope, true));
546868
547875
  }
546869
547876
  async executeSessionAbortCommand(args) {
546870
547877
  return this.executeSessionCancellationCommand(args, false);
@@ -546982,6 +547989,22 @@ var init_blun_tui = __esmMin((() => {
546982
547989
  this.enqueueMessage(input, options);
546983
547990
  return;
546984
547991
  }
547992
+ if (isExperimentalFlagEnabled("queue_policies") && this.session === session && this.state.appState.streamingPhase !== "idle" && this.state.appState.streamingPhase !== "shell") {
547993
+ this.stoppedInputSession = void 0;
547994
+ this.state.queuedMessages.push({
547995
+ text: input,
547996
+ agentId: this.interactiveAgentId,
547997
+ parts: options?.parts === void 0 ? void 0 : structuredClone(options.parts),
547998
+ imageAttachmentIds: options?.imageAttachmentIds?.slice(),
547999
+ transcriptRendered: options?.transcriptRendered
548000
+ });
548001
+ this.syncChannelQueueDeadline();
548002
+ this.track("input_queue");
548003
+ this.updateQueueDisplay();
548004
+ this.state.ui.requestRender();
548005
+ this.scheduleQueueDrain();
548006
+ return;
548007
+ }
546985
548008
  const policy = this.queuePolicyForSession(session);
546986
548009
  const timedSteer = isExperimentalFlagEnabled("queue_policies") && policy?.mode === "steer" && options?.parts === void 0 && (options?.imageAttachmentIds?.length ?? 0) === 0 && (this.state.appState.streamingPhase !== "idle" || this.state.queuedMessages.length > 0);
546987
548010
  if (timedSteer) {
@@ -547102,6 +548125,8 @@ var init_blun_tui = __esmMin((() => {
547102
548125
  }
547103
548126
  clearQueuedMessages(preserveCancellations = false) {
547104
548127
  if (!preserveCancellations) this.queueInterruptCancellations.clear();
548128
+ this.activeInputDelivery?.cancel();
548129
+ this.activeInputScope = void 0;
547105
548130
  this.queueSteerInFlight?.receiptAbort?.abort();
547106
548131
  if (this.manualPromptInFlight?.promptAbort !== void 0 && !this.manualPromptInFlight.promptSubmitted && this.state.appState.streamingPhase === "waiting" && !this.streamingUI.hasActiveTurn()) {
547107
548132
  this.setAppState({ streamingPhase: "idle" });
@@ -547483,6 +548508,8 @@ var init_blun_tui = __esmMin((() => {
547483
548508
  this.sessionBindingRequest = void 0;
547484
548509
  const previous = this.session;
547485
548510
  this.queueInterruptCancellations.clear();
548511
+ this.activeInputDelivery?.cancel();
548512
+ this.activeInputScope = void 0;
547486
548513
  this.queueSteerInFlight?.receiptAbort?.abort();
547487
548514
  this.manualPromptInFlight?.promptAbort?.abort();
547488
548515
  this.managedQuotaWarningController.dismiss();
@@ -547569,7 +548596,11 @@ var init_blun_tui = __esmMin((() => {
547569
548596
  this.localShellConsentRequest = void 0;
547570
548597
  if (this.session !== void 0) this.localShellConsent.invalidate(this.session);
547571
548598
  if (!this.preserveQueueAcrossSessionReset) this.queueInterruptCancellations.clear();
547572
- if (!this.preserveQueueAcrossSessionReset) this.queueSteerInFlight?.receiptAbort?.abort();
548599
+ if (!this.preserveQueueAcrossSessionReset) {
548600
+ this.activeInputDelivery?.cancel();
548601
+ this.activeInputScope = void 0;
548602
+ this.queueSteerInFlight?.receiptAbort?.abort();
548603
+ }
547573
548604
  this.manualPromptInFlight?.promptAbort?.abort();
547574
548605
  for (const recovery of this.queueReplayRecoveries.values()) recovery.cancel();
547575
548606
  this.queueReplayRecoveries.clear();
@@ -548475,6 +549506,7 @@ var init_blun_tui = __esmMin((() => {
548475
549506
  return this.state.livePane.mode;
548476
549507
  }
548477
549508
  updateQueueDisplay() {
549509
+ this.syncChannelQueueDeadline();
548478
549510
  this.state.queueContainer.clear();
548479
549511
  const queued = [...this.queueSteerInFlight?.items ?? [], ...this.state.queuedMessages];
548480
549512
  if (queued.length === 0) return;