@deepagents/context 7.10.0 → 7.10.2

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/dist/index.js CHANGED
@@ -158,7 +158,6 @@ import {
158
158
  import { styleText } from "node:util";
159
159
  import z from "zod";
160
160
  import {
161
- createRepairToolCall,
162
161
  withHostOnlyToolMetadata
163
162
  } from "@deepagents/agent";
164
163
 
@@ -387,10 +386,7 @@ var Agent = class _Agent {
387
386
  runtimeContext: this.#options.runtimeContext,
388
387
  model: this.#options.model,
389
388
  instructions: systemPrompt,
390
- messages: await convertToModelMessages(messages, {
391
- ignoreIncompleteToolCalls: true,
392
- tools: this.tools
393
- }),
389
+ messages: await toModelPrompt(messages, this.tools),
394
390
  stopWhen: this.#options.stopWhen ?? DEFAULT_STOP_WHEN,
395
391
  prepareStep: this.#withPrepareStep(
396
392
  this.#options.context.createReminderSession({
@@ -402,10 +398,6 @@ var Agent = class _Agent {
402
398
  tools: this.tools,
403
399
  toolsContext: options?.toolsContext,
404
400
  experimental_toolCallers: this.#options.experimental_toolCallers,
405
- repairToolCall: createRepairToolCall(
406
- this.#options.model,
407
- options?.abortSignal
408
- ),
409
401
  toolChoice: this.#options.toolChoice
410
402
  });
411
403
  }
@@ -508,11 +500,7 @@ var Agent = class _Agent {
508
500
  runtimeContext: this.#options.runtimeContext,
509
501
  model,
510
502
  instructions: systemPrompt,
511
- messages: await convertToModelMessages(messages, {
512
- ignoreIncompleteToolCalls: true,
513
- tools: this.tools
514
- }),
515
- repairToolCall: createRepairToolCall(model, config?.abortSignal),
503
+ messages: await toModelPrompt(messages, this.tools),
516
504
  stopWhen: this.#options.stopWhen ?? DEFAULT_STOP_WHEN,
517
505
  prepareStep,
518
506
  experimental_transform: config?.transform ?? smoothStream(),
@@ -792,15 +780,8 @@ function structuredOutput(options) {
792
780
  telemetry: options.telemetry,
793
781
  model: options.model,
794
782
  instructions: systemPrompt,
795
- messages: await convertToModelMessages(messages, {
796
- ignoreIncompleteToolCalls: true,
797
- tools
798
- }),
783
+ messages: await toModelPrompt(messages, tools),
799
784
  stopWhen: options.stopWhen ?? DEFAULT_STOP_WHEN,
800
- repairToolCall: createRepairToolCall(
801
- options.model,
802
- callOptions?.abortSignal
803
- ),
804
785
  toolsContext: callOptions?.toolsContext,
805
786
  output: Output.object({ schema: options.schema }),
806
787
  tools
@@ -830,14 +811,7 @@ function structuredOutput(options) {
830
811
  telemetry: options.telemetry,
831
812
  model: options.model,
832
813
  instructions: systemPrompt,
833
- repairToolCall: createRepairToolCall(
834
- options.model,
835
- callOptions?.abortSignal
836
- ),
837
- messages: await convertToModelMessages(messages, {
838
- ignoreIncompleteToolCalls: true,
839
- tools
840
- }),
814
+ messages: await toModelPrompt(messages, tools),
841
815
  stopWhen: options.stopWhen ?? DEFAULT_STOP_WHEN,
842
816
  experimental_transform: callOptions?.transform ?? smoothStream(),
843
817
  toolsContext: callOptions?.toolsContext,
@@ -847,6 +821,44 @@ function structuredOutput(options) {
847
821
  }
848
822
  };
849
823
  }
824
+ async function toModelPrompt(messages, tools) {
825
+ return withReasoningItemsOnce(
826
+ await convertToModelMessages(messages, {
827
+ ignoreIncompleteToolCalls: true,
828
+ tools
829
+ })
830
+ );
831
+ }
832
+ function withReasoningItemsOnce(messages) {
833
+ const contentByItemId = /* @__PURE__ */ new Map();
834
+ return messages.flatMap((message2) => {
835
+ if (message2.role !== "assistant" || typeof message2.content === "string") {
836
+ return [message2];
837
+ }
838
+ const content = [];
839
+ for (const part of message2.content) {
840
+ const itemId = reasoningItemIdOf2(part);
841
+ const owner = itemId === void 0 ? void 0 : contentByItemId.get(itemId);
842
+ if (itemId === void 0) {
843
+ content.push(part);
844
+ } else if (owner === void 0) {
845
+ contentByItemId.set(itemId, content);
846
+ content.push(part);
847
+ } else {
848
+ const lastOfItem = owner.findLastIndex(
849
+ (other) => reasoningItemIdOf2(other) === itemId
850
+ );
851
+ owner.splice(lastOfItem + 1, 0, part);
852
+ }
853
+ }
854
+ return content.length === 0 ? [] : [{ ...message2, content }];
855
+ });
856
+ }
857
+ function reasoningItemIdOf2(part) {
858
+ if (part.type !== "reasoning") return void 0;
859
+ const itemId = part.providerOptions?.openai?.itemId;
860
+ return typeof itemId === "string" ? itemId : void 0;
861
+ }
850
862
  function chunkId(chunk) {
851
863
  if (typeof chunk !== "object" || chunk === null || !("id" in chunk)) {
852
864
  return void 0;
@@ -876,6 +888,7 @@ function writeText(writer, text3, openPartId) {
876
888
  import {
877
889
  APICallError as APICallError2,
878
890
  InvalidToolInputError,
891
+ NoOutputGeneratedError,
879
892
  NoSuchToolError,
880
893
  ToolCallRepairError,
881
894
  createUIMessageStream as createUIMessageStream2,
@@ -4194,8 +4207,10 @@ var OpenChat = class {
4194
4207
  var ContextEngine = class _ContextEngine {
4195
4208
  /** Non-message fragments (role, hints, etc.) - not persisted in graph */
4196
4209
  #fragments = [];
4197
- /** Pending message fragments to be added to graph */
4210
+ /** Message fragments not yet committed to the graph, including those a save() is writing */
4198
4211
  #pendingMessages = [];
4212
+ /** Pending fragments an in-flight save() is writing; they stay pending until it commits */
4213
+ #savingMessages = /* @__PURE__ */ new Set();
4199
4214
  #store;
4200
4215
  #chatId;
4201
4216
  #userId;
@@ -4402,19 +4417,19 @@ var ContextEngine = class _ContextEngine {
4402
4417
  */
4403
4418
  async getMessages() {
4404
4419
  const open3 = await this.#open();
4420
+ const headMessageId = open3.branch.headMessageId;
4421
+ const pending = [...this.#pendingMessages];
4405
4422
  const messages = [];
4406
4423
  const indexById = /* @__PURE__ */ new Map();
4407
- if (open3.branch.headMessageId) {
4408
- const chain = await this.#store.getMessageChain(
4409
- open3.branch.headMessageId
4410
- );
4424
+ if (headMessageId) {
4425
+ const chain = await this.#store.getMessageChain(headMessageId);
4411
4426
  for (const msg of chain) {
4412
4427
  const data = requireUIMessage(msg.data, `Stored message "${msg.id}"`);
4413
4428
  if (isEmptyAssistantPlaceholder(data)) continue;
4414
4429
  indexById.set(data.id, messages.push(data) - 1);
4415
4430
  }
4416
4431
  }
4417
- for (const fragment2 of this.#pendingMessages) {
4432
+ for (const fragment2 of pending) {
4418
4433
  if (!fragment2.codec) {
4419
4434
  throw new Error(`Fragment "${fragment2.name}" is missing codec.`);
4420
4435
  }
@@ -4533,6 +4548,9 @@ var ContextEngine = class _ContextEngine {
4533
4548
  * Each message is added as a node with parentId pointing to the previous message.
4534
4549
  * The branch head is updated to point to the last message.
4535
4550
  *
4551
+ * The messages stay pending until the head commits, so `getMessages()`
4552
+ * during the save still returns them; a failed save leaves them pending.
4553
+ *
4536
4554
  * @example
4537
4555
  * ```ts
4538
4556
  * context.set(user('Hello'));
@@ -4543,11 +4561,14 @@ var ContextEngine = class _ContextEngine {
4543
4561
  */
4544
4562
  async save(options) {
4545
4563
  const open3 = await this.#open();
4546
- if (this.#pendingMessages.length === 0) {
4564
+ const taken = this.#pendingMessages.filter(
4565
+ (fragment2) => !this.#savingMessages.has(fragment2)
4566
+ );
4567
+ if (taken.length === 0) {
4547
4568
  return { headMessageId: open3.branch.headMessageId ?? void 0 };
4548
4569
  }
4549
- const pending = this.#pendingMessages;
4550
- this.#pendingMessages = [];
4570
+ for (const fragment2 of taken) this.#savingMessages.add(fragment2);
4571
+ const pending = [...taken];
4551
4572
  const pipeline = new SavePipeline(
4552
4573
  this.#asSavePipelineEngine(open3),
4553
4574
  pending,
@@ -4556,10 +4577,14 @@ var ContextEngine = class _ContextEngine {
4556
4577
  try {
4557
4578
  await pipeline.applyUpdateBranching();
4558
4579
  await this.#foldUserReminders(pending);
4559
- return await pipeline.persist();
4560
- } catch (error) {
4561
- this.#pendingMessages.unshift(...pending);
4562
- throw error;
4580
+ const result = await pipeline.persist();
4581
+ const committed = new Set(taken);
4582
+ this.#pendingMessages = this.#pendingMessages.filter(
4583
+ (fragment2) => !committed.has(fragment2)
4584
+ );
4585
+ return result;
4586
+ } finally {
4587
+ for (const fragment2 of taken) this.#savingMessages.delete(fragment2);
4563
4588
  }
4564
4589
  }
4565
4590
  /**
@@ -5878,7 +5903,12 @@ async function chat(agent2, ...args) {
5878
5903
  };
5879
5904
  const message2 = Object.keys(mergedMetadata).length > 0 ? { ...settled, metadata: mergedMetadata } : settled;
5880
5905
  await writeAssistantSegment(message2);
5881
- const usage = await result?.result.usage;
5906
+ const usage = await Promise.resolve(result?.result.usage).catch(
5907
+ (error) => {
5908
+ if (NoOutputGeneratedError.isInstance(error)) return void 0;
5909
+ throw error;
5910
+ }
5911
+ );
5882
5912
  if (usage !== void 0) {
5883
5913
  await context.trackUsage(usage);
5884
5914
  }
@@ -7192,9 +7222,6 @@ function render(tag, ...fragments) {
7192
7222
  return renderer.render([wrapped]);
7193
7223
  }
7194
7224
 
7195
- // packages/context/src/index.ts
7196
- import { createRepairToolCall as createRepairToolCall2 } from "@deepagents/agent";
7197
-
7198
7225
  // packages/context/src/lib/sandbox/apple-container-sandbox.ts
7199
7226
  import { TemporaryFiles } from "@zukhruf/fs";
7200
7227
  import spawn, { SubprocessError } from "nano-spawn";
@@ -8572,6 +8599,7 @@ var BashException = class extends Error {
8572
8599
  };
8573
8600
 
8574
8601
  // packages/context/src/lib/sandbox/bash-tool.ts
8602
+ import { experimental_createBashTool } from "@ai-sdk/tool-bash";
8575
8603
  import { tool as tool3 } from "ai";
8576
8604
  import fg from "fast-glob";
8577
8605
  import { BashTransformPipeline, TeePlugin } from "just-bash";
@@ -8766,6 +8794,14 @@ function createReadFileTool({
8766
8794
  });
8767
8795
  }
8768
8796
 
8797
+ // packages/context/src/lib/sandbox/types.ts
8798
+ var SandboxNotFoundError = class extends Error {
8799
+ constructor(sandbox, options) {
8800
+ super(`The sandbox "${sandbox}" no longer exists.`, options);
8801
+ this.name = "SandboxNotFoundError";
8802
+ }
8803
+ };
8804
+
8769
8805
  // packages/context/src/lib/sandbox/bash-tool.ts
8770
8806
  var DEFAULT_MAX_FILES = 1e3;
8771
8807
  var DEFAULT_MAX_OUTPUT_LENGTH = 3e4;
@@ -8773,12 +8809,10 @@ var TEE_OUTPUT_DIR = "/tmp/bash-tool";
8773
8809
  var MAX_CONCURRENT_WRITES = 20;
8774
8810
  var COMMAND_TIMEOUT_EXIT_CODE = 124;
8775
8811
  var REASONING_INSTRUCTION = 'Every bash tool call must include a brief non-empty "reasoning" input explaining why the command is needed.';
8776
- function truncateOutput(output, maxLength, streamName) {
8812
+ function truncateOutput(output, maxLength) {
8777
8813
  if (output.length <= maxLength) return output;
8778
- const removed = output.length - maxLength;
8779
8814
  return `${output.slice(0, maxLength)}
8780
-
8781
- [${streamName} truncated: ${removed} characters removed]`;
8815
+ [Output truncated: ${output.length - maxLength} characters omitted.]`;
8782
8816
  }
8783
8817
  function makeTeeScriptPortable(script) {
8784
8818
  const withoutStatusAssignments = script.replace(
@@ -8832,37 +8866,22 @@ async function uploadInitialFiles(sandbox, workingDirectory, files) {
8832
8866
  );
8833
8867
  }
8834
8868
  }
8835
- function createBashDescription(options) {
8836
- return [
8837
- "Run Bash commands in the sandbox. " + (options.workingDirectory !== void 0 ? `Every command starts in ${options.workingDirectory}. ` : "Commands run in the sandbox's default working directory. ") + "Use ls to discover files and commands such as cat, grep, sort, awk, and jq to inspect and transform them. Pipes and redirections are supported. Returns stdout, stderr, and exitCode; long output is truncated.",
8838
- options.sandboxDescription,
8839
- options.experimentalTeeTransform && `Pipeline stdout is captured under ${TEE_OUTPUT_DIR}/. Use the returned teeFiles paths to inspect full intermediate output.`,
8840
- options.extraInstructions,
8841
- REASONING_INSTRUCTION
8842
- ].filter(Boolean).join("\n\n");
8843
- }
8844
8869
  async function createBashTool(options) {
8845
8870
  const { workingDirectory, sandbox } = options;
8846
8871
  const initialFiles = await listInitialFiles(options);
8847
- if (workingDirectory !== void 0) {
8848
- const created = await sandbox.run({
8849
- command: `mkdir -p -- ${shellQuote(workingDirectory)}`
8850
- });
8851
- if (created.exitCode !== 0) {
8852
- throw new Error(
8853
- `Could not set up working directory ${workingDirectory}: ${created.stderr}`
8854
- );
8855
- }
8856
- }
8872
+ const aiSdkBash = await experimental_createBashTool({
8873
+ sandbox,
8874
+ workingDirectory
8875
+ });
8857
8876
  await uploadInitialFiles(sandbox, workingDirectory, initialFiles);
8858
8877
  const experimentalTeeTransform = options.experimentalTeeTransform ?? false;
8859
8878
  const bash = tool3({
8860
- description: createBashDescription({
8861
- workingDirectory,
8862
- sandboxDescription: sandbox.description,
8863
- extraInstructions: options.extraInstructions,
8864
- experimentalTeeTransform
8865
- }),
8879
+ description: [
8880
+ aiSdkBash.description,
8881
+ experimentalTeeTransform && `Pipeline stdout is captured under ${TEE_OUTPUT_DIR}/. Use the returned teeFiles paths to inspect full intermediate output.`,
8882
+ options.extraInstructions,
8883
+ REASONING_INSTRUCTION
8884
+ ].filter(Boolean).join("\n\n"),
8866
8885
  inputSchema: z12.object({
8867
8886
  command: z12.string().describe("The bash command to execute"),
8868
8887
  reasoning: z12.string().trim().min(1).describe("Brief reason for executing this command")
@@ -8911,8 +8930,8 @@ async function createBashTool(options) {
8911
8930
  const maxOutputLength = options.maxOutputLength ?? DEFAULT_MAX_OUTPUT_LENGTH;
8912
8931
  result = {
8913
8932
  ...result,
8914
- stdout: truncateOutput(result.stdout, maxOutputLength, "stdout"),
8915
- stderr: truncateOutput(result.stderr, maxOutputLength, "stderr"),
8933
+ stdout: truncateOutput(result.stdout, maxOutputLength),
8934
+ stderr: truncateOutput(result.stderr, maxOutputLength),
8916
8935
  ...teeFiles ? { teeFiles } : {}
8917
8936
  };
8918
8937
  const executionMeta = result.meta;
@@ -9511,6 +9530,10 @@ var DockerContainer = class {
9511
9530
  this.#execOnly = layout.execOnly;
9512
9531
  this.#autoRemove = autoRemove;
9513
9532
  }
9533
+ /** A removed container is a sandbox that no longer exists, whichever request finds it. */
9534
+ #notFound(error) {
9535
+ return error instanceof ContainerNotFoundError ? new SandboxNotFoundError(this.name, { cause: error }) : error;
9536
+ }
9514
9537
  #config(argv, { workingDirectory, env = {} }) {
9515
9538
  return {
9516
9539
  Cmd: argv,
@@ -9526,16 +9549,23 @@ var DockerContainer = class {
9526
9549
  );
9527
9550
  return { stdout, stderr, exitCode };
9528
9551
  } catch (error) {
9552
+ if (error instanceof ContainerNotFoundError) {
9553
+ throw this.#notFound(error);
9554
+ }
9529
9555
  if (!(error instanceof DockerError)) throw error;
9530
9556
  return { stdout: "", stderr: error.message, exitCode: 1 };
9531
9557
  }
9532
9558
  }
9533
9559
  async spawn(argv, options) {
9534
- return engineProcess2(
9535
- await this.#container.spawn(this.#config(argv, options), {
9536
- stdin: options.stdin
9537
- })
9538
- );
9560
+ try {
9561
+ return engineProcess2(
9562
+ await this.#container.spawn(this.#config(argv, options), {
9563
+ stdin: options.stdin
9564
+ })
9565
+ );
9566
+ } catch (error) {
9567
+ throw this.#notFound(error);
9568
+ }
9539
9569
  }
9540
9570
  #resolve(path6) {
9541
9571
  return posix3.resolve(this.workdir, path6);
@@ -9556,7 +9586,23 @@ var DockerContainer = class {
9556
9586
  target = posix3.resolve(posix3.dirname(target), stat.linkTarget);
9557
9587
  }
9558
9588
  }
9589
+ async #isLinkOrUnstatable(path6, signal) {
9590
+ try {
9591
+ const stat = await this.#container.stat(path6, { signal });
9592
+ return stat !== void 0 && stat.linkTarget !== "";
9593
+ } catch (error) {
9594
+ if (isUnexplainedFailure(error)) return true;
9595
+ throw this.#notFound(error);
9596
+ }
9597
+ }
9559
9598
  async readFile(path6, signal) {
9599
+ try {
9600
+ return await this.#readFile(path6, signal);
9601
+ } catch (error) {
9602
+ throw this.#notFound(error);
9603
+ }
9604
+ }
9605
+ async #readFile(path6, signal) {
9560
9606
  const target = this.#resolve(path6);
9561
9607
  if (this.#isExecOnly(target)) {
9562
9608
  return readFileOverExec(this, target, signal);
@@ -9590,7 +9636,7 @@ var DockerContainer = class {
9590
9636
  }
9591
9637
  async writeFile(path6, content, signal) {
9592
9638
  const target = this.#resolve(path6);
9593
- if (this.#isExecOnly(target)) {
9639
+ if (this.#isExecOnly(target) || await this.#isLinkOrUnstatable(target, signal)) {
9594
9640
  return writeFileOverExec(this, target, content, signal);
9595
9641
  }
9596
9642
  try {
@@ -9599,6 +9645,7 @@ var DockerContainer = class {
9599
9645
  copyUIDGID: true
9600
9646
  });
9601
9647
  } catch (error) {
9648
+ if (error instanceof ContainerNotFoundError) throw this.#notFound(error);
9602
9649
  throw new Error(`Failed to write file "${path6}": ${messageOf(error)}`, {
9603
9650
  cause: error
9604
9651
  });
@@ -12910,60 +12957,94 @@ var StreamStore = class {
12910
12957
  };
12911
12958
 
12912
12959
  // packages/context/src/lib/stream-buffer.ts
12960
+ var MAX_QUEUED_CHUNKS = 128;
12913
12961
  async function persistedWriter(options) {
12914
- const {
12915
- writer,
12916
- store,
12917
- streamId,
12918
- strategy = "buffered",
12919
- flushSize = 20
12920
- } = options;
12962
+ const { writer, store, streamId } = options;
12921
12963
  let seq = 0;
12922
- let buffer = [];
12964
+ let queue = [];
12965
+ let appending;
12966
+ let appendSettled = Promise.resolve();
12967
+ let failure;
12923
12968
  let failedByChunk = false;
12924
12969
  let abortedByChunk = false;
12925
- async function flush() {
12926
- if (buffer.length === 0) return;
12927
- const batch = buffer;
12928
- buffer = [];
12929
- await appendBatch(batch);
12930
- }
12931
- function makeChunk(part) {
12932
- return {
12933
- streamId,
12934
- seq: seq++,
12935
- data: part,
12936
- createdAt: Date.now()
12937
- };
12938
- }
12939
- async function appendBatch(batch) {
12940
- await store.appendChunks(batch);
12941
- failedByChunk ||= collectStreamFailures(batch).length > 0;
12942
- }
12943
- async function persistChunk(chunk) {
12944
- if (chunk.data.type === "abort") {
12945
- abortedByChunk = true;
12970
+ function enqueue(part, committed, failed) {
12971
+ if (failure) {
12972
+ failed(failure.error);
12973
+ return;
12946
12974
  }
12947
- if (strategy === "immediate") {
12948
- await appendBatch([chunk]);
12949
- } else {
12950
- buffer.push(chunk);
12951
- if (buffer.length >= flushSize || chunk.data.type.startsWith("data-")) {
12952
- await flush();
12975
+ queue.push({
12976
+ chunk: { streamId, seq: seq++, data: part, createdAt: Date.now() },
12977
+ committed,
12978
+ failed
12979
+ });
12980
+ appending ??= appendQueued();
12981
+ }
12982
+ async function appendQueued() {
12983
+ while (queue.length > 0) {
12984
+ const batch = queue;
12985
+ queue = [];
12986
+ const chunks = batch.map(({ chunk }) => chunk);
12987
+ const append = Promise.try(() => store.appendChunks(chunks));
12988
+ appendSettled = append.then(
12989
+ () => void 0,
12990
+ () => void 0
12991
+ );
12992
+ try {
12993
+ await append;
12994
+ } catch (error) {
12995
+ failure = { error };
12996
+ const rejected = [...batch, ...queue];
12997
+ queue = [];
12998
+ for (const entry of rejected) entry.failed(error);
12999
+ break;
12953
13000
  }
13001
+ failedByChunk ||= collectStreamFailures(chunks).length > 0;
13002
+ abortedByChunk ||= chunks.some(({ data }) => data.type === "abort");
13003
+ for (const entry of batch) entry.committed();
12954
13004
  }
13005
+ appending = void 0;
13006
+ }
13007
+ async function settle() {
13008
+ while (appending) await appending;
13009
+ }
13010
+ async function flush() {
13011
+ await settle();
13012
+ if (failure) throw failure.error;
12955
13013
  }
12956
13014
  const wrappedWriter = {
12957
13015
  onError: writer.onError,
12958
- async write(part) {
12959
- await persistChunk(makeChunk(part));
12960
- writer.write(part);
13016
+ write(part) {
13017
+ const { promise, resolve: resolve3, reject } = Promise.withResolvers();
13018
+ enqueue(
13019
+ part,
13020
+ () => {
13021
+ writer.write(part);
13022
+ resolve3();
13023
+ },
13024
+ reject
13025
+ );
13026
+ return promise;
12961
13027
  },
12962
13028
  merge(stream) {
13029
+ let cancelled = false;
12963
13030
  const transform = new TransformStream({
12964
- async transform(chunk, controller) {
12965
- await persistChunk(makeChunk(chunk));
12966
- controller.enqueue(chunk);
13031
+ async transform(part, controller) {
13032
+ enqueue(
13033
+ part,
13034
+ () => {
13035
+ if (!cancelled) controller.enqueue(part);
13036
+ },
13037
+ (error) => {
13038
+ if (!cancelled) controller.error(error);
13039
+ }
13040
+ );
13041
+ while (queue.length >= MAX_QUEUED_CHUNKS && !failure) {
13042
+ await appendSettled;
13043
+ }
13044
+ },
13045
+ flush: () => flush(),
13046
+ cancel() {
13047
+ cancelled = true;
12967
13048
  }
12968
13049
  });
12969
13050
  writer.merge(stream.pipeThrough(transform));
@@ -12982,7 +13063,7 @@ async function persistedWriter(options) {
12982
13063
  );
12983
13064
  },
12984
13065
  async fail(error) {
12985
- await flush();
13066
+ await settle();
12986
13067
  if (failedByChunk) return;
12987
13068
  await store.updateStreamStatus(streamId, "failed", { error });
12988
13069
  },
@@ -12993,105 +13074,27 @@ async function persistedWriter(options) {
12993
13074
  }
12994
13075
 
12995
13076
  // packages/context/src/lib/stream/polling-change-source.ts
13077
+ import { Backoff } from "@zukhruf/async";
12996
13078
  import { setTimeout as delay2 } from "node:timers/promises";
12997
-
12998
- // packages/context/src/lib/stream/polling-policy.ts
12999
- var DEFAULT_WATCH_POLLING = {
13000
- minMs: 25,
13001
- maxMs: 500,
13002
- multiplier: 2,
13003
- jitterRatio: 0.15,
13004
- statusCheckEvery: 3
13005
- };
13006
- var DEFAULT_CANCEL_POLLING = {
13007
- minMs: 50,
13008
- maxMs: 500,
13009
- multiplier: 2,
13010
- jitterRatio: 0.15
13011
- };
13012
- function normalizeWatchPolling(polling, fallback = DEFAULT_WATCH_POLLING) {
13013
- const merged = {
13014
- ...fallback,
13015
- ...polling
13016
- };
13017
- const normalizedBase = normalizeAdaptivePolling(merged, fallback);
13018
- return {
13019
- ...normalizedBase,
13020
- statusCheckEvery: clampInt(merged.statusCheckEvery, 1, 1e4)
13021
- };
13022
- }
13023
- function normalizeCancelPolling(polling, fallback = DEFAULT_CANCEL_POLLING) {
13024
- return normalizeAdaptivePolling(polling, fallback);
13025
- }
13026
- function createAdaptivePollingState(config) {
13027
- return {
13028
- config,
13029
- currentMs: config.minMs
13030
- };
13031
- }
13032
- function resetAdaptivePolling(state) {
13033
- state.currentMs = state.config.minMs;
13034
- }
13035
- function nextAdaptivePollingDelay(state) {
13036
- const current = clampInt(
13037
- state.currentMs,
13038
- state.config.minMs,
13039
- state.config.maxMs
13040
- );
13041
- const delay4 = applyJitter(
13042
- current,
13043
- state.config.jitterRatio,
13044
- state.config.minMs,
13045
- state.config.maxMs
13046
- );
13047
- state.currentMs = clampInt(
13048
- Math.ceil(current * state.config.multiplier),
13049
- state.config.minMs,
13050
- state.config.maxMs
13051
- );
13052
- return delay4;
13053
- }
13054
- function normalizeAdaptivePolling(polling, fallback) {
13055
- const merged = {
13056
- ...fallback,
13057
- ...polling
13058
- };
13059
- const minMs = clampInt(merged.minMs, 1, 6e4);
13060
- const maxMs = clampInt(merged.maxMs, minMs, 6e4);
13061
- return {
13062
- minMs,
13063
- maxMs,
13064
- multiplier: clampFloat(merged.multiplier, 1, 10),
13065
- jitterRatio: clampFloat(merged.jitterRatio, 0, 1)
13066
- };
13067
- }
13068
- function applyJitter(value, jitterRatio, min, max) {
13069
- if (jitterRatio <= 0) return value;
13070
- const radius = value * jitterRatio;
13071
- const lowerBound = Math.max(0, value - radius);
13072
- const upperBound = value + radius;
13073
- const jittered = Math.round(
13074
- lowerBound + Math.random() * (upperBound - lowerBound)
13075
- );
13076
- return clampInt(jittered, min, max);
13077
- }
13078
- function clampInt(value, min, max) {
13079
- if (!Number.isFinite(value)) return min;
13080
- return Math.min(max, Math.max(min, Math.round(value)));
13081
- }
13082
- function clampFloat(value, min, max) {
13083
- if (!Number.isFinite(value)) return min;
13084
- return Math.min(max, Math.max(min, value));
13085
- }
13086
-
13087
- // packages/context/src/lib/stream/polling-change-source.ts
13088
13079
  var PollingChangeSource = class {
13089
13080
  #reads;
13090
- #config;
13081
+ #backoff;
13082
+ #statusCheckEvery;
13091
13083
  #onPoll;
13092
13084
  constructor(options) {
13085
+ const statusCheckEvery = options.statusCheckEvery ?? 3;
13086
+ if (!(Number.isInteger(statusCheckEvery) && statusCheckEvery >= 1))
13087
+ throw new RangeError(
13088
+ `statusCheckEvery must be a positive integer, not ${statusCheckEvery}`
13089
+ );
13093
13090
  this.#reads = options.reads;
13094
- this.#config = normalizeWatchPolling(options.config, DEFAULT_WATCH_POLLING);
13091
+ this.#backoff = options.backoff ?? new Backoff({
13092
+ initial: 25,
13093
+ multiplier: 2,
13094
+ max: 500,
13095
+ jitter: { kind: "ratio", ratio: 0.15 }
13096
+ });
13097
+ this.#statusCheckEvery = statusCheckEvery;
13095
13098
  this.#onPoll = options.onPoll;
13096
13099
  }
13097
13100
  async *subscribe(streamId, signal) {
@@ -13101,15 +13104,15 @@ var PollingChangeSource = class {
13101
13104
  }
13102
13105
  yield { kind: "tick" };
13103
13106
  if (isTerminal(initialStatus)) return;
13104
- const delayState = createAdaptivePollingState(this.#config);
13107
+ let retries = 0;
13105
13108
  let pollsSinceStatus = 0;
13106
13109
  let lastStatus = initialStatus;
13107
13110
  while (!signal.aborted) {
13108
- const delayMs = nextAdaptivePollingDelay(delayState);
13111
+ const delayMs = this.#backoff.duration(retries++);
13109
13112
  this.#emit({ type: "idle", streamId, delayMs });
13110
13113
  if (!await waitForDelay(delayMs, signal)) return;
13111
13114
  pollsSinceStatus += 1;
13112
- const shouldCheckStatus = pollsSinceStatus >= this.#config.statusCheckEvery;
13115
+ const shouldCheckStatus = pollsSinceStatus >= this.#statusCheckEvery;
13113
13116
  if (!shouldCheckStatus) {
13114
13117
  yield { kind: "chunks" };
13115
13118
  continue;
@@ -13127,7 +13130,7 @@ var PollingChangeSource = class {
13127
13130
  return;
13128
13131
  }
13129
13132
  if (status === "running" && lastStatus !== "running") {
13130
- resetAdaptivePolling(delayState);
13133
+ retries = 0;
13131
13134
  }
13132
13135
  lastStatus = status;
13133
13136
  if (isTerminal(status)) {
@@ -14053,8 +14056,16 @@ var SqliteStreamStore = class extends StreamStore {
14053
14056
  };
14054
14057
 
14055
14058
  // packages/context/src/lib/stream/stream-manager.ts
14059
+ import { Backoff as Backoff2 } from "@zukhruf/async";
14056
14060
  import { createUIMessageStream as createUIMessageStream3 } from "ai";
14057
14061
  import { setTimeout as delay3 } from "node:timers/promises";
14062
+ var CANCEL_WATCHER_RETRY_MAX_MS = 500;
14063
+ var CANCEL_WATCHER_RETRY = new Backoff2({
14064
+ initial: 50,
14065
+ multiplier: 2,
14066
+ max: CANCEL_WATCHER_RETRY_MAX_MS,
14067
+ jitter: { kind: "ratio", ratio: 0.15 }
14068
+ });
14058
14069
  function isTerminal3(status) {
14059
14070
  return status !== "queued" && status !== "running";
14060
14071
  }
@@ -14137,9 +14148,7 @@ var StreamManager = class {
14137
14148
  pw = await persistedWriter({
14138
14149
  writer,
14139
14150
  store: this.#store,
14140
- streamId,
14141
- strategy: options?.strategy,
14142
- flushSize: options?.flushSize
14151
+ streamId
14143
14152
  });
14144
14153
  pw.writer.merge(stream);
14145
14154
  }
@@ -14183,7 +14192,7 @@ var StreamManager = class {
14183
14192
  ac.abort();
14184
14193
  await this.#notifyCancellation(streamId, options);
14185
14194
  };
14186
- const retryState = createAdaptivePollingState(DEFAULT_CANCEL_POLLING);
14195
+ let retries = 0;
14187
14196
  const listeners = this.#localCancellationListeners.get(streamId) ?? /* @__PURE__ */ new Set();
14188
14197
  listeners.add(detect);
14189
14198
  this.#localCancellationListeners.set(streamId, listeners);
@@ -14206,8 +14215,8 @@ var StreamManager = class {
14206
14215
  streamId,
14207
14216
  ac.signal
14208
14217
  )) {
14209
- if (!subscriptionStabilized && Date.now() - subscribedAt >= DEFAULT_CANCEL_POLLING.maxMs) {
14210
- resetAdaptivePolling(retryState);
14218
+ if (!subscriptionStabilized && Date.now() - subscribedAt >= CANCEL_WATCHER_RETRY_MAX_MS) {
14219
+ retries = 0;
14211
14220
  subscriptionStabilized = true;
14212
14221
  }
14213
14222
  if (change.kind === "chunks") continue;
@@ -14225,7 +14234,10 @@ var StreamManager = class {
14225
14234
  } catch {
14226
14235
  if (ac.signal.aborted || detected) return;
14227
14236
  }
14228
- if (!await waitForDelay2(nextAdaptivePollingDelay(retryState), ac.signal)) {
14237
+ if (!await waitForDelay2(
14238
+ CANCEL_WATCHER_RETRY.duration(retries++),
14239
+ ac.signal
14240
+ )) {
14229
14241
  return;
14230
14242
  }
14231
14243
  }
@@ -14470,9 +14482,7 @@ export {
14470
14482
  ContextEngine,
14471
14483
  ContextRenderer,
14472
14484
  ContextStore,
14473
- DEFAULT_CANCEL_POLLING,
14474
14485
  DEFAULT_STOP_WHEN,
14475
- DEFAULT_WATCH_POLLING,
14476
14486
  DaytonaCreationError,
14477
14487
  DaytonaSandboxError,
14478
14488
  DockerEngine,
@@ -14507,6 +14517,7 @@ export {
14507
14517
  PostgresStreamStore,
14508
14518
  PostgresTransaction,
14509
14519
  RuntimeStrategy,
14520
+ SandboxNotFoundError,
14510
14521
  SearchQuerySyntaxError,
14511
14522
  SqlServerContextStore,
14512
14523
  SqliteContextStore,
@@ -14553,7 +14564,6 @@ export {
14553
14564
  contentMatches,
14554
14565
  contentPattern,
14555
14566
  correction,
14556
- createAdaptivePollingState,
14557
14567
  createAppleContainerSandbox,
14558
14568
  createBashTool,
14559
14569
  createBinaryBridges,
@@ -14561,7 +14571,6 @@ export {
14561
14571
  createDockerSandbox,
14562
14572
  createInstallerContext,
14563
14573
  createMicrosandboxSandbox,
14564
- createRepairToolCall2 as createRepairToolCall,
14565
14574
  createVirtualSandbox,
14566
14575
  dateReminder,
14567
14576
  dayChanged,
@@ -14620,9 +14629,6 @@ export {
14620
14629
  message,
14621
14630
  monthChanged,
14622
14631
  monthReminder,
14623
- nextAdaptivePollingDelay,
14624
- normalizeCancelPolling,
14625
- normalizeWatchPolling,
14626
14632
  not,
14627
14633
  npm,
14628
14634
  nullUsage,
@@ -14644,7 +14650,6 @@ export {
14644
14650
  reminder,
14645
14651
  render,
14646
14652
  repairQuotedArg,
14647
- resetAdaptivePolling,
14648
14653
  resolveReminder,
14649
14654
  resolveReminderAsync,
14650
14655
  resolveTz,