blun-king-cli 9.1.641 → 9.1.643

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/worker-host.mjs CHANGED
@@ -1,5 +1,6 @@
1
1
  #!/usr/bin/env node
2
- // BLUN_BUILD_INPUT_SHA256:d4df2815be55011d12f15cf3f9b01e9c4c1ba80d84ef9322ad9e8fd20b13e018
2
+ // BLUN_BUILD_INPUT_SHA256:e50c78300e52dc6fc7d8003478fe2fa01fe7fdff8b1a749e108e6627de244e7e
3
+ import toolLiveness642 from "./tool-liveness642/index.cjs";
3
4
  /*! wasm-webp 0.1.0
4
5
  MIT License
5
6
 
@@ -21308,7 +21309,7 @@ const FLAG_DEFINITIONS = [
21308
21309
  title: "Session queue policies",
21309
21310
  description: "Apply explicitly persisted session queue admission rules.",
21310
21311
  env: "BLUN_EXPERIMENTAL_QUEUE_POLICIES",
21311
- default: false,
21312
+ default: true,
21312
21313
  surface: "core"
21313
21314
  },
21314
21315
  {
@@ -29638,6 +29639,59 @@ var DenyAllPermissionPolicy = class {
29638
29639
  };
29639
29640
  }
29640
29641
  };
29642
+ var InputControl = class {
29643
+ epoch = 0;
29644
+ stopped = false;
29645
+ provider;
29646
+ preparations = /* @__PURE__ */ new Set();
29647
+ listeners = /* @__PURE__ */ new Set();
29648
+ onChange(listener) {
29649
+ this.listeners.add(listener);
29650
+ return () => {
29651
+ this.listeners.delete(listener);
29652
+ };
29653
+ }
29654
+ changed(stop = false) {
29655
+ this.epoch++;
29656
+ this.stopped ||= stop;
29657
+ this.provider?.abort(new DOMException("INPUT_SUPERSEDED", "AbortError"));
29658
+ for (const controller of this.preparations) controller.abort(new DOMException("INPUT_SUPERSEDED", "AbortError"));
29659
+ for (const listener of this.listeners) listener();
29660
+ }
29661
+ async prepare(signal, operation) {
29662
+ const controller = new AbortController();
29663
+ this.preparations.add(controller);
29664
+ const preparationSignal = AbortSignal.any([signal, controller.signal]);
29665
+ try {
29666
+ return await abortable(Promise.resolve().then(() => {
29667
+ preparationSignal.throwIfAborted();
29668
+ return operation(preparationSignal);
29669
+ }), preparationSignal);
29670
+ } finally {
29671
+ this.preparations.delete(controller);
29672
+ }
29673
+ }
29674
+ beginProvider() {
29675
+ const controller = new AbortController();
29676
+ this.provider = controller;
29677
+ return controller;
29678
+ }
29679
+ endProvider(controller) {
29680
+ if (this.provider === controller) this.provider = void 0;
29681
+ }
29682
+ };
29683
+ var controls = /* @__PURE__ */ new WeakMap();
29684
+ function inputControl(signal) {
29685
+ let control = controls.get(signal);
29686
+ if (control === void 0) {
29687
+ control = new InputControl();
29688
+ controls.set(signal, control);
29689
+ }
29690
+ return control;
29691
+ }
29692
+ function inheritInputControl(signal, control) {
29693
+ if (control !== void 0) controls.set(signal, control);
29694
+ }
29641
29695
  function migrateToolCall(toolCall) {
29642
29696
  const { function: fn, ...rest } = toolCall;
29643
29697
  return {
@@ -29924,8 +29978,11 @@ var FileSystemAgentRecordPersistence = class {
29924
29978
  this.shouldClear = false;
29925
29979
  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("");
29926
29980
  const directory = dirname$3(this.filePath);
29927
- await mkdir(directory, { recursive: true });
29928
- const fh = await open(this.filePath, shouldClear ? "w" : "a");
29981
+ await mkdir(directory, {
29982
+ recursive: true,
29983
+ mode: 448
29984
+ });
29985
+ const fh = await open(this.filePath, shouldClear ? "w" : "a", 384);
29929
29986
  try {
29930
29987
  const before = await fh.stat();
29931
29988
  if (shouldClear || before.size === 0) this.persistedRecordCount = 0;
@@ -183420,7 +183477,13 @@ function getSubagentExecutionCompletion(handle) {
183420
183477
  var SessionSubagentHost = class {
183421
183478
  session;
183422
183479
  ownerAgentId;
183423
- admissionClosed = false;
183480
+ inputLeases = /* @__PURE__ */ new WeakMap();
183481
+ assertInputLease(options) {
183482
+ const lease = this.inputLeases.get(options);
183483
+ if (lease?.active?.runInBackground) return;
183484
+ if (lease !== void 0 && (lease.control.stopped || lease.control.epoch !== lease.epoch)) throw new DOMException("INPUT_SUPERSEDED", "AbortError");
183485
+ }
183486
+ admissionClosed = false;
183424
183487
  operations = new ExecutionLedger();
183425
183488
  childExecutions = new ExecutionLedger();
183426
183489
  preparedDisposers = /* @__PURE__ */ new Set();
@@ -183455,8 +183518,16 @@ var SessionSubagentHost = class {
183455
183518
  assertAdmissionOpen() {
183456
183519
  if (this.admissionClosed) throw new Error("Subagent admission is closed for quiescence");
183457
183520
  }
183458
- runOperation(id, operation) {
183521
+ runOperation(id, operation, input) {
183459
183522
  this.assertAdmissionOpen();
183523
+ if (input !== void 0) {
183524
+ const control = inputControl(input.signal);
183525
+ this.inputLeases.set(input, {
183526
+ control,
183527
+ epoch: control.epoch
183528
+ });
183529
+ this.assertInputLease(input);
183530
+ }
183460
183531
  const completion = operation();
183461
183532
  this.operations.track(id, completion);
183462
183533
  return completion;
@@ -183490,7 +183561,7 @@ var SessionSubagentHost = class {
183490
183561
  return this.session.getReadyAgent(currentId);
183491
183562
  }
183492
183563
  async spawn(options) {
183493
- return this.runOperation("spawn", () => this.spawnInner(options));
183564
+ return this.runOperation("spawn", () => this.spawnInner(options), options);
183494
183565
  }
183495
183566
  async spawnInner(options) {
183496
183567
  options.signal.throwIfAborted();
@@ -183522,7 +183593,7 @@ var SessionSubagentHost = class {
183522
183593
  });
183523
183594
  }
183524
183595
  async resume(agentId, options) {
183525
- return this.runOperation("resume", () => this.resumeInner(agentId, options));
183596
+ return this.runOperation("resume", () => this.resumeInner(agentId, options), options);
183526
183597
  }
183527
183598
  async resumeInner(agentId, options) {
183528
183599
  options.signal.throwIfAborted();
@@ -183549,7 +183620,7 @@ var SessionSubagentHost = class {
183549
183620
  });
183550
183621
  }
183551
183622
  async retry(agentId, options) {
183552
- return this.runOperation("retry", () => this.retryInner(agentId, options));
183623
+ return this.runOperation("retry", () => this.retryInner(agentId, options), options);
183553
183624
  }
183554
183625
  async retryInner(agentId, options) {
183555
183626
  options.signal.throwIfAborted();
@@ -183561,6 +183632,7 @@ var SessionSubagentHost = class {
183561
183632
  modelAlias: parent.config.modelAlias,
183562
183633
  actionStyle: parent.config.actionStyle
183563
183634
  });
183635
+ this.assertInputLease(runOptions);
183564
183636
  this.emitSubagentStarted(parent, agentId);
183565
183637
  if (child.turn.retry("agent-host") === null) throw new Error(`Agent instance "${agentId}" could not start a retry turn`);
183566
183638
  this.observeFirstRequest(child, runOptions);
@@ -183627,7 +183699,7 @@ var SessionSubagentHost = class {
183627
183699
  const { parent, child, profileName } = await this.ensureIdleSubagent(agentId, token);
183628
183700
  signal?.throwIfAborted();
183629
183701
  const source = child.records.fileSource;
183630
- if (source === void 0 || resolve(source.path) !== wire || source.protocolVersion !== "1.4" || child.context.history.length === 0 || child.config.systemPrompt.length === 0) throw new Error("Preserved subagent context could not be verified.");
183702
+ if (source === void 0 || resolve(source.path$1) !== wire || source.protocolVersion !== "1.4" || child.context.history.length === 0 || child.config.systemPrompt.length === 0) throw new Error("Preserved subagent context could not be verified.");
183631
183703
  await sourceReference.refreshAfterReplay();
183632
183704
  this.assertAdmissionOpen();
183633
183705
  const reference = createHash("sha256").update(JSON.stringify([
@@ -183675,7 +183747,7 @@ var SessionSubagentHost = class {
183675
183747
  completion,
183676
183748
  update: (message) => this.updateActiveRun(agentId, completion, message)
183677
183749
  });
183678
- })
183750
+ }, options)
183679
183751
  };
183680
183752
  } catch (error) {
183681
183753
  await dispose();
@@ -183763,6 +183835,7 @@ var SessionSubagentHost = class {
183763
183835
  }
183764
183836
  runWithActiveChild(childId, options, run) {
183765
183837
  this.assertAdmissionOpen();
183838
+ this.assertInputLease(options);
183766
183839
  if (this.activeChildren.has(childId)) throw new Error(`Agent instance "${childId}" is already running`);
183767
183840
  const controller = new AbortController();
183768
183841
  const unlinkAbortSignal = linkAbortSignal(options.signal, controller);
@@ -183771,10 +183844,22 @@ var SessionSubagentHost = class {
183771
183844
  runInBackground: options.runInBackground
183772
183845
  };
183773
183846
  this.activeChildren.set(childId, active);
183774
- const completion = run({
183847
+ const runOptions = {
183775
183848
  ...options,
183776
183849
  signal: controller.signal
183777
- }).finally(() => {
183850
+ };
183851
+ const lease = this.inputLeases.get(options);
183852
+ if (lease !== void 0) {
183853
+ lease.active = active;
183854
+ this.inputLeases.set(runOptions, lease);
183855
+ }
183856
+ const unlinkInput = lease?.control.onChange(() => {
183857
+ if (active.runInBackground) return;
183858
+ const child = this.session.getReadyAgent(childId);
183859
+ if (child !== void 0) child.turn.stop(child.turn.currentId);
183860
+ });
183861
+ const completion = run(runOptions).finally(() => {
183862
+ unlinkInput?.();
183778
183863
  unlinkAbortSignal();
183779
183864
  if (this.activeChildren.get(childId) === active) this.activeChildren.delete(childId);
183780
183865
  });
@@ -183800,6 +183885,7 @@ var SessionSubagentHost = class {
183800
183885
  }
183801
183886
  async runPromptTurn(parent, childId, child, profileName, options) {
183802
183887
  options.signal.throwIfAborted();
183888
+ this.assertInputLease(options);
183803
183889
  await this.triggerSubagentStart(parent, profileName, options.prompt, options.signal);
183804
183890
  options.signal.throwIfAborted();
183805
183891
  let childPrompt = options.prompt;
@@ -183807,6 +183893,7 @@ var SessionSubagentHost = class {
183807
183893
  const gitContext = await collectGitContext(child.kaos, child.config.cwd);
183808
183894
  if (gitContext) childPrompt = `${gitContext}\n\n${childPrompt}`;
183809
183895
  }
183896
+ this.assertInputLease(options);
183810
183897
  this.emitSubagentStarted(parent, childId);
183811
183898
  if (child.turn.prompt([{
183812
183899
  type: "text",
@@ -183822,6 +183909,7 @@ var SessionSubagentHost = class {
183822
183909
  while (remainingContinuations > 0 && result.length < SUMMARY_MIN_LENGTH) {
183823
183910
  remainingContinuations -= 1;
183824
183911
  options.signal.throwIfAborted();
183912
+ this.assertInputLease(options);
183825
183913
  child.turn.prompt([{
183826
183914
  type: "text",
183827
183915
  text: summary_continuation_default
@@ -184807,7 +184895,8 @@ var BackgroundManager = class {
184807
184895
  * Wait for a task to reach a terminal state.
184808
184896
  * Returns immediately if already terminal. Times out after `timeoutMs`.
184809
184897
  */
184810
- async wait(taskId, timeoutMs = 3e4) {
184898
+ async wait(taskId, timeoutMs = 3e4, signal) {
184899
+ signal?.throwIfAborted();
184811
184900
  const entry = this.tasks.get(taskId);
184812
184901
  if (!entry) return void 0;
184813
184902
  if (TERMINAL_STATUSES.has(entry.status)) {
@@ -184816,7 +184905,7 @@ var BackgroundManager = class {
184816
184905
  }
184817
184906
  if (timeoutMs <= 0) return this.toInfo(entry);
184818
184907
  const timeout = timeoutOutcome(timeoutMs, void 0);
184819
- await Promise.race([entry.terminal, timeout]).finally(() => timeout.clear());
184908
+ await toolLiveness642.waitForTaskTerminal(entry.terminal, timeout, signal);
184820
184909
  if (TERMINAL_STATUSES.has(entry.status)) await entry.persistWriteQueue;
184821
184910
  return this.toInfo(entry);
184822
184911
  }
@@ -247986,6 +248075,11 @@ async function prepareSkippedToolCall(step, call) {
247986
248075
  await dispatchToolCall(step, call, call.args);
247987
248076
  return makeResolvedToolCallTask(makeErrorToolResult(call, call.args, output));
247988
248077
  }
248078
+ function waitForPreparationBoundary(step, operation) {
248079
+ if (step.canStart?.() === false) return Promise.reject(new DOMException("INPUT_SUPERSEDED", "AbortError"));
248080
+ if (step.inputControl === void 0) return waitForToolBoundary(step, () => operation(step.signal));
248081
+ return step.inputControl.prepare(step.signal, (signal) => operation(signal));
248082
+ }
247989
248083
  function waitForToolBoundary(step, operation) {
247990
248084
  if (step.programmaticParentCallId === void 0) return Promise.resolve(operation());
247991
248085
  step.signal.throwIfAborted();
@@ -248013,6 +248107,11 @@ function makeResolvedToolCallTask(result) {
248013
248107
  async function runPrepareToolExecutionHook(step, call) {
248014
248108
  const { hooks, signal, turnId, currentStep, llm } = step;
248015
248109
  const { toolCall, args } = call;
248110
+ if (step.canStart?.() === false) return {
248111
+ kind: "blocked",
248112
+ args,
248113
+ output: "INPUT_SUPERSEDED"
248114
+ };
248016
248115
  const hook = hooks?.prepareToolExecution;
248017
248116
  if (hook === void 0) return {
248018
248117
  kind: "allowed",
@@ -248064,7 +248163,7 @@ async function runAuthorizeToolExecutionHook(step, call, args, execution) {
248064
248163
  const hook = hooks?.authorizeToolExecution;
248065
248164
  if (hook === void 0) return void 0;
248066
248165
  try {
248067
- return await waitForToolBoundary(step, () => hook({
248166
+ return await waitForPreparationBoundary(step, (preparationSignal) => hook({
248068
248167
  toolCall: call.toolCall,
248069
248168
  toolCalls: step.toolCalls,
248070
248169
  tool: call.tool,
@@ -248072,7 +248171,7 @@ async function runAuthorizeToolExecutionHook(step, call, args, execution) {
248072
248171
  execution,
248073
248172
  turnId,
248074
248173
  stepNumber: currentStep,
248075
- signal,
248174
+ signal: preparationSignal,
248076
248175
  llm
248077
248176
  }));
248078
248177
  } catch (error) {
@@ -248126,6 +248225,7 @@ async function runRunnableToolCall(step, call, effectiveArgs, metadata, executio
248126
248225
  function createNestedToolInvoker(step, parent) {
248127
248226
  const controller = new AbortController();
248128
248227
  const parentSignal = AbortSignal.any([step.signal, controller.signal]);
248228
+ inheritInputControl(parentSignal, step.inputControl);
248129
248229
  let accepting = true;
248130
248230
  let stopped = false;
248131
248231
  let sequence = 0;
@@ -248152,6 +248252,7 @@ function createNestedToolInvoker(step, parent) {
248152
248252
  while (reservedIds.has(id));
248153
248253
  reservedIds.add(id);
248154
248254
  const signal = input.signal === void 0 ? parentSignal : AbortSignal.any([parentSignal, input.signal]);
248255
+ inheritInputControl(signal, step.inputControl);
248155
248256
  const run = async () => {
248156
248257
  if (stopped) throw new Error("A nested tool stopped the turn.");
248157
248258
  signal.throwIfAborted();
@@ -248241,6 +248342,10 @@ async function finalizePendingToolResult(step, pendingResult) {
248241
248342
  async function executeTool(step, execution, toolCall, toolName, metadata, invokeTool) {
248242
248343
  const { dispatchEvent, signal, turnId } = step;
248243
248344
  signal.throwIfAborted();
248345
+ if (step.canStart?.() === false) return {
248346
+ output: "INPUT_SUPERSEDED",
248347
+ isError: true
248348
+ };
248244
248349
  const executePromise = execution.execute({
248245
248350
  turnId,
248246
248351
  toolCallId: toolCall.id,
@@ -248394,6 +248499,8 @@ async function dispatchToolCall(step, call, args, displayFields) {
248394
248499
  */
248395
248500
  async function executeLoopStep(deps) {
248396
248501
  const { turnId, signal, buildMessages, buildMessagesStrict, dispatchEvent, llm, tools, hooks, executionObserver, log, currentStep, maxRetryAttempts, checkpointBeforeRetry, recordUsage, onStepStarted } = deps;
248502
+ const control = inputControl(signal);
248503
+ const inputEpoch = control.epoch;
248397
248504
  if (hooks?.beforeStep !== void 0) {
248398
248505
  const beforeStep = await hooks.beforeStep({
248399
248506
  turnId,
@@ -248412,10 +248519,13 @@ async function executeLoopStep(deps) {
248412
248519
  turnId,
248413
248520
  currentStep,
248414
248521
  stepUuid,
248415
- onStepStarted
248522
+ onStepStarted,
248523
+ acceptOutput: () => !control.stopped && control.epoch === inputEpoch
248416
248524
  });
248417
248525
  const prepareRequestBoundary = llm.prepareRequestBoundary?.bind(llm);
248418
248526
  const step = {
248527
+ inputControl: control,
248528
+ canStart: () => !control.stopped && control.epoch === inputEpoch,
248419
248529
  tools,
248420
248530
  hooks,
248421
248531
  executionObserver,
@@ -248431,6 +248541,7 @@ async function executeLoopStep(deps) {
248431
248541
  messages,
248432
248542
  tools: tools ?? [],
248433
248543
  signal,
248544
+ boundarySignal: signal,
248434
248545
  ...stepEvents.callbacks
248435
248546
  };
248436
248547
  if (prepareRequestBoundary === void 0) await stepEvents.start();
@@ -248480,6 +248591,12 @@ async function executeLoopStep(deps) {
248480
248591
  log
248481
248592
  };
248482
248593
  let response;
248594
+ const provider = control.beginProvider();
248595
+ chatParams = {
248596
+ ...chatParams,
248597
+ signal: AbortSignal.any([signal, provider.signal])
248598
+ };
248599
+ if (control.stopped || control.epoch !== inputEpoch) provider.abort();
248483
248600
  try {
248484
248601
  response = await chatWithRetry({
248485
248602
  ...retryInput,
@@ -248487,35 +248604,50 @@ async function executeLoopStep(deps) {
248487
248604
  });
248488
248605
  } catch (error) {
248489
248606
  await stepEvents.drain();
248490
- if (buildMessagesStrict === void 0 || !isRecoverableRequestStructureError(error) || prepareRequestBoundary !== void 0 && stepEvents.hasOutput) throw error;
248491
- signal.throwIfAborted();
248492
- log?.warn("provider rejected request structure; resending with strict projection", {
248493
- turnStep: `${turnId}.${String(currentStep)}`,
248494
- model: llm.modelName
248495
- });
248496
- const strictMessages = await buildMessagesStrict();
248497
- signal.throwIfAborted();
248498
- let strictParams = {
248499
- ...chatParams,
248500
- messages: strictMessages
248607
+ if (provider.signal.aborted && !signal.aborted) response = {
248608
+ toolCalls: [],
248609
+ usage: emptyUsage()
248501
248610
  };
248502
- if (prepareRequestBoundary !== void 0) strictParams = await prepareRequestBoundary(strictParams, buildMessagesStrict);
248503
- signal.throwIfAborted();
248504
- try {
248505
- response = await chatWithRetry({
248506
- ...retryInput,
248507
- params: strictParams
248508
- });
248509
- } catch (strictError) {
248510
- log?.error("strict resend still rejected by provider; request remains wire-invalid", {
248611
+ else if (buildMessagesStrict === void 0 || !isRecoverableRequestStructureError(error) || prepareRequestBoundary !== void 0 && stepEvents.hasOutput) throw error;
248612
+ else try {
248613
+ signal.throwIfAborted();
248614
+ log?.warn("provider rejected request structure; resending with strict projection", {
248511
248615
  turnStep: `${turnId}.${String(currentStep)}`,
248512
- model: llm.modelName,
248513
- originalError: errorMessage$4(error),
248514
- strictError: errorMessage$4(strictError)
248616
+ model: llm.modelName
248515
248617
  });
248516
- throw strictError;
248618
+ const strictMessages = await buildMessagesStrict();
248619
+ signal.throwIfAborted();
248620
+ let strictParams = {
248621
+ ...chatParams,
248622
+ messages: strictMessages
248623
+ };
248624
+ if (prepareRequestBoundary !== void 0) strictParams = await prepareRequestBoundary(strictParams, buildMessagesStrict);
248625
+ signal.throwIfAborted();
248626
+ try {
248627
+ response = await chatWithRetry({
248628
+ ...retryInput,
248629
+ params: strictParams
248630
+ });
248631
+ } catch (strictError) {
248632
+ if (provider.signal.aborted) throw strictError;
248633
+ log?.error("strict resend still rejected by provider; request remains wire-invalid", {
248634
+ turnStep: `${turnId}.${String(currentStep)}`,
248635
+ model: llm.modelName,
248636
+ originalError: errorMessage$4(error),
248637
+ strictError: errorMessage$4(strictError)
248638
+ });
248639
+ throw strictError;
248640
+ }
248641
+ log?.info("recovered after strict resend", { turnStep: `${turnId}.${String(currentStep)}` });
248642
+ } catch (strictBoundaryError) {
248643
+ if (!provider.signal.aborted || signal.aborted) throw strictBoundaryError;
248644
+ response = {
248645
+ toolCalls: [],
248646
+ usage: emptyUsage()
248647
+ };
248517
248648
  }
248518
- log?.info("recovered after strict resend", { turnStep: `${turnId}.${String(currentStep)}` });
248649
+ } finally {
248650
+ control.endProvider(provider);
248519
248651
  }
248520
248652
  await stepEvents.start();
248521
248653
  await stepEvents.drain();
@@ -248526,6 +248658,7 @@ async function executeLoopStep(deps) {
248526
248658
  if (effectiveStopReason === "tool_use") {
248527
248659
  if ((await runToolCallBatch(step, response)).stopTurn) effectiveStopReason = "end_turn";
248528
248660
  }
248661
+ if (control.epoch !== inputEpoch) effectiveStopReason = control.stopped ? "end_turn" : "tool_use";
248529
248662
  signal.throwIfAborted();
248530
248663
  await dispatchEvent({
248531
248664
  type: "step.end",
@@ -248636,8 +248769,10 @@ function createStepEventGate(deps) {
248636
248769
  return startPromise;
248637
248770
  };
248638
248771
  const enqueue = (dispatch) => {
248772
+ if (!deps.acceptOutput()) return Promise.resolve();
248639
248773
  hasOutput = true;
248640
248774
  const queued = eventQueue.then(async () => {
248775
+ if (!deps.acceptOutput()) return;
248641
248776
  await start();
248642
248777
  await dispatch();
248643
248778
  });
@@ -248741,6 +248876,10 @@ async function runTurn(input) {
248741
248876
  try {
248742
248877
  while (true) {
248743
248878
  signal.throwIfAborted();
248879
+ if (inputControl(signal).stopped) {
248880
+ stopReason = "aborted";
248881
+ break;
248882
+ }
248744
248883
  if (maxSteps !== void 0 && maxSteps > 0 && steps >= maxSteps) throw createMaxStepsExceededError(maxSteps);
248745
248884
  steps += 1;
248746
248885
  const stepNumber = steps;
@@ -248762,6 +248901,10 @@ async function runTurn(input) {
248762
248901
  onStepStarted: setActiveStep.bind(void 0, stepNumber)
248763
248902
  });
248764
248903
  activeStep = void 0;
248904
+ if (inputControl(signal).stopped) {
248905
+ stopReason = "aborted";
248906
+ break;
248907
+ }
248765
248908
  if (stepResult.stopReason === "tool_use") continue;
248766
248909
  const terminalStopReason = stepResult.stopReason;
248767
248910
  stopReason = terminalStopReason;
@@ -249455,7 +249598,8 @@ var init_prompt = __esmMin((() => {
249455
249598
  sessionAdmissionSteerRequestSchema = admissionReadIdentitySchema.omit({ timeout_ms: true }).extend({ expected_turn_id: admissionTurnSchema });
249456
249599
  sessionAdmissionCancelRequestSchema = object({
249457
249600
  scope: admissionIdentitySchema,
249458
- turn_id: admissionTurnSchema
249601
+ turn_id: admissionTurnSchema,
249602
+ graceful: boolean$1().optional()
249459
249603
  }).strict();
249460
249604
  sessionAdmissionCancelResponseSchema = sessionAdmissionCancelRequestSchema.extend({
249461
249605
  session_id: string().min(1),
@@ -256634,16 +256778,27 @@ var TaskOutputTool = class {
256634
256778
  description: `Reading output of task ${args.task_id}`,
256635
256779
  approvalRule: this.name,
256636
256780
  matchesRule: (ruleArgs) => matchesGlobRuleSubject(ruleArgs, args.task_id),
256637
- execute: () => this.execute(args)
256781
+ execute: ({ signal }) => this.execute(args, signal)
256638
256782
  };
256639
256783
  }
256640
- async execute(args) {
256784
+ async execute(args, signal = new AbortController().signal) {
256785
+ signal.throwIfAborted();
256786
+ const control642 = inputControl(signal);
256787
+ const epoch642 = control642.epoch;
256788
+ let waitReleasedForInput642 = false;
256641
256789
  const info = this.manager.getTask(args.task_id);
256642
256790
  if (!info) return {
256643
256791
  isError: true,
256644
256792
  output: `Task not found: ${args.task_id}`
256645
256793
  };
256646
- if (args.block && !isBackgroundTaskTerminal(info.status)) await this.manager.wait(args.task_id, (args.timeout ?? 30) * 1e3);
256794
+ if (args.block && !isBackgroundTaskTerminal(info.status)) {
256795
+ waitReleasedForInput642 = await toolLiveness642.waitForTaskInput({
256796
+ manager: this.manager, taskId: args.task_id,
256797
+ timeoutMs: (args.timeout ?? 30) * 1e3, signal,
256798
+ control: control642, initialEpoch: epoch642
256799
+ }) === "input";
256800
+ }
256801
+ signal.throwIfAborted();
256647
256802
  const current = this.manager.getTask(args.task_id);
256648
256803
  if (!current) return {
256649
256804
  isError: true,
@@ -256651,7 +256806,8 @@ var TaskOutputTool = class {
256651
256806
  };
256652
256807
  const output = await this.manager.getOutputSnapshot(args.task_id, OUTPUT_PREVIEW_BYTES);
256653
256808
  const lines = [formatPlainObject({
256654
- retrievalStatus: retrievalStatus(current.status, args.block),
256809
+ retrievalStatus: retrievalStatus(current.status, args.block && !waitReleasedForInput642),
256810
+ waitReleasedForInput: waitReleasedForInput642 || void 0,
256655
256811
  ...current,
256656
256812
  outputPath: output.outputPath,
256657
256813
  terminalReason: terminalReason(current),
@@ -257037,6 +257193,8 @@ var AgentTool = class {
257037
257193
  };
257038
257194
  }
257039
257195
  async execution(args, { toolCallId, signal }) {
257196
+ const control642 = inputControl(signal);
257197
+ const epoch642 = control642.epoch;
257040
257198
  try {
257041
257199
  signal.throwIfAborted();
257042
257200
  const runInBackground = args.run_in_background === true;
@@ -257104,8 +257262,16 @@ var AgentTool = class {
257104
257262
  };
257105
257263
  }
257106
257264
  if (runInBackground) return { output: formatBackgroundAgentResult(taskId, handle, args.description, this.allowBackground) };
257107
- if (await this.backgroundManager.waitForForegroundRelease(taskId) === "detached") return { output: formatBackgroundAgentResult(taskId, handle, args.description, this.allowBackground) };
257108
- return await this.formatForegroundResult(taskId, handle);
257265
+ const inputYield642 = toolLiveness642.createForegroundYield({
257266
+ control: control642, initialEpoch: epoch642, signal,
257267
+ enabled: this.allowBackground, idleMs: 0,
257268
+ detach: () => this.backgroundManager.detach(taskId),
257269
+ onError: error => this.log?.warn("Could not background active agent", { error })
257270
+ });
257271
+ try {
257272
+ if (await this.backgroundManager.waitForForegroundRelease(taskId) === "detached") return { output: formatBackgroundAgentResult(taskId, handle, args.description, this.allowBackground) };
257273
+ return await this.formatForegroundResult(taskId, handle);
257274
+ } finally { inputYield642.dispose(); }
257109
257275
  } catch (error) {
257110
257276
  return {
257111
257277
  output: `subagent error: ${launchErrorMessage(error, signal)}`,
@@ -265214,6 +265380,7 @@ var TurnFlow = class {
265214
265380
  if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 2147483647) throw new Error("INVALID_PROMPT_TIMEOUT");
265215
265381
  }
265216
265382
  this.assertAdmissionOpen();
265383
+ this.stopRequested = false;
265217
265384
  this.agent.records.logRecord({
265218
265385
  type: "turn.prompt",
265219
265386
  input,
@@ -265230,6 +265397,7 @@ var TurnFlow = class {
265230
265397
  }
265231
265398
  steer(input, origin = USER_PROMPT_ORIGIN) {
265232
265399
  this.assertAdmissionOpen();
265400
+ this.stopRequested = false;
265233
265401
  this.agent.records.logRecord({
265234
265402
  type: "turn.steer",
265235
265403
  input,
@@ -265243,7 +265411,7 @@ var TurnFlow = class {
265243
265411
  }
265244
265412
  /** Buffer only into the currently active turn; never launch from an idle state. */
265245
265413
  steerActive(input, expectedTurnId, origin = USER_PROMPT_ORIGIN, onDisposition) {
265246
- if (this.admissionClosed) return null;
265414
+ if (this.admissionClosed || this.stopRequested) return null;
265247
265415
  const active = this.activeTurn;
265248
265416
  if (active === null || active === "resuming" || !active.acceptingSteers || expectedTurnId !== void 0 && expectedTurnId !== this.currentId) return null;
265249
265417
  this.agent.records.logRecord({
@@ -265334,7 +265502,19 @@ var TurnFlow = class {
265334
265502
  this.turnId += 1;
265335
265503
  this.activeTurn = "resuming";
265336
265504
  }
265337
- cancel(turnId, reason) {
265505
+ stopRequested = false;
265506
+ stop(turnId) {
265507
+ const active = this.activeTurn;
265508
+ if (turnId !== this.currentId) return;
265509
+ this.stopRequested = true;
265510
+ if (active === null || active === "resuming") return;
265511
+ this.agent.records.logRecord({
265512
+ type: "turn.cancel",
265513
+ turnId
265514
+ });
265515
+ inputControl(active.controller.signal).changed(true);
265516
+ }
265517
+ cancel(turnId, reason) {
265338
265518
  this.agent.records.logRecord({
265339
265519
  type: "turn.cancel",
265340
265520
  turnId
@@ -265405,6 +265585,8 @@ var TurnFlow = class {
265405
265585
  timeoutMs
265406
265586
  });
265407
265587
  this.nextSteerSequence += 1;
265588
+ const active = this.activeTurn;
265589
+ if (origin.kind !== "background_task" && active !== null && active !== "resuming") inputControl(active.controller.signal).changed();
265408
265590
  }
265409
265591
  flushSteerBuffer(turnId = this.currentId, throughSequence = Number.POSITIVE_INFINITY) {
265410
265592
  if (this.steerBuffer.length === 0) return false;
@@ -265465,7 +265647,7 @@ var TurnFlow = class {
265465
265647
  * draining into it via `flushSteerBuffer`.
265466
265648
  */
265467
265649
  onCompactionFinished() {
265468
- if (this.admissionClosed) return;
265650
+ if (this.admissionClosed || this.stopRequested) return;
265469
265651
  if (this.steerBuffer.length === 0) return;
265470
265652
  if (this.activeTurn !== null) return;
265471
265653
  const next = this.steerBuffer.shift();
@@ -265494,7 +265676,7 @@ var TurnFlow = class {
265494
265676
  try {
265495
265677
  if (this.agent.goal.getGoal().goal?.status === "active") return finish(await this.driveGoal(firstTurnId, input, origin, signal));
265496
265678
  const end = await this.runOneTurn(firstTurnId, input, origin, signal, true);
265497
- 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(), [{
265679
+ 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(), [{
265498
265680
  type: "text",
265499
265681
  text: GOAL_CONTINUATION_PROMPT
265500
265682
  }], goalContinuationOrigin(origin), signal));
@@ -265532,6 +265714,11 @@ var TurnFlow = class {
265532
265714
  let turnInput = input;
265533
265715
  let turnOrigin = origin;
265534
265716
  while (true) {
265717
+ if (inputControl(signal).stopped) return { event: {
265718
+ type: "turn.ended",
265719
+ turnId,
265720
+ reason: "cancelled"
265721
+ } };
265535
265722
  const goalBeforeTurn = this.agent.goal.getGoal().goal;
265536
265723
  if (goalBeforeTurn?.status === "active" && goalBeforeTurn.budget.overBudget) {
265537
265724
  await this.agent.goal.markBlocked({ reason: "A configured budget was reached" });
@@ -265621,7 +265808,13 @@ var TurnFlow = class {
265621
265808
  let completedResponse;
265622
265809
  let errorEvent;
265623
265810
  try {
265811
+ const checkStop = () => {
265812
+ signal.throwIfAborted();
265813
+ if (inputControl(signal).stopped) throw new DOMException("INPUT_STOPPED", "AbortError");
265814
+ };
265815
+ checkStop();
265624
265816
  const promptHookEnded = await this.applyUserPromptHook(turnId, input, origin, signal, startedAt);
265817
+ checkStop();
265625
265818
  if (promptHookEnded !== void 0) {
265626
265819
  ended = promptHookEnded.event;
265627
265820
  blockedByUserPromptHook = promptHookEnded.blocked;
@@ -265640,6 +265833,7 @@ var TurnFlow = class {
265640
265833
  this.agent.log.warn("Turn-start observation failed");
265641
265834
  }
265642
265835
  signal.throwIfAborted();
265836
+ checkStop();
265643
265837
  const stopReason = await this.runStepLoop(turnId, signal, input, origin, (response) => {
265644
265838
  completedResponse = response;
265645
265839
  });
@@ -265892,7 +266086,7 @@ var TurnFlow = class {
265892
266086
  },
265893
266087
  settleStep: async ({ signal: stepSignal }) => {
265894
266088
  if (stopForGoalBudget) this.setActiveSteerAcceptance(turnId, false);
265895
- await this.agent.fullCompaction.afterStep(stepSignal);
266089
+ if (!inputControl(stepSignal).stopped) await this.agent.fullCompaction.afterStep(stepSignal);
265896
266090
  },
265897
266091
  afterStep: async () => {
265898
266092
  deduper.endStep();
@@ -266925,6 +267119,9 @@ var BashTool = class BashTool {
266925
267119
  return this.kaos.execWithEnv(shellArgs, mergedEnv);
266926
267120
  }
266927
267121
  async execution(args, signal, onUpdate, onForegroundTaskStart) {
267122
+ const inputControl642 = inputControl(signal);
267123
+ const inputEpoch642 = inputControl642.epoch;
267124
+ let foregroundYield642;
266928
267125
  const validationError = this.validateRunRequest(args, signal);
266929
267126
  if (validationError !== void 0) return validationError;
266930
267127
  const startsInBackground = args.run_in_background === true;
@@ -266949,6 +267146,7 @@ var BashTool = class BashTool {
266949
267146
  let foregroundTaskId;
266950
267147
  const onProcessOutput = startsInBackground ? void 0 : (kind, text) => {
266951
267148
  if (!collectForegroundOutput) return;
267149
+ if (text.length > 0) foregroundYield642?.touch();
266952
267150
  onUpdate?.({
266953
267151
  kind,
266954
267152
  text
@@ -266978,6 +267176,13 @@ var BashTool = class BashTool {
266978
267176
  };
266979
267177
  }
266980
267178
  if (!startsInBackground) onForegroundTaskStart?.(taskId);
267179
+ foregroundYield642 = toolLiveness642.createForegroundYield({
267180
+ control: inputControl642, initialEpoch: inputEpoch642, signal,
267181
+ enabled: !startsInBackground && this.allowBackground,
267182
+ detach: () => this.backgroundManager.detach(taskId),
267183
+ onError: () => onUpdate?.({ kind: "status",
267184
+ text: "Could not move this command to the background; it remains running." }),
267185
+ });
266981
267186
  if (startsInBackground) return this.backgroundStartedResult(taskId, proc, description, {
266982
267187
  title: "Background task started",
266983
267188
  brief: `Started ${taskId}`
@@ -266992,6 +267197,7 @@ var BashTool = class BashTool {
266992
267197
  }
266993
267198
  return await this.foregroundCompletionResult(taskId, proc, builder, foregroundTimeoutMs);
266994
267199
  } finally {
267200
+ foregroundYield642?.dispose();
266995
267201
  collectForegroundOutput = false;
266996
267202
  }
266997
267203
  }
@@ -269945,7 +270151,7 @@ var Agent$1 = class {
269945
270151
  messages: await rebuildMessages()
269946
270152
  };
269947
270153
  let systemPrompt = this.effectiveSystemPrompt;
269948
- const compacted = await this.fullCompaction.beforeStep(params.signal, {
270154
+ const compacted = await this.fullCompaction.beforeStep(params.boundarySignal ?? params.signal, {
269949
270155
  messages: params.messages,
269950
270156
  additionalMessages: steers.messages,
269951
270157
  rebuildMessages,
@@ -270110,6 +270316,12 @@ var Agent$1 = class {
270110
270316
  };
270111
270317
  },
270112
270318
  cancel: (payload) => {
270319
+ if (payload.graceful === true) {
270320
+ if (payload.turnId === void 0) throw new Error("STOP_TURN_REQUIRED");
270321
+ if (payload.turnId !== this.turn.currentId) return;
270322
+ this.turn.stop(payload.turnId);
270323
+ return Promise.all([this.turn.waitForExecutionEnd(), this.fullCompaction.waitForExecutionEnd()]).then(() => void 0);
270324
+ }
270113
270325
  const waitForExecution = this.experimentalFlags.enabled("queue_policies") && payload.turnId !== void 0 && payload.turnId === this.turn.currentId;
270114
270326
  if (this.turn.hasActiveTurn) this.telemetry.track("cancel", { from: "streaming" });
270115
270327
  this.turn.cancel(payload.turnId, payload.cancellationReason === "timeout" ? new DOMException("Prompt execution timed out", "TimeoutError") : void 0);
@@ -335322,7 +335534,10 @@ async function appendSessionIndexEntry(homeDir, entry) {
335322
335534
  recursive: true,
335323
335535
  mode: 448
335324
335536
  });
335325
- await appendFile(indexPath, `${JSON.stringify(entry)}\n`, "utf-8");
335537
+ await appendFile(indexPath, `${JSON.stringify(entry)}\n`, {
335538
+ encoding: "utf-8",
335539
+ mode: 384
335540
+ });
335326
335541
  }
335327
335542
  async function readSessionIndex(homeDir, sessionsDir) {
335328
335543
  let raw;
@@ -343390,12 +343605,14 @@ let SessionService = class SessionService extends Disposable {
343390
343605
  sessionId: id,
343391
343606
  agentId: "main",
343392
343607
  expectedScope: request.scope,
343393
- turnId: request.turn_id
343608
+ turnId: request.turn_id,
343609
+ graceful: request.graceful
343394
343610
  });
343395
343611
  return {
343396
343612
  session_id: id,
343397
343613
  scope: request.scope,
343398
343614
  turn_id: request.turn_id,
343615
+ graceful: request.graceful,
343399
343616
  settled: true
343400
343617
  };
343401
343618
  }
@@ -346436,13 +346653,14 @@ var Session = class {
346436
346653
  this.ensureOpen();
346437
346654
  await this.trackLocalInputRequest(() => this.rpc.cancel({ sessionId: this.id }));
346438
346655
  }
346439
- async cancelTurn(turnId, expectedScope) {
346656
+ async cancelTurn(turnId, expectedScope, graceful) {
346440
346657
  this.ensureOpen();
346441
346658
  if (!Number.isSafeInteger(turnId) || turnId < 0) throw new Error("INVALID_TURN_ID");
346442
346659
  await this.trackLocalInputRequest(() => this.rpc.cancelTurn({
346443
346660
  sessionId: this.id,
346444
346661
  turnId,
346445
- expectedScope
346662
+ expectedScope,
346663
+ graceful
346446
346664
  }));
346447
346665
  }
346448
346666
  async setModel(model, options) {
@@ -347917,7 +348135,8 @@ var SDKRpcClientBase = class {
347917
348135
  sessionId: input.sessionId,
347918
348136
  agentId,
347919
348137
  turnId: input.turnId,
347920
- expectedScope: input.expectedScope
348138
+ expectedScope: input.expectedScope,
348139
+ graceful: input.graceful
347921
348140
  });
347922
348141
  }
347923
348142
  async registerTool(input) {
@@ -350223,7 +350442,7 @@ function optionalBuildString(value) {
350223
350442
  return typeof value === "string" && value.length > 0 ? value : void 0;
350224
350443
  }
350225
350444
  const BLUN_BUILD_INFO = {
350226
- version: optionalBuildString("9.1.640"),
350445
+ version: optionalBuildString("9.1.643"),
350227
350446
  channel: typeof __BLUN_CHANNEL__ === "string" ? optionalBuildString(__BLUN_CHANNEL__) : void 0,
350228
350447
  commit: typeof __BLUN_COMMIT__ === "string" ? optionalBuildString(__BLUN_COMMIT__) : void 0,
350229
350448
  buildTarget: typeof __BLUN_BUILD_TARGET__ === "string" ? optionalBuildString(__BLUN_BUILD_TARGET__) : void 0