@deepagents/context 7.5.1 → 7.6.0

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.
Files changed (55) hide show
  1. package/README.md +7 -5
  2. package/dist/index.js +1171 -1066
  3. package/dist/index.js.map +4 -4
  4. package/dist/lib/agent.d.ts.map +1 -1
  5. package/dist/lib/fragments/plan-shared.d.ts.map +1 -1
  6. package/dist/lib/sandbox/apple-container-sandbox.d.ts +2 -2
  7. package/dist/lib/sandbox/apple-container-sandbox.d.ts.map +1 -1
  8. package/dist/lib/sandbox/bash-tool.d.ts +0 -2
  9. package/dist/lib/sandbox/bash-tool.d.ts.map +1 -1
  10. package/dist/lib/sandbox/container-engine.d.ts +46 -14
  11. package/dist/lib/sandbox/container-engine.d.ts.map +1 -1
  12. package/dist/lib/sandbox/container-sandbox.d.ts.map +1 -1
  13. package/dist/lib/sandbox/container-session.d.ts +21 -0
  14. package/dist/lib/sandbox/container-session.d.ts.map +1 -0
  15. package/dist/lib/sandbox/daytona-sandbox.d.ts +3 -3
  16. package/dist/lib/sandbox/daytona-sandbox.d.ts.map +1 -1
  17. package/dist/lib/sandbox/docker-sandbox.d.ts +12 -13
  18. package/dist/lib/sandbox/docker-sandbox.d.ts.map +1 -1
  19. package/dist/lib/sandbox/legacy-sandbox.d.ts +8 -0
  20. package/dist/lib/sandbox/legacy-sandbox.d.ts.map +1 -0
  21. package/dist/lib/sandbox/microsandbox-sandbox.d.ts +6 -13
  22. package/dist/lib/sandbox/microsandbox-sandbox.d.ts.map +1 -1
  23. package/dist/lib/sandbox/read-file-tool/index.d.ts +2 -2
  24. package/dist/lib/sandbox/read-file-tool/index.d.ts.map +1 -1
  25. package/dist/lib/sandbox/read-file-tool/text.d.ts.map +1 -1
  26. package/dist/lib/sandbox/strace/file-changes.d.ts +22 -16
  27. package/dist/lib/sandbox/strace/file-changes.d.ts.map +1 -1
  28. package/dist/lib/sandbox/strace/index.d.ts +1 -1
  29. package/dist/lib/sandbox/strace/index.d.ts.map +1 -1
  30. package/dist/lib/sandbox/strace/index.js +7 -6
  31. package/dist/lib/sandbox/strace/index.js.map +2 -2
  32. package/dist/lib/sandbox/types.d.ts +26 -23
  33. package/dist/lib/sandbox/types.d.ts.map +1 -1
  34. package/dist/lib/sandbox/virtual-sandbox.d.ts +3 -3
  35. package/dist/lib/sandbox/virtual-sandbox.d.ts.map +1 -1
  36. package/dist/lib/stream/change-source.d.ts.map +1 -1
  37. package/dist/lib/telemetry/console-telemetry.d.ts +7 -1
  38. package/dist/lib/telemetry/console-telemetry.d.ts.map +1 -1
  39. package/dist/lib/telemetry/file/file-telemetry.d.ts +6 -0
  40. package/dist/lib/telemetry/file/file-telemetry.d.ts.map +1 -1
  41. package/dist/lib/telemetry/file/index.js +9 -5
  42. package/dist/lib/telemetry/file/index.js.map +2 -2
  43. package/dist/lib/telemetry/index.js +10 -6
  44. package/dist/lib/telemetry/index.js.map +2 -2
  45. package/dist/lib/telemetry/safe-serialize.d.ts +1 -1
  46. package/dist/lib/telemetry/safe-serialize.d.ts.map +1 -1
  47. package/dist/lib/tracing/batch-processor.d.ts +7 -1
  48. package/dist/lib/tracing/batch-processor.d.ts.map +1 -1
  49. package/dist/lib/tracing/index.js +24 -16
  50. package/dist/lib/tracing/index.js.map +2 -2
  51. package/dist/lib/tracing/openai-traces-integration.d.ts +9 -3
  52. package/dist/lib/tracing/openai-traces-integration.d.ts.map +1 -1
  53. package/package.json +19 -15
  54. package/dist/lib/sandbox/cli-process.d.ts +0 -35
  55. package/dist/lib/sandbox/cli-process.d.ts.map +0 -1
package/dist/index.js CHANGED
@@ -122,10 +122,10 @@ function nullUsage() {
122
122
  };
123
123
  }
124
124
  function mapGenerateErrorToCode(error) {
125
- if (error instanceof Error && error.name === "AbortError") {
125
+ if (Error.isError(error) && error.name === "AbortError") {
126
126
  return null;
127
127
  }
128
- if (error instanceof Error && error.name === "TimeoutError") {
128
+ if (Error.isError(error) && error.name === "TimeoutError") {
129
129
  return "execution_time_exceeded";
130
130
  }
131
131
  if (APICallError.isInstance(error)) {
@@ -385,6 +385,7 @@ var Agent = class _Agent {
385
385
  sandbox: this.#options.sandbox
386
386
  })
387
387
  ),
388
+ experimental_sandbox: this.#options.sandbox.sandbox,
388
389
  tools: this.tools,
389
390
  toolsContext: options?.toolsContext,
390
391
  experimental_toolCallers: this.#options.experimental_toolCallers,
@@ -502,6 +503,7 @@ var Agent = class _Agent {
502
503
  sandbox: this.#options.sandbox
503
504
  }),
504
505
  experimental_transform: config?.transform ?? smoothStream(),
506
+ experimental_sandbox: this.#options.sandbox.sandbox,
505
507
  tools: this.tools,
506
508
  toolsContext,
507
509
  experimental_toolCallers: this.#options.experimental_toolCallers,
@@ -619,7 +621,7 @@ var Agent = class _Agent {
619
621
  }
620
622
  },
621
623
  onError: (error) => {
622
- const message2 = error instanceof Error ? error.message : String(error);
624
+ const message2 = Error.isError(error) ? error.message : String(error);
623
625
  return `Stream failed: ${message2}`;
624
626
  }
625
627
  });
@@ -664,11 +666,11 @@ ${output}
664
666
  }
665
667
  return result.text;
666
668
  } catch (error) {
667
- if (error instanceof Error && error.name === "AbortError") {
669
+ if (Error.isError(error) && error.name === "AbortError") {
668
670
  throw error;
669
671
  }
670
672
  console.error(error);
671
- const details = error instanceof Error ? error.message : JSON.stringify(error);
673
+ const details = Error.isError(error) ? error.message : JSON.stringify(error);
672
674
  return `An error thrown from a tool call.
673
675
  <ErrorDetails>
674
676
  ${details}
@@ -838,7 +840,7 @@ function chunkId(chunk) {
838
840
  }
839
841
  return typeof chunk.id === "string" ? chunk.id : void 0;
840
842
  }
841
- function writeText(writer, text, openPartId) {
843
+ function writeText(writer, text3, openPartId) {
842
844
  const feedbackPartId = openPartId ?? generateId3();
843
845
  if (openPartId === void 0) {
844
846
  writer.write({
@@ -849,7 +851,7 @@ function writeText(writer, text, openPartId) {
849
851
  writer.write({
850
852
  id: feedbackPartId,
851
853
  type: "text-delta",
852
- delta: ` ${text}`
854
+ delta: ` ${text3}`
853
855
  });
854
856
  writer.write({
855
857
  id: feedbackPartId,
@@ -1245,12 +1247,12 @@ ${this.#indent(safe, 2)}
1245
1247
  }
1246
1248
  return value.replaceAll(/&/g, "&amp;").replaceAll(/</g, "&lt;").replaceAll(/>/g, "&gt;").replaceAll(/"/g, "&quot;").replaceAll(/'/g, "&apos;");
1247
1249
  }
1248
- #indent(text, spaces) {
1249
- if (!text.trim()) {
1250
+ #indent(text3, spaces) {
1251
+ if (!text3.trim()) {
1250
1252
  return "";
1251
1253
  }
1252
1254
  const padding = " ".repeat(spaces);
1253
- return text.split("\n").map((line) => line.length ? padding + line : padding).join("\n");
1255
+ return text3.split("\n").map((line) => line.length ? padding + line : padding).join("\n");
1254
1256
  }
1255
1257
  #leaf(tag, value, depth) {
1256
1258
  const safe = this.#escape(value);
@@ -1789,16 +1791,16 @@ function normalizeReminderTarget(target) {
1789
1791
  function normalizeConditionalReminderText(textOrFragment) {
1790
1792
  return isFragment(textOrFragment) ? new XmlRenderer().render([textOrFragment]) : textOrFragment;
1791
1793
  }
1792
- function stripTextByRanges(text, ranges) {
1794
+ function stripTextByRanges(text3, ranges) {
1793
1795
  if (ranges.length === 0) {
1794
- return text;
1796
+ return text3;
1795
1797
  }
1796
1798
  const normalized = ranges.map((range) => ({
1797
- start: Math.max(0, Math.min(text.length, range.start)),
1798
- end: Math.max(0, Math.min(text.length, range.end))
1799
+ start: Math.max(0, Math.min(text3.length, range.start)),
1800
+ end: Math.max(0, Math.min(text3.length, range.end))
1799
1801
  })).filter((range) => range.end > range.start).sort((a, b) => a.start - b.start);
1800
1802
  if (normalized.length === 0) {
1801
- return text;
1803
+ return text3;
1802
1804
  }
1803
1805
  let cursor = 0;
1804
1806
  let output = "";
@@ -1809,10 +1811,10 @@ function stripTextByRanges(text, ranges) {
1809
1811
  }
1810
1812
  continue;
1811
1813
  }
1812
- output += text.slice(cursor, range.start);
1814
+ output += text3.slice(cursor, range.start);
1813
1815
  cursor = range.end;
1814
1816
  }
1815
- output += text.slice(cursor);
1817
+ output += text3.slice(cursor);
1816
1818
  return output.trimEnd();
1817
1819
  }
1818
1820
  function stripReminders(message2) {
@@ -1858,13 +1860,13 @@ function stripReminders(message2) {
1858
1860
  function isRecord(value) {
1859
1861
  return typeof value === "object" && value !== null && !Array.isArray(value);
1860
1862
  }
1861
- function assertReminderText(text) {
1862
- if (text.trim().length === 0) {
1863
+ function assertReminderText(text3) {
1864
+ if (text3.trim().length === 0) {
1863
1865
  throw new Error("Reminder text must not be empty");
1864
1866
  }
1865
1867
  }
1866
- function formatTaggedReminder(text) {
1867
- return `${SYSTEM_REMINDER_OPEN_TAG}${text}${SYSTEM_REMINDER_CLOSE_TAG}`;
1868
+ function formatTaggedReminder(text3) {
1869
+ return `${SYSTEM_REMINDER_OPEN_TAG}${text3}${SYSTEM_REMINDER_CLOSE_TAG}`;
1868
1870
  }
1869
1871
  function findLastTextPartIndex(message2) {
1870
1872
  for (let i = message2.parts.length - 1; i >= 0; i--) {
@@ -1943,8 +1945,8 @@ function resolveReminder(item, ctx) {
1943
1945
  return metadata ? { ...resolved, metadata } : resolved;
1944
1946
  }
1945
1947
  async function resolveReminderAsync(item, ctx) {
1946
- const text = await (typeof item.text === "function" ? item.text(ctx) : item.text);
1947
- const resolved = normalizeReminderResolution(text);
1948
+ const text3 = await (typeof item.text === "function" ? item.text(ctx) : item.text);
1949
+ const resolved = normalizeReminderResolution(text3);
1948
1950
  if (!resolved) return null;
1949
1951
  const metadata = item.metadata || resolved.metadata ? { ...item.metadata ?? {}, ...resolved.metadata ?? {} } : void 0;
1950
1952
  return metadata ? { ...resolved, metadata } : resolved;
@@ -1979,16 +1981,16 @@ function reminder(textOrFragment, options) {
1979
1981
  if (options?.when === void 0 && target !== "user") {
1980
1982
  throw new Error(`Reminder target "${target}" requires a when predicate`);
1981
1983
  }
1982
- const text = normalizeConditionalReminderText(textOrFragment);
1983
- if (typeof text === "string") {
1984
- assertReminderText(text);
1984
+ const text3 = normalizeConditionalReminderText(textOrFragment);
1985
+ if (typeof text3 === "string") {
1986
+ assertReminderText(text3);
1985
1987
  }
1986
1988
  return {
1987
1989
  name: "reminder",
1988
1990
  data: null,
1989
1991
  metadata: {
1990
1992
  reminder: {
1991
- text,
1993
+ text: text3,
1992
1994
  when: options?.when ?? (() => true),
1993
1995
  asPart,
1994
1996
  target
@@ -2006,8 +2008,8 @@ function applyUserRemindersToMessage(message2, reminders) {
2006
2008
  }
2007
2009
  mergeReminderMetadata(message2, added);
2008
2010
  }
2009
- function synthesizeReminderMessage(text, firedAt, onceIds = []) {
2010
- const texts = Array.isArray(text) ? text : [text];
2011
+ function synthesizeReminderMessage(text3, firedAt, onceIds = []) {
2012
+ const texts = Array.isArray(text3) ? text3 : [text3];
2011
2013
  for (const value of texts) assertReminderText(value);
2012
2014
  return {
2013
2015
  id: generateId4(),
@@ -2180,8 +2182,8 @@ function classifies(classifier, options) {
2180
2182
  function contentIncludes(keywords) {
2181
2183
  const lower = keywords.map((k) => k.toLowerCase());
2182
2184
  return (ctx) => {
2183
- const text = ctx.content.toLowerCase();
2184
- return lower.some((kw) => text.includes(kw));
2185
+ const text3 = ctx.content.toLowerCase();
2186
+ return lower.some((kw) => text3.includes(kw));
2185
2187
  };
2186
2188
  }
2187
2189
  function contentPattern(pattern) {
@@ -2212,8 +2214,8 @@ function lastAssistantLength(spec) {
2212
2214
  assertCountSpec(spec);
2213
2215
  return (ctx) => {
2214
2216
  const message2 = ctx.lastAssistantMessage;
2215
- const text = message2 ? extractPlainText(message2) : "";
2216
- return checkCount(text.length, spec);
2217
+ const text3 = message2 ? extractPlainText(message2) : "";
2218
+ return checkCount(text3.length, spec);
2217
2219
  };
2218
2220
  }
2219
2221
 
@@ -2270,8 +2272,8 @@ function toolCall(options) {
2270
2272
  }
2271
2273
  if (options.errorText) {
2272
2274
  if (part.state !== "output-error") return false;
2273
- const text = part.errorText ?? "";
2274
- if (!options.errorText(text)) return false;
2275
+ const text3 = part.errorText ?? "";
2276
+ if (!options.errorText(text3)) return false;
2275
2277
  }
2276
2278
  return true;
2277
2279
  });
@@ -2751,11 +2753,11 @@ import { encode } from "gpt-tokenizer";
2751
2753
  import pMemoize from "p-memoize";
2752
2754
  import { z as z2 } from "zod";
2753
2755
  var defaultTokenizer = {
2754
- encode(text) {
2755
- return encode(text);
2756
+ encode(text3) {
2757
+ return encode(text3);
2756
2758
  },
2757
- count(text) {
2758
- return encode(text).length;
2759
+ count(text3) {
2760
+ return encode(text3).length;
2759
2761
  }
2760
2762
  };
2761
2763
  var modelCostSchema = z2.object({
@@ -3113,7 +3115,7 @@ var FragmentLoaderResolver = class {
3113
3115
  resolved = await untilAborted(handler.resolve(value, ctx), ctx.signal);
3114
3116
  } catch (cause) {
3115
3117
  throw new Error(
3116
- `Async fragment '${path6}' failed in ${handler.name}: ${cause instanceof Error ? cause.message : String(cause)}`,
3118
+ `Async fragment '${path6}' failed in ${handler.name}: ${Error.isError(cause) ? cause.message : String(cause)}`,
3117
3119
  { cause }
3118
3120
  );
3119
3121
  }
@@ -3298,11 +3300,11 @@ import { z as z4 } from "zod";
3298
3300
  import { z as z3 } from "zod";
3299
3301
  var bigintColumn = z3.union([z3.number(), z3.string().regex(/^-?\d+$/)]).transform(Number);
3300
3302
  var jsonObject = z3.record(z3.string(), z3.unknown());
3301
- function parseJson(text) {
3302
- return JSON.parse(text);
3303
+ function parseJson(text3) {
3304
+ return JSON.parse(text3);
3303
3305
  }
3304
- function parseJsonObject(text) {
3305
- return jsonObject.parse(parseJson(text));
3306
+ function parseJsonObject(text3) {
3307
+ return jsonObject.parse(parseJson(text3));
3306
3308
  }
3307
3309
 
3308
3310
  // packages/context/src/lib/store/ddl.sqlite.ts
@@ -3530,7 +3532,7 @@ var SearchQuerySyntaxError = class extends Error {
3530
3532
  }
3531
3533
  };
3532
3534
  function isFts5QueryError(error) {
3533
- return error instanceof Error && "errcode" in error && error.errcode === 1 && /^(fts5: syntax error near |no such column: |unterminated string$|unknown special query: |expected integer, got )/.test(
3535
+ return Error.isError(error) && "errcode" in error && error.errcode === 1 && /^(fts5: syntax error near |no such column: |unterminated string$|unknown special query: |expected integer, got )/.test(
3534
3536
  error.message
3535
3537
  );
3536
3538
  }
@@ -4340,8 +4342,8 @@ var ContextEngine = class _ContextEngine {
4340
4342
  */
4341
4343
  async headMessage() {
4342
4344
  const open3 = await this.#open();
4343
- if (this.#pendingMessages.length > 0) {
4344
- const tail = this.#pendingMessages[this.#pendingMessages.length - 1];
4345
+ const tail = this.#pendingMessages.at(-1);
4346
+ if (tail) {
4345
4347
  if (!tail.id) {
4346
4348
  throw new Error(
4347
4349
  `headMessage: pending fragment "${tail.name}" is missing id`
@@ -5375,16 +5377,16 @@ function term(name, definition) {
5375
5377
  }
5376
5378
  };
5377
5379
  }
5378
- function hint(text) {
5380
+ function hint(text3) {
5379
5381
  return {
5380
5382
  name: "hint",
5381
- data: text,
5383
+ data: text3,
5382
5384
  codec: {
5383
5385
  encode() {
5384
- return { type: "hint", text };
5386
+ return { type: "hint", text: text3 };
5385
5387
  },
5386
5388
  decode() {
5387
- return text;
5389
+ return text3;
5388
5390
  }
5389
5391
  }
5390
5392
  };
@@ -5726,7 +5728,7 @@ var TitleGenerator = class {
5726
5728
  if (!msg) return null;
5727
5729
  try {
5728
5730
  const title = await this.#generateTitle(msg, options);
5729
- return this.#applyTitle(title, "llm");
5731
+ return await this.#applyTitle(title, "llm");
5730
5732
  } catch (error) {
5731
5733
  console.warn(
5732
5734
  "TitleGenerator: LLM title generation failed, falling back to static.",
@@ -5744,8 +5746,8 @@ var TitleGenerator = class {
5744
5746
  return this.#truncateTitle(this.#extractText(message2));
5745
5747
  }
5746
5748
  async #generateTitle(message2, options) {
5747
- const text = this.#extractText(message2);
5748
- if (!text) {
5749
+ const text3 = this.#extractText(message2);
5750
+ if (!text3) {
5749
5751
  throw new Error(
5750
5752
  "Cannot generate chat title: message has no text content."
5751
5753
  );
@@ -5756,7 +5758,7 @@ var TitleGenerator = class {
5756
5758
  chatId: crypto.randomUUID(),
5757
5759
  userId: "system"
5758
5760
  });
5759
- context.set(role(TITLE_PROMPT), user(text));
5761
+ context.set(role(TITLE_PROMPT), user(text3));
5760
5762
  const { title } = await structuredOutput({
5761
5763
  context,
5762
5764
  model: options.model,
@@ -5770,9 +5772,9 @@ var TitleGenerator = class {
5770
5772
  #extractText(message2) {
5771
5773
  return extractPlainText(stripReminders(message2));
5772
5774
  }
5773
- #truncateTitle(text) {
5774
- if (!text) return "New Chat";
5775
- return text.length > 100 ? text.slice(0, 100) + "..." : text;
5775
+ #truncateTitle(text3) {
5776
+ if (!text3) return "New Chat";
5777
+ return text3.length > 100 ? text3.slice(0, 100) + "..." : text3;
5776
5778
  }
5777
5779
  async #applyTitle(title, source) {
5778
5780
  await this.#context.updateChat({ title });
@@ -5926,7 +5928,7 @@ function formatChatError(error) {
5926
5928
  console.error("Upstream API call failed:", error);
5927
5929
  return `Upstream API call failed with status ${error.statusCode}: ${error.message}`;
5928
5930
  }
5929
- return error instanceof Error ? "An error occurred." : JSON.stringify(error);
5931
+ return Error.isError(error) ? "An error occurred." : JSON.stringify(error);
5930
5932
  }
5931
5933
  async function makeTitle(options) {
5932
5934
  const titler = new TitleGenerator({ context: options.context });
@@ -6426,14 +6428,14 @@ function latestEvidence(items) {
6426
6428
  return latest ? ` Evidence: ${latest.summary} (${latest.source})` : "";
6427
6429
  }
6428
6430
  function errorMessage(error) {
6429
- const message2 = error instanceof Error ? error.message : String(error);
6431
+ const message2 = Error.isError(error) ? error.message : String(error);
6430
6432
  return message2.length > 500 ? `${message2.slice(0, 497)}...` : message2;
6431
6433
  }
6432
6434
  function parsePlanJson(raw) {
6433
6435
  try {
6434
6436
  return JSON.parse(raw);
6435
6437
  } catch (error) {
6436
- const message2 = error instanceof Error ? error.message : String(error);
6438
+ const message2 = Error.isError(error) ? error.message : String(error);
6437
6439
  throw new Error(`invalid JSON: ${message2}`, { cause: error });
6438
6440
  }
6439
6441
  }
@@ -6442,7 +6444,11 @@ function createPlanReview(options, formatPlanReview, reviewReminder) {
6442
6444
  async ({ sandbox }) => {
6443
6445
  let raw;
6444
6446
  try {
6445
- raw = await sandbox.sandbox.readFile(PLAN_FILE_PATH);
6447
+ const plan2 = await sandbox.sandbox.readTextFile({
6448
+ path: PLAN_FILE_PATH
6449
+ });
6450
+ if (plan2 === null) throw new Error("the file does not exist");
6451
+ raw = plan2;
6446
6452
  } catch (error) {
6447
6453
  return [
6448
6454
  `The plan file at ${PLAN_FILE_PATH} could not be read: ${errorMessage(error)}`,
@@ -6847,7 +6853,7 @@ var SOCRATIC_REVIEW_REMINDER = [
6847
6853
  "Record the review and its nextQuestionId, then revise the inquiry before continuing when needed.",
6848
6854
  "Before claiming completion, verify that every required question has an evidence-backed answer and that the answers establish the requested outcome."
6849
6855
  ].join("\n");
6850
- var questionText = nonEmptyString.refine((text) => text.endsWith("?"), {
6856
+ var questionText = nonEmptyString.refine((text3) => text3.endsWith("?"), {
6851
6857
  message: "must end with a question mark"
6852
6858
  });
6853
6859
  var answer = z9.strictObject({
@@ -7163,11 +7169,15 @@ function render(tag, ...fragments) {
7163
7169
  import { createRepairToolCall as createRepairToolCall2 } from "@deepagents/agent";
7164
7170
 
7165
7171
  // packages/context/src/lib/sandbox/apple-container-sandbox.ts
7166
- import spawn, { SubprocessError as SubprocessError2 } from "nano-spawn";
7167
- import { spawn as childSpawn } from "node:child_process";
7168
- import { mkdtemp, rm, writeFile } from "node:fs/promises";
7169
- import { tmpdir } from "node:os";
7172
+ import { TemporaryFiles } from "@zukhruf/fs";
7173
+ import spawn, { SubprocessError } from "nano-spawn";
7174
+ import {
7175
+ spawn as childSpawn
7176
+ } from "node:child_process";
7177
+ import { once as once2 } from "node:events";
7178
+ import { writeFile } from "node:fs/promises";
7170
7179
  import { join } from "node:path";
7180
+ import { Readable, Writable } from "node:stream";
7171
7181
  import z10 from "zod";
7172
7182
 
7173
7183
  // packages/context/src/lib/sandbox/container-sandbox-errors.ts
@@ -7258,115 +7268,365 @@ var AppleContainerVolumeRemoveError = class extends AppleContainerSandboxError {
7258
7268
  }
7259
7269
  };
7260
7270
 
7261
- // packages/context/src/lib/sandbox/cli-process.ts
7262
- import { SubprocessError } from "nano-spawn";
7263
- import { Readable } from "node:stream";
7271
+ // packages/context/src/lib/sandbox/container-sandbox.ts
7272
+ import { createHash, randomUUID as randomUUID2 } from "node:crypto";
7273
+ import { existsSync, readFileSync } from "node:fs";
7274
+ import { setTimeout as setTimeout2 } from "node:timers/promises";
7275
+
7276
+ // packages/context/src/lib/sandbox/container-session.ts
7277
+ import {
7278
+ extractLines
7279
+ } from "@ai-sdk/provider-utils";
7280
+ import { randomUUID } from "node:crypto";
7281
+ import { posix } from "node:path";
7282
+ import { text } from "node:stream/consumers";
7283
+ import { setTimeout as delay } from "node:timers/promises";
7264
7284
 
7265
7285
  // packages/context/src/lib/sandbox/shell-quote.ts
7266
7286
  function shellQuote(s) {
7267
7287
  return `'${s.replace(/'/g, `'\\''`)}'`;
7268
7288
  }
7269
7289
 
7270
- // packages/context/src/lib/sandbox/cli-process.ts
7271
- function commandResultFrom(error) {
7272
- if (error instanceof SubprocessError) {
7273
- return {
7274
- stdout: error.stdout,
7275
- stderr: error.stderr || error.message,
7276
- exitCode: error.exitCode ?? 1
7277
- };
7290
+ // packages/context/src/lib/sandbox/container-session.ts
7291
+ var NOT_FOUND_EXIT_CODE = 3;
7292
+ var WRONG_TYPE_EXIT_CODE = 4;
7293
+ var FILE_STAT_TYPES = [
7294
+ "file",
7295
+ "directory",
7296
+ "other"
7297
+ ];
7298
+ var DIRECTORY_ENTRY_TYPES = [
7299
+ "file",
7300
+ "directory",
7301
+ "symlink",
7302
+ "other"
7303
+ ];
7304
+ function bufferEncoding(encoding = "utf-8") {
7305
+ if (!Buffer.isEncoding(encoding)) {
7306
+ throw new TypeError(`Unknown encoding: ${encoding}`);
7278
7307
  }
7279
- return {
7280
- stdout: "",
7281
- stderr: error instanceof Error ? error.message : "",
7282
- exitCode: 1
7283
- };
7308
+ return encoding;
7284
7309
  }
7285
- function toSandboxProcess(child, abortSignal) {
7286
- if (!child.stdout || !child.stderr) {
7287
- child.kill("SIGKILL");
7288
- throw new Error("exec child process is missing stdout/stderr streams");
7310
+ var EXIT_MISSING_FUNCTION = `
7311
+ exit_missing() {
7312
+ error=$(LC_ALL=C; : 2>&1 < "$1")
7313
+ case $error in
7314
+ *": No such file or directory" | *": Not a directory") exit ${NOT_FOUND_EXIT_CODE} ;;
7315
+ esac
7316
+ echo "\${error:-Cannot access $1}" >&2
7317
+ exit 1
7318
+ }
7319
+ `;
7320
+ var STAT_SCRIPT = `${EXIT_MISSING_FUNCTION}
7321
+ [ -e "$1" ] || exit_missing "$1"
7322
+ if [ -f "$1" ]; then type=file; elif [ -d "$1" ]; then type=directory; else type=other; fi
7323
+ size=$(stat -L -c %s -- "$1") || exit 1
7324
+ printf '%s %s' "$type" "$size"
7325
+ `;
7326
+ var READ_FILE_SCRIPT = `${EXIT_MISSING_FUNCTION}
7327
+ [ -e "$1" ] || exit_missing "$1"
7328
+ base64 < "$1"
7329
+ `;
7330
+ var LIST_DIRECTORY_SCRIPT = `${EXIT_MISSING_FUNCTION}
7331
+ if [ ! -d "$1" ]; then
7332
+ [ -e "$1" ] || exit_missing "$1"
7333
+ echo "Not a directory" >&2
7334
+ exit ${WRONG_TYPE_EXIT_CODE}
7335
+ fi
7336
+ case $1 in /*) dir=$1 ;; *) dir=./$1 ;; esac
7337
+ cd -P -- "$dir" || exit 1
7338
+ [ -r . ] || { echo "Permission denied" >&2; exit 1; }
7339
+ shopt -s dotglob nullglob
7340
+ for name in *; do
7341
+ if [ -L "$name" ]; then type=symlink
7342
+ elif [ -f "$name" ]; then type=file
7343
+ elif [ -d "$name" ]; then type=directory
7344
+ else type=other
7345
+ fi
7346
+ printf '%s %s\\0' "$type" "$name"
7347
+ done
7348
+ `;
7349
+ var DELETE_FILE_SCRIPT = `${EXIT_MISSING_FUNCTION}
7350
+ if [ -d "$1" ] && [ ! -L "$1" ]; then
7351
+ echo "Is a directory" >&2
7352
+ exit ${WRONG_TYPE_EXIT_CODE}
7353
+ fi
7354
+ [ -e "$1" ] || [ -L "$1" ] || exit_missing "$1"
7355
+ rm -f -- "$1"
7356
+ `;
7357
+ async function runPathScript(container, script, path6, signal) {
7358
+ signal?.throwIfAborted();
7359
+ const result = await container.exec(["bash", "-c", script, "bash", path6], {
7360
+ signal
7361
+ });
7362
+ signal?.throwIfAborted();
7363
+ return result;
7364
+ }
7365
+ async function statOverExec(container, path6, signal) {
7366
+ const { exitCode, stdout, stderr } = await runPathScript(
7367
+ container,
7368
+ STAT_SCRIPT,
7369
+ path6,
7370
+ signal
7371
+ );
7372
+ if (exitCode === NOT_FOUND_EXIT_CODE) return null;
7373
+ if (exitCode !== 0) {
7374
+ throw new Error(`Failed to stat "${path6}": ${stderr.trim()}`);
7375
+ }
7376
+ const [printed, size] = stdout.split(" ");
7377
+ const type = FILE_STAT_TYPES.find((known) => known === printed);
7378
+ if (!type) {
7379
+ throw new Error(`Failed to stat "${path6}": unknown type "${printed}"`);
7380
+ }
7381
+ return { type, size: Number(size) };
7382
+ }
7383
+ async function readFileOverExec(container, path6, signal) {
7384
+ const { exitCode, stdout, stderr } = await runPathScript(
7385
+ container,
7386
+ READ_FILE_SCRIPT,
7387
+ path6,
7388
+ signal
7389
+ );
7390
+ if (exitCode === NOT_FOUND_EXIT_CODE) return null;
7391
+ if (exitCode !== 0) {
7392
+ throw new Error(`Failed to read file "${path6}": ${stderr.trim()}`);
7289
7393
  }
7290
- const onAbort = () => child.kill("SIGKILL");
7291
- if (abortSignal) {
7292
- if (abortSignal.aborted) onAbort();
7293
- else abortSignal.addEventListener("abort", onAbort, { once: true });
7394
+ return Buffer.from(stdout, "base64");
7395
+ }
7396
+ async function writeFileOverExec(container, path6, content, signal) {
7397
+ const { exitCode, stderr } = await container.exec(
7398
+ [
7399
+ "bash",
7400
+ "-c",
7401
+ 'mkdir -p -- "$(dirname -- "$1")" && cat > "$1"',
7402
+ "bash",
7403
+ path6
7404
+ ],
7405
+ { signal, stdin: content }
7406
+ );
7407
+ signal?.throwIfAborted();
7408
+ if (exitCode !== 0) {
7409
+ throw new Error(`Failed to write file "${path6}": ${stderr.trim()}`);
7294
7410
  }
7295
- return {
7296
- stdout: Readable.toWeb(child.stdout),
7297
- stderr: Readable.toWeb(child.stderr),
7298
- exit: new Promise((resolve3, reject) => {
7299
- const settle = () => {
7300
- child.removeListener("exit", onExitEvent);
7301
- child.removeListener("error", onError);
7302
- abortSignal?.removeEventListener("abort", onAbort);
7303
- };
7304
- const onError = (err) => {
7305
- settle();
7306
- reject(err);
7307
- };
7308
- const onExitEvent = (code, exitSignal) => {
7309
- settle();
7310
- resolve3({ code, signal: exitSignal, success: code === 0 });
7311
- };
7312
- child.on("exit", onExitEvent);
7313
- child.on("error", onError);
7314
- })
7315
- };
7316
7411
  }
7317
- var BASE64_WRITE_CHUNK = 32768;
7318
- function base64WriteCommands(path6, content) {
7319
- const base64 = Buffer.from(content).toString("base64");
7320
- const quotedPath = shellQuote(path6);
7321
- const commands = [];
7322
- for (let offset = 0; offset < base64.length; offset += BASE64_WRITE_CHUNK) {
7323
- const chunk = base64.slice(offset, offset + BASE64_WRITE_CHUNK);
7324
- const redirect = offset === 0 ? ">" : ">>";
7325
- commands.push(
7326
- `printf '%s' ${shellQuote(chunk)} | base64 -d ${redirect} ${quotedPath}`
7327
- );
7412
+ async function listDirectoryOverExec(container, path6, signal) {
7413
+ const { exitCode, stdout, stderr } = await runPathScript(
7414
+ container,
7415
+ LIST_DIRECTORY_SCRIPT,
7416
+ path6,
7417
+ signal
7418
+ );
7419
+ if (exitCode === NOT_FOUND_EXIT_CODE) return null;
7420
+ if (exitCode !== 0) {
7421
+ throw new Error(`Failed to list "${path6}": ${stderr.trim()}`);
7422
+ }
7423
+ return stdout.split("\0").filter((record) => record !== "").map((record) => {
7424
+ const separator = record.indexOf(" ");
7425
+ const printed = record.slice(0, separator);
7426
+ const type = DIRECTORY_ENTRY_TYPES.find((known) => known === printed);
7427
+ if (!type) {
7428
+ throw new Error(`Failed to list "${path6}": unknown type "${printed}"`);
7429
+ }
7430
+ return { name: record.slice(separator + 1), type };
7431
+ });
7432
+ }
7433
+ async function deleteFileOverExec(container, path6, signal) {
7434
+ const { exitCode, stderr } = await runPathScript(
7435
+ container,
7436
+ DELETE_FILE_SCRIPT,
7437
+ path6,
7438
+ signal
7439
+ );
7440
+ if (exitCode === NOT_FOUND_EXIT_CODE) return false;
7441
+ if (exitCode === WRONG_TYPE_EXIT_CODE) {
7442
+ throw new Error(`Cannot delete "${path6}": it is a directory.`);
7328
7443
  }
7329
- if (commands.length === 0) {
7330
- commands.push(`printf '' > ${quotedPath}`);
7444
+ if (exitCode !== 0) {
7445
+ throw new Error(`Failed to delete "${path6}": ${stderr.trim()}`);
7331
7446
  }
7332
- return commands;
7447
+ return true;
7333
7448
  }
7334
- async function readFileOverExec(executeCommand, path6) {
7335
- const result = await executeCommand(`base64 ${shellQuote(path6)}`);
7336
- if (result.exitCode !== 0) {
7337
- throw new Error(`Failed to read file "${path6}": ${result.stderr}`);
7338
- }
7339
- return Buffer.from(result.stdout, "base64");
7449
+ async function collectOutput(process2) {
7450
+ const [stdout, stderr, exitCode] = await Promise.all([
7451
+ text(process2.stdout),
7452
+ text(process2.stderr),
7453
+ process2.exitCode
7454
+ ]);
7455
+ return { stdout, stderr, exitCode };
7456
+ }
7457
+ function managedCommand(command, controlPath, commandTimeout) {
7458
+ return [
7459
+ "set -m",
7460
+ `control=${shellQuote(controlPath)}`,
7461
+ ': > "$control" || exit 1',
7462
+ "timer=",
7463
+ `trap 'if [ -n "$timer" ]; then kill -TERM "$timer" 2>/dev/null || :; wait "$timer" 2>/dev/null || :; fi; rm -f "$control" "$control.timeout"' EXIT`,
7464
+ `bash -lc ${shellQuote(command)} &`,
7465
+ "pid=$!",
7466
+ `printf '%s\\n' "$pid" > "$control"`,
7467
+ ...commandTimeout ? [
7468
+ // Keep the deadline on the engine host: SSH setup/round trips must not
7469
+ // let the command run past its execution budget.
7470
+ "(",
7471
+ `sleep ${commandTimeout / 1e3} &`,
7472
+ "alarm=$!",
7473
+ `trap 'kill "$alarm" 2>/dev/null || :; wait "$alarm" 2>/dev/null || :; exit 0' TERM`,
7474
+ 'wait "$alarm" || exit',
7475
+ 'if kill -0 -- "-$pid" 2>/dev/null; then : > "$control.timeout"; kill -KILL -- "-$pid" 2>/dev/null || :; fi',
7476
+ ") &",
7477
+ "timer=$!"
7478
+ ] : [],
7479
+ 'wait "$pid"',
7480
+ "status=$?",
7481
+ '[ ! -e "$control.timeout" ] || exit 124',
7482
+ 'exit "$status"'
7483
+ ].join("\n");
7340
7484
  }
7341
- async function existsOverExec(executeCommand, path6) {
7342
- const result = await executeCommand(
7343
- `test -e ${shellQuote(path6)} && printf true || printf false`
7485
+ async function terminate(container, controlPath, exitCode) {
7486
+ const exited = exitCode.then(
7487
+ () => true,
7488
+ () => true
7344
7489
  );
7345
- if (result.stdout === "true") return true;
7346
- if (result.stdout === "false") return false;
7347
- throw new Error(`Failed to check "${path6}": ${result.stderr}`);
7348
- }
7349
- async function writeFilesOverExec(executeCommand, files) {
7350
- for (const file of files) {
7351
- const dir = file.path.substring(0, file.path.lastIndexOf("/"));
7352
- if (dir) {
7353
- await executeCommand(`mkdir -p ${shellQuote(dir)}`);
7354
- }
7355
- for (const command of base64WriteCommands(file.path, file.content)) {
7356
- const result = await executeCommand(command);
7357
- if (result.exitCode !== 0) {
7358
- throw new Error(
7359
- `Failed to write file "${file.path}": ${result.stderr}`
7360
- );
7361
- }
7490
+ const killGroup = [
7491
+ `IFS= read -r pid < ${shellQuote(controlPath)} || exit 0`,
7492
+ '[ -n "$pid" ] || exit 0',
7493
+ "printf found",
7494
+ 'kill -KILL -- "-$pid" 2>/dev/null || exit 0',
7495
+ "group_alive() {",
7496
+ " local stat rest state pgrp",
7497
+ " for stat_path in /proc/[0-9]*/stat; do",
7498
+ ' IFS= read -r stat < "$stat_path" || continue',
7499
+ " rest=${stat##*) }",
7500
+ ' read -r state _ pgrp _ <<< "$rest"',
7501
+ ' if [ "$pgrp" = "$pid" ] && [ "$state" != Z ]; then return 0; fi',
7502
+ " done",
7503
+ " return 1",
7504
+ "}",
7505
+ "while group_alive; do sleep 0.01; done"
7506
+ ].join("\n");
7507
+ while (true) {
7508
+ const { stdout } = await container.exec(["bash", "-c", killGroup]);
7509
+ if (stdout) return;
7510
+ if (await Promise.race([exited, delay(10).then(() => false)])) return;
7511
+ }
7512
+ }
7513
+ function validateEnv(env, errors) {
7514
+ for (const key of Object.keys(env ?? {})) {
7515
+ if (key.length === 0 || key.includes("=")) {
7516
+ throw errors.generic(`Invalid environment variable key: "${key}"`);
7362
7517
  }
7363
7518
  }
7364
7519
  }
7365
-
7366
- // packages/context/src/lib/sandbox/container-sandbox.ts
7367
- import { createHash, randomUUID } from "node:crypto";
7368
- import { existsSync, readFileSync } from "node:fs";
7369
- import { setTimeout as setTimeout2 } from "node:timers/promises";
7520
+ function containerSession(container, errors) {
7521
+ const scope = ({
7522
+ workingDirectory,
7523
+ env
7524
+ }) => {
7525
+ validateEnv(env, errors);
7526
+ return {
7527
+ env,
7528
+ // Joined, not normalized, so that `link/..` follows the link.
7529
+ workingDirectory: workingDirectory === void 0 || posix.isAbsolute(workingDirectory) ? workingDirectory : `${container.workdir}/${workingDirectory}`
7530
+ };
7531
+ };
7532
+ const start = async (options) => {
7533
+ const { command, abortSignal, stdin } = options;
7534
+ abortSignal?.throwIfAborted();
7535
+ const controlPath = `/dev/shm/deepagents-exec-${randomUUID()}.pid`;
7536
+ const process2 = await container.spawn(
7537
+ [
7538
+ "bash",
7539
+ "-c",
7540
+ managedCommand(command, controlPath, container.commandTimeout)
7541
+ ],
7542
+ { ...scope(options), stdin }
7543
+ );
7544
+ let termination;
7545
+ const kill = () => termination ??= terminate(container, controlPath, process2.exitCode);
7546
+ const onAbort = () => {
7547
+ void kill().catch(() => {
7548
+ });
7549
+ };
7550
+ if (abortSignal?.aborted) onAbort();
7551
+ else abortSignal?.addEventListener("abort", onAbort, { once: true });
7552
+ void process2.exitCode.catch(() => {
7553
+ }).finally(() => abortSignal?.removeEventListener("abort", onAbort));
7554
+ return { process: process2, kill };
7555
+ };
7556
+ async function spawn5(options) {
7557
+ const { process: process2, kill } = await start(options);
7558
+ return {
7559
+ stdout: process2.stdout,
7560
+ stderr: process2.stderr,
7561
+ ...process2.stdin ? { stdin: process2.stdin } : {},
7562
+ wait: async () => ({
7563
+ exitCode: await process2.exitCode.finally(
7564
+ () => options.abortSignal?.throwIfAborted()
7565
+ )
7566
+ }),
7567
+ kill
7568
+ };
7569
+ }
7570
+ const readBinaryFile = async ({
7571
+ path: path6,
7572
+ abortSignal
7573
+ }) => {
7574
+ abortSignal?.throwIfAborted();
7575
+ return container.readFile(path6, abortSignal);
7576
+ };
7577
+ const writeBinaryFile = async ({
7578
+ path: path6,
7579
+ content,
7580
+ abortSignal
7581
+ }) => {
7582
+ abortSignal?.throwIfAborted();
7583
+ return container.writeFile(path6, content, abortSignal);
7584
+ };
7585
+ return {
7586
+ description: `Commands run through bash -lc in a Linux container, starting in ${container.workdir}.`,
7587
+ run: async (options) => {
7588
+ const { command, abortSignal } = options;
7589
+ abortSignal?.throwIfAborted();
7590
+ if (!abortSignal && !container.commandTimeout) {
7591
+ return container.exec(["bash", "-lc", command], scope(options));
7592
+ }
7593
+ const { process: process2 } = await start(options);
7594
+ return collectOutput(process2).finally(
7595
+ () => abortSignal?.throwIfAborted()
7596
+ );
7597
+ },
7598
+ spawn: spawn5,
7599
+ readBinaryFile,
7600
+ readFile: async (options) => {
7601
+ const bytes = await readBinaryFile(options);
7602
+ return bytes && ReadableStream.from([bytes]);
7603
+ },
7604
+ readTextFile: async ({ startLine, endLine, encoding, ...options }) => {
7605
+ const bytes = await readBinaryFile(options);
7606
+ if (!bytes) return null;
7607
+ return extractLines({
7608
+ text: Buffer.from(bytes).toString(bufferEncoding(encoding)),
7609
+ startLine,
7610
+ endLine
7611
+ });
7612
+ },
7613
+ writeBinaryFile,
7614
+ writeFile: async ({ content, ...options }) => writeBinaryFile({
7615
+ ...options,
7616
+ content: await new Response(content).bytes()
7617
+ }),
7618
+ writeTextFile: ({ content, encoding, ...options }) => writeBinaryFile({
7619
+ ...options,
7620
+ content: Buffer.from(content, bufferEncoding(encoding))
7621
+ }),
7622
+ stat: async ({ path: path6, abortSignal }) => {
7623
+ abortSignal?.throwIfAborted();
7624
+ return container.stat(path6, abortSignal);
7625
+ },
7626
+ listDirectory: ({ path: path6, abortSignal }) => listDirectoryOverExec(container, path6, abortSignal),
7627
+ deleteFile: ({ path: path6, abortSignal }) => deleteFileOverExec(container, path6, abortSignal)
7628
+ };
7629
+ }
7370
7630
 
7371
7631
  // packages/context/src/lib/sandbox/docker-sandbox-errors.ts
7372
7632
  var DockerSandboxError = class extends ContainerSandboxError {
@@ -7577,20 +7837,10 @@ function createInstallerContext(shell, containerId, image) {
7577
7837
  };
7578
7838
  }
7579
7839
 
7580
- // packages/context/src/lib/sandbox/read-file.ts
7581
- var decoder = new TextDecoder();
7582
- function readFileContent(bytes, options) {
7583
- return options?.encoding === "binary" ? bytes : decoder.decode(bytes);
7584
- }
7585
-
7586
7840
  // packages/context/src/lib/sandbox/container-sandbox.ts
7587
7841
  var CONTAINER_NAME_PATTERN = /^[A-Za-z0-9_.-]+$/;
7588
7842
  function validateSandboxOptions(opts, errors) {
7589
- for (const key of Object.keys(opts.env ?? {})) {
7590
- if (key.length === 0 || key.includes("=")) {
7591
- throw errors.generic(`Invalid environment variable key: "${key}"`);
7592
- }
7593
- }
7843
+ validateEnv(opts.env, errors);
7594
7844
  if (opts.name !== void 0 && !CONTAINER_NAME_PATTERN.test(opts.name)) {
7595
7845
  throw errors.generic(
7596
7846
  `Invalid container name: "${opts.name}". Use only letters, numbers, underscore, period, or hyphen. The "sandbox-" prefix is added automatically.`
@@ -7598,7 +7848,7 @@ function validateSandboxOptions(opts, errors) {
7598
7848
  }
7599
7849
  }
7600
7850
  function suppress(originalError, cleanupError) {
7601
- if (!(originalError instanceof Error)) return;
7851
+ if (!Error.isError(originalError)) return;
7602
7852
  const suppressed = "suppressed" in originalError && Array.isArray(originalError.suppressed) ? originalError.suppressed : [];
7603
7853
  Object.assign(originalError, { suppressed: [...suppressed, cleanupError] });
7604
7854
  }
@@ -7657,7 +7907,7 @@ var ContainerSandboxStrategy = class {
7657
7907
  return sandbox;
7658
7908
  }
7659
7909
  containerName() {
7660
- return this.name ? `sandbox-${this.name}` : `sandbox-${randomUUID().slice(0, 8)}`;
7910
+ return this.name ? `sandbox-${this.name}` : `sandbox-${randomUUID2().slice(0, 8)}`;
7661
7911
  }
7662
7912
  async acquireContainer(image) {
7663
7913
  const name = this.containerName();
@@ -7792,7 +8042,7 @@ var ContainerSandboxStrategy = class {
7792
8042
  return container.stop();
7793
8043
  }
7794
8044
  async assertBashAvailable(container) {
7795
- const result = await container.executeCommand(":");
8045
+ const result = await container.exec(["bash", "-lc", ":"]);
7796
8046
  if (result.exitCode === 0) return;
7797
8047
  const detail = result.stderr.trim() || result.stdout.trim();
7798
8048
  throw this.engine.errors.generic(
@@ -7810,16 +8060,11 @@ var ContainerSandboxStrategy = class {
7810
8060
  await this.engine.dispose();
7811
8061
  }
7812
8062
  };
8063
+ const disposeOnce = () => disposal ??= dispose();
7813
8064
  return {
7814
- executeCommand: (command, options) => container.executeCommand(command, options),
7815
- spawn: (command, options) => container.spawn(command, options),
7816
- readFile: async (path6, options) => readFileContent(await container.readFile(path6), options),
7817
- exists: (path6) => container.exists(path6),
7818
- writeFiles: (files) => container.writeFiles(files),
7819
- dispose: () => disposal ??= dispose(),
7820
- [Symbol.asyncDispose]() {
7821
- return this.dispose();
7822
- }
8065
+ ...containerSession(container, this.engine.errors),
8066
+ dispose: disposeOnce,
8067
+ [Symbol.asyncDispose]: disposeOnce
7823
8068
  };
7824
8069
  }
7825
8070
  };
@@ -7893,10 +8138,10 @@ function buildMountArg(volume) {
7893
8138
  return parts.join(",");
7894
8139
  }
7895
8140
  function getCliErrorMessage(error) {
7896
- if (error instanceof SubprocessError2) {
8141
+ if (error instanceof SubprocessError) {
7897
8142
  return error.stderr.trim() || error.stdout.trim() || error.message;
7898
8143
  }
7899
- return error instanceof Error && error.message || String(error);
8144
+ return Error.isError(error) && error.message || String(error);
7900
8145
  }
7901
8146
  function safeParseArray(stdout) {
7902
8147
  try {
@@ -7932,53 +8177,78 @@ function isMissing(message2) {
7932
8177
  function isNameConflict(message2) {
7933
8178
  return /already exists/i.test(message2);
7934
8179
  }
7935
- function execArgs(name, command, options) {
7936
- const flags = ["--cwd", options?.cwd || WORKDIR];
7937
- for (const [key, value] of Object.entries(options?.env ?? {})) {
7938
- if (key.length === 0 || key.includes("=")) {
7939
- throw new AppleContainerSandboxError(
7940
- `Invalid environment variable key: "${key}"`
7941
- );
7942
- }
7943
- flags.push("--env", `${key}=${value}`);
7944
- }
7945
- return ["exec", ...flags, name, "bash", "-lc", command];
7946
- }
7947
- async function run(args, signal) {
7948
- try {
7949
- const result = await spawn(CLI, args, { signal });
7950
- return { stdout: result.stdout, stderr: result.stderr, exitCode: 0 };
7951
- } catch (error) {
7952
- return commandResultFrom(error);
7953
- }
8180
+ function engineProcess(child) {
8181
+ return {
8182
+ stdout: Readable.toWeb(child.stdout),
8183
+ stderr: Readable.toWeb(child.stderr),
8184
+ exitCode: once2(child, "close").then(([code]) => code ?? 1)
8185
+ };
7954
8186
  }
7955
8187
  var AppleContainer = class {
7956
8188
  name;
8189
+ workdir = WORKDIR;
7957
8190
  constructor(name) {
7958
8191
  this.name = name;
7959
8192
  }
7960
- executeCommand(command, options) {
7961
- return run(execArgs(this.name, command), options?.signal);
8193
+ async exec(argv, { stdin, ...options } = {}) {
8194
+ try {
8195
+ const child = this.#exec(argv, options, stdin !== void 0);
8196
+ child.stdin.on("error", () => {
8197
+ });
8198
+ child.stdin.end(stdin);
8199
+ return await collectOutput(engineProcess(child));
8200
+ } catch (error) {
8201
+ return {
8202
+ stdout: "",
8203
+ stderr: Error.isError(error) ? error.message : String(error),
8204
+ exitCode: 1
8205
+ };
8206
+ }
8207
+ }
8208
+ async spawn(argv, { stdin, ...options }) {
8209
+ const child = this.#exec(argv, options, stdin === true);
8210
+ if (stdin) {
8211
+ return { ...engineProcess(child), stdin: Writable.toWeb(child.stdin) };
8212
+ }
8213
+ child.stdin.end();
8214
+ return engineProcess(child);
7962
8215
  }
7963
- async spawn(command, options) {
7964
- return toSandboxProcess(
7965
- childSpawn(CLI, execArgs(this.name, command, options)),
7966
- options?.signal
8216
+ #exec(argv, {
8217
+ workingDirectory = WORKDIR,
8218
+ env = {},
8219
+ signal
8220
+ }, interactive) {
8221
+ return childSpawn(
8222
+ CLI,
8223
+ [
8224
+ "exec",
8225
+ ...interactive ? ["--interactive"] : [],
8226
+ "--cwd",
8227
+ workingDirectory,
8228
+ ...Object.entries(env).flatMap(([key, value]) => [
8229
+ "--env",
8230
+ `${key}=${value}`
8231
+ ]),
8232
+ this.name,
8233
+ ...argv
8234
+ ],
8235
+ // The CLI traps SIGTERM and exits 0, which would read as a success.
8236
+ { signal, killSignal: "SIGKILL" }
7967
8237
  );
7968
8238
  }
7969
- readFile(path6) {
7970
- return readFileOverExec((command) => this.executeCommand(command), path6);
8239
+ readFile(path6, signal) {
8240
+ return readFileOverExec(this, path6, signal);
7971
8241
  }
7972
- writeFiles(files) {
7973
- return writeFilesOverExec((command) => this.executeCommand(command), files);
8242
+ stat(path6, signal) {
8243
+ return statOverExec(this, path6, signal);
7974
8244
  }
7975
- exists(path6) {
7976
- return existsOverExec((command) => this.executeCommand(command), path6);
8245
+ writeFile(path6, content, signal) {
8246
+ return writeFileOverExec(this, path6, content, signal);
7977
8247
  }
7978
8248
  installerContext(image) {
7979
8249
  return createInstallerContext(
7980
8250
  {
7981
- exec: (command) => run(["exec", this.name, "sh", "-c", command]),
8251
+ exec: (command) => this.exec(["sh", "-c", command]),
7982
8252
  SandboxError: AppleContainerSandboxError
7983
8253
  },
7984
8254
  this.name,
@@ -8059,7 +8329,7 @@ var appleEngine = {
8059
8329
  throw new AppleContainerCreationError(
8060
8330
  message2,
8061
8331
  image,
8062
- error instanceof Error ? error : void 0
8332
+ Error.isError(error) ? error : void 0
8063
8333
  );
8064
8334
  }
8065
8335
  }
@@ -8075,7 +8345,7 @@ var appleEngine = {
8075
8345
  throw new AppleContainerCreationError(
8076
8346
  message2,
8077
8347
  image,
8078
- error instanceof Error ? error : void 0
8348
+ Error.isError(error) ? error : void 0
8079
8349
  );
8080
8350
  }
8081
8351
  return { created: true, container: new AppleContainer(name) };
@@ -8129,17 +8399,23 @@ var appleEngine = {
8129
8399
  async buildImage(spec) {
8130
8400
  const archFlag = spec.identity ? ["--arch", spec.identity] : [];
8131
8401
  if (spec.dockerfile.includes("\n")) {
8132
- const tempDir = await mkdtemp(join(tmpdir(), "sandbox-containerfile-"));
8133
- const dockerfilePath = join(tempDir, "Dockerfile");
8402
+ await using tempDir = await new TemporaryFiles().directory(
8403
+ "sandbox-containerfile-"
8404
+ );
8405
+ const dockerfilePath = join(tempDir.path, "Dockerfile");
8134
8406
  await writeFile(dockerfilePath, spec.dockerfile);
8135
- try {
8136
- await runAppleBuild(
8137
- ["build", ...archFlag, "-t", spec.tag, "-f", dockerfilePath, tempDir],
8138
- spec.showBuildLogs
8139
- );
8140
- } finally {
8141
- await rm(tempDir, { recursive: true, force: true });
8142
- }
8407
+ await runAppleBuild(
8408
+ [
8409
+ "build",
8410
+ ...archFlag,
8411
+ "-t",
8412
+ spec.tag,
8413
+ "-f",
8414
+ dockerfilePath,
8415
+ tempDir.path
8416
+ ],
8417
+ spec.showBuildLogs
8418
+ );
8143
8419
  return;
8144
8420
  }
8145
8421
  await runAppleBuild(
@@ -8204,12 +8480,8 @@ async function createAppleContainerSandbox(options = {}) {
8204
8480
  }).create();
8205
8481
  }
8206
8482
  async function useAppleContainerSandbox(options, fn) {
8207
- const sandbox = await createAppleContainerSandbox(options);
8208
- try {
8209
- return await fn(sandbox);
8210
- } finally {
8211
- await sandbox.dispose();
8212
- }
8483
+ await using sandbox = await createAppleContainerSandbox(options);
8484
+ return await fn(sandbox);
8213
8485
  }
8214
8486
 
8215
8487
  // packages/context/src/lib/sandbox/bash-exception.ts
@@ -8225,6 +8497,108 @@ import * as path4 from "node:path";
8225
8497
  import z12 from "zod";
8226
8498
  import { withHostOnlyToolMetadata as withHostOnlyToolMetadata2 } from "@deepagents/agent";
8227
8499
 
8500
+ // packages/context/src/lib/sandbox/legacy-sandbox.ts
8501
+ import {
8502
+ extractLines as extractLines2
8503
+ } from "@ai-sdk/provider-utils";
8504
+ function commandInScope({
8505
+ command,
8506
+ workingDirectory,
8507
+ env
8508
+ }) {
8509
+ const exports = Object.entries(env ?? {}).map(
8510
+ ([name, value]) => `export ${name}=${shellQuote(value)}; `
8511
+ );
8512
+ const directory = workingDirectory === void 0 ? "" : `cd -- ${shellQuote(workingDirectory)} && `;
8513
+ return `${exports.join("")}${directory}${command}`;
8514
+ }
8515
+ function unported(method) {
8516
+ throw new Error(`${method} is not available until this backend is ported.`);
8517
+ }
8518
+ function fromLegacySandbox(legacy) {
8519
+ const readBinaryFile = async ({
8520
+ path: path6
8521
+ }) => {
8522
+ try {
8523
+ return await legacy.readFile(path6, { encoding: "binary" });
8524
+ } catch (error) {
8525
+ if (await legacy.exists(path6)) throw error;
8526
+ return null;
8527
+ }
8528
+ };
8529
+ const writeBinaryFile = ({
8530
+ path: path6,
8531
+ content
8532
+ }) => legacy.writeFiles([{ path: path6, content: Buffer.from(content) }]);
8533
+ async function spawn5(options) {
8534
+ if (options.stdin) throw new Error("This sandbox has no writable stdin.");
8535
+ if (!legacy.spawn) throw new Error("This sandbox cannot spawn processes.");
8536
+ const killer = new AbortController();
8537
+ const { abortSignal } = options;
8538
+ const child = await legacy.spawn(commandInScope(options), {
8539
+ signal: abortSignal ? AbortSignal.any([abortSignal, killer.signal]) : killer.signal
8540
+ });
8541
+ return {
8542
+ stdout: child.stdout,
8543
+ stderr: child.stderr,
8544
+ wait: async () => {
8545
+ const { code } = await child.exit;
8546
+ abortSignal?.throwIfAborted();
8547
+ return { exitCode: code ?? 1 };
8548
+ },
8549
+ kill: async () => killer.abort()
8550
+ };
8551
+ }
8552
+ return {
8553
+ description: "Commands run through bash -lc.",
8554
+ run: (options) => legacy.executeCommand(
8555
+ commandInScope(options),
8556
+ options.abortSignal ? { signal: options.abortSignal } : void 0
8557
+ ),
8558
+ spawn: spawn5,
8559
+ readBinaryFile,
8560
+ readFile: async (options) => {
8561
+ const bytes = await readBinaryFile(options);
8562
+ return bytes && new Blob([Buffer.from(bytes)]).stream();
8563
+ },
8564
+ readTextFile: async ({ startLine, endLine, encoding, ...options }) => {
8565
+ const bytes = await readBinaryFile(options);
8566
+ if (!bytes) return null;
8567
+ return extractLines2({
8568
+ text: Buffer.from(bytes).toString(bufferEncoding(encoding)),
8569
+ startLine,
8570
+ endLine
8571
+ });
8572
+ },
8573
+ writeBinaryFile,
8574
+ writeFile: async ({ path: path6, content }) => writeBinaryFile({
8575
+ path: path6,
8576
+ content: new Uint8Array(await new Response(content).arrayBuffer())
8577
+ }),
8578
+ writeTextFile: ({ path: path6, content, encoding }) => writeBinaryFile({
8579
+ path: path6,
8580
+ content: Buffer.from(content, bufferEncoding(encoding))
8581
+ }),
8582
+ stat: async ({ path: path6 }) => {
8583
+ const quoted = shellQuote(path6);
8584
+ const { stdout } = await legacy.executeCommand(
8585
+ `if [ -d ${quoted} ]; then echo directory 0; elif [ -f ${quoted} ]; then echo file $(wc -c < ${quoted}); elif [ -e ${quoted} ]; then echo other 0; fi`
8586
+ );
8587
+ const [printed, size] = stdout.trim().split(" ");
8588
+ if (!printed) return null;
8589
+ const type = FILE_STAT_TYPES.find((known) => known === printed);
8590
+ if (!type) {
8591
+ throw new Error(`Failed to stat "${path6}": unknown type "${printed}"`);
8592
+ }
8593
+ return { type, size: Number(size) };
8594
+ },
8595
+ listDirectory: () => unported("listDirectory"),
8596
+ deleteFile: () => unported("deleteFile"),
8597
+ dispose: () => legacy.dispose(),
8598
+ [Symbol.asyncDispose]: () => legacy.dispose()
8599
+ };
8600
+ }
8601
+
8228
8602
  // packages/context/src/lib/sandbox/read-file-tool/index.ts
8229
8603
  import { tool as tool2 } from "ai";
8230
8604
  import path3 from "node:path";
@@ -8356,7 +8730,7 @@ var textFileFormat = {
8356
8730
  value: `Text file exceeds ${formatBytes(TEXT_MAX_BYTES)} limit (got ${formatBytes(bytes.byteLength)}). Use offset/limit to slice.`
8357
8731
  };
8358
8732
  }
8359
- const content = readFileContent(bytes, { encoding: "utf-8" });
8733
+ const content = new TextDecoder().decode(bytes);
8360
8734
  if (offset === void 0 && limit === void 0) {
8361
8735
  return { type: "text", value: content };
8362
8736
  }
@@ -8384,7 +8758,7 @@ var inputSchema = z11.strictObject({
8384
8758
  });
8385
8759
  function createReadFileTool({
8386
8760
  sandbox,
8387
- destination
8761
+ workingDirectory
8388
8762
  }) {
8389
8763
  return tool2({
8390
8764
  description: "Read a sandbox file. Supports text, PNG, JPEG, GIF, WebP, PDF, XLSX, DOCX, and PPTX; other binary files such as HEIC, video, and audio are refused with conversion guidance. Use offset/limit with large text files.",
@@ -8395,11 +8769,12 @@ function createReadFileTool({
8395
8769
  inputSchema,
8396
8770
  execute: async (input, options) => {
8397
8771
  options.abortSignal?.throwIfAborted();
8398
- const bytes = await sandbox.readFile(
8399
- path3.posix.resolve(destination, input.path),
8400
- { encoding: "binary" }
8401
- );
8772
+ const bytes = await sandbox.readBinaryFile({
8773
+ path: workingDirectory === void 0 ? input.path : path3.posix.resolve(workingDirectory, input.path),
8774
+ abortSignal: options.abortSignal
8775
+ });
8402
8776
  options.abortSignal?.throwIfAborted();
8777
+ if (bytes === null) throw new Error(`File not found: ${input.path}`);
8403
8778
  for (const format of formats) {
8404
8779
  const result = format.read({ ...input, bytes, options });
8405
8780
  if (result !== void 0) return result;
@@ -8411,111 +8786,12 @@ function createReadFileTool({
8411
8786
  }
8412
8787
 
8413
8788
  // packages/context/src/lib/sandbox/bash-tool.ts
8414
- var DEFAULT_DESTINATION = "/workspace";
8415
8789
  var DEFAULT_MAX_FILES = 1e3;
8416
8790
  var DEFAULT_MAX_OUTPUT_LENGTH = 3e4;
8417
8791
  var TEE_OUTPUT_DIR = "/tmp/bash-tool";
8418
- var WRITE_BATCH_SIZE = 20;
8792
+ var MAX_CONCURRENT_WRITES = 20;
8793
+ var COMMAND_TIMEOUT_EXIT_CODE = 124;
8419
8794
  var REASONING_INSTRUCTION = 'Every bash tool call must include a brief non-empty "reasoning" input explaining why the command is needed.';
8420
- var KNOWN_TOOLS = /* @__PURE__ */ new Set([
8421
- "awk",
8422
- "cat",
8423
- "column",
8424
- "comm",
8425
- "curl",
8426
- "cut",
8427
- "diff",
8428
- "expand",
8429
- "find",
8430
- "fold",
8431
- "grep",
8432
- "head",
8433
- "html-to-markdown",
8434
- "iconv",
8435
- "js-exec",
8436
- "join",
8437
- "jq",
8438
- "node",
8439
- "nl",
8440
- "od",
8441
- "paste",
8442
- "printf",
8443
- "python",
8444
- "rev",
8445
- "sed",
8446
- "sort",
8447
- "split",
8448
- "strings",
8449
- "tail",
8450
- "tee",
8451
- "tr",
8452
- "uniq",
8453
- "unexpand",
8454
- "wc",
8455
- "xan",
8456
- "xargs",
8457
- "xxd",
8458
- "yq"
8459
- ]);
8460
- var FORMAT_TOOLS = {
8461
- json: ["jq"],
8462
- yaml: ["yq"],
8463
- html: ["html-to-markdown"],
8464
- xml: ["yq"],
8465
- csv: ["xan", "awk", "cut"],
8466
- toml: ["yq"],
8467
- ini: ["yq"]
8468
- };
8469
- var FORMAT_LABELS = {
8470
- json: "JSON",
8471
- yaml: "YAML",
8472
- html: "HTML",
8473
- xml: "XML",
8474
- csv: "CSV/TSV",
8475
- toml: "TOML",
8476
- ini: "INI"
8477
- };
8478
- var EXTENSION_FORMATS = {
8479
- ".json": "json",
8480
- ".jsonl": "json",
8481
- ".ndjson": "json",
8482
- ".yaml": "yaml",
8483
- ".yml": "yaml",
8484
- ".html": "html",
8485
- ".htm": "html",
8486
- ".xml": "xml",
8487
- ".svg": "xml",
8488
- ".csv": "csv",
8489
- ".tsv": "csv",
8490
- ".toml": "toml",
8491
- ".ini": "ini",
8492
- ".cfg": "ini",
8493
- ".conf": "ini"
8494
- };
8495
- function withBashExceptionCatch(sandbox) {
8496
- const decorated = {
8497
- async executeCommand(command, options) {
8498
- try {
8499
- return await sandbox.executeCommand(command, options);
8500
- } catch (error) {
8501
- if (error instanceof BashException) return error.format();
8502
- throw error;
8503
- }
8504
- },
8505
- readFile: (filePath, options) => sandbox.readFile(filePath, options),
8506
- writeFiles: (files) => sandbox.writeFiles(files),
8507
- exists: (filePath) => sandbox.exists(filePath),
8508
- dispose: () => sandbox.dispose(),
8509
- [Symbol.asyncDispose]() {
8510
- return decorated.dispose();
8511
- }
8512
- };
8513
- if (sandbox.spawn) {
8514
- const spawn5 = sandbox.spawn.bind(sandbox);
8515
- decorated.spawn = (command, options) => spawn5(command, options);
8516
- }
8517
- return decorated;
8518
- }
8519
8795
  function truncateOutput(output, maxLength, streamName) {
8520
8796
  if (output.length <= maxLength) return output;
8521
8797
  const removed = output.length - maxLength;
@@ -8530,6 +8806,9 @@ function makeTeeScriptPortable(script) {
8530
8806
  );
8531
8807
  return `set -o pipefail; ${withoutStatusAssignments}`;
8532
8808
  }
8809
+ function isTimeoutOf(signal, error) {
8810
+ return error === signal?.reason && error instanceof DOMException && error.name === "TimeoutError";
8811
+ }
8533
8812
  async function listInitialFiles(options) {
8534
8813
  const files = /* @__PURE__ */ new Map();
8535
8814
  if (options.uploadDirectory) {
@@ -8559,101 +8838,49 @@ async function listInitialFiles(options) {
8559
8838
  }
8560
8839
  return [...files.values()];
8561
8840
  }
8562
- async function uploadInitialFiles(sandbox, destination, files) {
8563
- for (let index = 0; index < files.length; index += WRITE_BATCH_SIZE) {
8564
- const batch = await Promise.all(
8565
- files.slice(index, index + WRITE_BATCH_SIZE).map(async (file) => ({
8566
- path: path4.posix.join(destination, file.path),
8567
- content: "content" in file ? file.content : await readFile(file.sourcePath)
8568
- }))
8841
+ async function uploadInitialFiles(sandbox, workingDirectory, files) {
8842
+ for (let index = 0; index < files.length; index += MAX_CONCURRENT_WRITES) {
8843
+ await Promise.all(
8844
+ files.slice(index, index + MAX_CONCURRENT_WRITES).map(async (file) => {
8845
+ const target = workingDirectory === void 0 ? file.path : path4.posix.join(workingDirectory, file.path);
8846
+ await ("content" in file ? sandbox.writeTextFile({ path: target, content: file.content }) : sandbox.writeBinaryFile({
8847
+ path: target,
8848
+ content: await readFile(file.sourcePath)
8849
+ }));
8850
+ })
8569
8851
  );
8570
- await sandbox.writeFiles(batch);
8571
8852
  }
8572
8853
  }
8573
- async function createToolPrompt(sandbox, filenames, customPrompt) {
8574
- if (customPrompt !== void 0) return customPrompt;
8575
- const result = await sandbox.executeCommand(
8576
- "ls /usr/bin /usr/local/bin /bin /sbin /usr/sbin 2>/dev/null"
8577
- );
8578
- const available = new Set(
8579
- result.stdout.split("\n").filter((entry) => KNOWN_TOOLS.has(entry))
8580
- );
8581
- if (available.has("js-exec")) available.delete("node");
8582
- if (available.size === 0) return "";
8583
- const lines = [
8584
- `Available tools: ${[...available].sort().join(", ")}, and more`
8585
- ];
8586
- const formats2 = new Set(
8587
- filenames.map(
8588
- (filename) => EXTENSION_FORMATS[path4.extname(filename).toLowerCase()]
8589
- ).filter((format) => format !== void 0)
8590
- );
8591
- for (const format of formats2) {
8592
- const tools = FORMAT_TOOLS[format].filter((name) => available.has(name));
8593
- if (tools.length > 0) {
8594
- lines.push(`For ${FORMAT_LABELS[format]}: ${tools.join(", ")}`);
8595
- }
8596
- }
8597
- return lines.join("\n");
8598
- }
8599
8854
  function createBashDescription(options) {
8600
- const lines = [
8601
- "Execute bash commands in the sandbox environment.",
8602
- "",
8603
- `WORKING DIRECTORY: ${options.destination}`,
8604
- "All commands execute from this directory. Use relative paths from here.",
8605
- ""
8606
- ];
8607
- if (options.filenames.length > 0) {
8608
- lines.push("Available files:");
8609
- for (const filename of options.filenames.slice(0, 8)) {
8610
- lines.push(` ${filename}`);
8611
- }
8612
- if (options.filenames.length > 8) {
8613
- lines.push(` ... and ${options.filenames.length - 8} more files`);
8614
- }
8615
- lines.push("");
8616
- }
8617
- if (options.toolPrompt) lines.push(options.toolPrompt, "");
8618
- lines.push(
8619
- "Common operations:",
8620
- " ls -la # List files with details",
8621
- " find . -name '*.ts' # Find files by pattern",
8622
- " grep -r 'pattern' . # Search file contents",
8623
- " cat <file> # View file contents",
8624
- ""
8625
- );
8626
- if (options.experimentalTeeTransform) {
8627
- lines.push(
8628
- "INTERMEDIATE OUTPUT CAPTURE:",
8629
- `Pipeline stdout is captured under ${TEE_OUTPUT_DIR}/.`,
8630
- "Use the returned teeFiles paths to inspect full intermediate output.",
8631
- ""
8632
- );
8633
- }
8634
- if (options.extraInstructions) {
8635
- lines.push(options.extraInstructions, "");
8636
- }
8637
- return lines.join("\n").trim();
8855
+ return [
8856
+ "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.",
8857
+ options.sandboxDescription,
8858
+ options.experimentalTeeTransform && `Pipeline stdout is captured under ${TEE_OUTPUT_DIR}/. Use the returned teeFiles paths to inspect full intermediate output.`,
8859
+ options.extraInstructions,
8860
+ REASONING_INSTRUCTION
8861
+ ].filter(Boolean).join("\n\n");
8638
8862
  }
8639
8863
  async function createBashTool(options) {
8640
- const destination = options.destination ?? DEFAULT_DESTINATION;
8864
+ const { workingDirectory } = options;
8865
+ const sandbox = "run" in options.sandbox ? options.sandbox : fromLegacySandbox(options.sandbox);
8641
8866
  const initialFiles = await listInitialFiles(options);
8642
- const sandbox = withBashExceptionCatch(options.sandbox);
8643
- await uploadInitialFiles(sandbox, destination, initialFiles);
8644
- const toolPrompt = await createToolPrompt(
8645
- sandbox,
8646
- initialFiles.map((file) => file.path),
8647
- options.promptOptions?.toolPrompt
8648
- );
8649
- const extraInstructions = [options.extraInstructions, REASONING_INSTRUCTION].filter(Boolean).join("\n\n");
8867
+ if (workingDirectory !== void 0) {
8868
+ const created = await sandbox.run({
8869
+ command: `mkdir -p -- ${shellQuote(workingDirectory)}`
8870
+ });
8871
+ if (created.exitCode !== 0) {
8872
+ throw new Error(
8873
+ `Could not set up working directory ${workingDirectory}: ${created.stderr}`
8874
+ );
8875
+ }
8876
+ }
8877
+ await uploadInitialFiles(sandbox, workingDirectory, initialFiles);
8650
8878
  const experimentalTeeTransform = options.experimentalTeeTransform ?? false;
8651
8879
  const bash = tool3({
8652
8880
  description: createBashDescription({
8653
- destination,
8654
- filenames: initialFiles.map((file) => file.path),
8655
- toolPrompt,
8656
- extraInstructions,
8881
+ workingDirectory,
8882
+ sandboxDescription: sandbox.description,
8883
+ extraInstructions: options.extraInstructions,
8657
8884
  experimentalTeeTransform
8658
8885
  }),
8659
8886
  inputSchema: z12.object({
@@ -8664,26 +8891,43 @@ async function createBashTool(options) {
8664
8891
  let command = originalCommand;
8665
8892
  const before = options.onBeforeBashCall?.({ command });
8666
8893
  if (before?.command !== void 0) command = before.command;
8667
- let fullCommand;
8894
+ let script = command;
8668
8895
  let teeFiles;
8669
8896
  if (experimentalTeeTransform) {
8670
8897
  const pipeline = new BashTransformPipeline().use(
8671
8898
  new TeePlugin({ outputDir: TEE_OUTPUT_DIR })
8672
8899
  );
8673
8900
  const transformed = pipeline.transform(command);
8674
- fullCommand = `mkdir -p ${shellQuote(TEE_OUTPUT_DIR)} ${shellQuote(destination)} && cd ${shellQuote(destination)} && ${makeTeeScriptPortable(transformed.script)}`;
8901
+ script = `mkdir -p ${shellQuote(TEE_OUTPUT_DIR)} && ${makeTeeScriptPortable(transformed.script)}`;
8675
8902
  teeFiles = transformed.metadata.teeFiles.map(
8676
8903
  (file) => ({
8677
8904
  command: file.command,
8678
8905
  stdoutFile: file.stdoutFile
8679
8906
  })
8680
8907
  );
8681
- } else {
8682
- fullCommand = `mkdir -p ${shellQuote(destination)} && cd ${shellQuote(destination)} && ${command}`;
8683
8908
  }
8684
- let result = await sandbox.executeCommand(fullCommand, {
8685
- signal: executionOptions.abortSignal
8686
- });
8909
+ const { abortSignal } = executionOptions;
8910
+ const startedAt = performance.now();
8911
+ let result;
8912
+ try {
8913
+ result = await sandbox.run({
8914
+ command: script,
8915
+ ...workingDirectory !== void 0 ? { workingDirectory } : {},
8916
+ abortSignal
8917
+ });
8918
+ } catch (error) {
8919
+ if (error instanceof BashException) {
8920
+ result = error.format();
8921
+ } else if (isTimeoutOf(abortSignal, error)) {
8922
+ result = {
8923
+ stdout: "",
8924
+ stderr: `Command timed out after ${Math.round(performance.now() - startedAt)} ms`,
8925
+ exitCode: COMMAND_TIMEOUT_EXIT_CODE
8926
+ };
8927
+ } else {
8928
+ throw error;
8929
+ }
8930
+ }
8687
8931
  const maxOutputLength = options.maxOutputLength ?? DEFAULT_MAX_OUTPUT_LENGTH;
8688
8932
  result = {
8689
8933
  ...result,
@@ -8698,7 +8942,7 @@ async function createBashTool(options) {
8698
8942
  return Object.keys(meta).length > 0 ? { ...result, meta } : result;
8699
8943
  }
8700
8944
  });
8701
- const readFile2 = createReadFileTool({ sandbox, destination });
8945
+ const readFileTool = createReadFileTool({ sandbox, workingDirectory });
8702
8946
  const writeFile2 = tool3({
8703
8947
  description: "Write content to a file in the sandbox. Creates parent directories if needed.",
8704
8948
  inputSchema: z12.object({
@@ -8707,12 +8951,10 @@ async function createBashTool(options) {
8707
8951
  }),
8708
8952
  execute: async ({ path: filePath, content }) => {
8709
8953
  try {
8710
- await sandbox.writeFiles([
8711
- {
8712
- path: path4.posix.resolve(destination, filePath),
8713
- content
8714
- }
8715
- ]);
8954
+ await sandbox.writeTextFile({
8955
+ path: workingDirectory === void 0 ? filePath : path4.posix.resolve(workingDirectory, filePath),
8956
+ content
8957
+ });
8716
8958
  return { success: true };
8717
8959
  } catch (error) {
8718
8960
  if (error instanceof BashException) return error.format();
@@ -8720,14 +8962,18 @@ async function createBashTool(options) {
8720
8962
  }
8721
8963
  }
8722
8964
  });
8723
- const tools = withHostOnlyToolMetadata2({ bash, readFile: readFile2, writeFile: writeFile2 });
8965
+ const tools = withHostOnlyToolMetadata2({
8966
+ bash,
8967
+ readFile: readFileTool,
8968
+ writeFile: writeFile2
8969
+ });
8724
8970
  return { bash: tools.bash, tools, sandbox };
8725
8971
  }
8726
8972
 
8727
8973
  // packages/context/src/lib/sandbox/binary-bridges.ts
8728
8974
  import { existsSync as existsSync2 } from "fs";
8729
8975
  import { defineCommand } from "just-bash";
8730
- import spawn2, { SubprocessError as SubprocessError3 } from "nano-spawn";
8976
+ import spawn2, { SubprocessError as SubprocessError2 } from "nano-spawn";
8731
8977
  import * as path5 from "path";
8732
8978
  function createBinaryBridges(...binaries) {
8733
8979
  return binaries.map((input) => {
@@ -8775,7 +9021,7 @@ function createBinaryBridges(...binaries) {
8775
9021
  exitCode: 0
8776
9022
  };
8777
9023
  } catch (error) {
8778
- if (error instanceof SubprocessError3) {
9024
+ if (error instanceof SubprocessError2) {
8779
9025
  if (hasErrorCode(error.cause, "ENOENT")) {
8780
9026
  return {
8781
9027
  stdout: "",
@@ -8793,7 +9039,7 @@ function createBinaryBridges(...binaries) {
8793
9039
  }
8794
9040
  return {
8795
9041
  stdout: "",
8796
- stderr: `${name}: ${error instanceof Error ? error.message : String(error)}`,
9042
+ stderr: `${name}: ${Error.isError(error) ? error.message : String(error)}`,
8797
9043
  exitCode: 127
8798
9044
  };
8799
9045
  }
@@ -8822,8 +9068,16 @@ function mapToRealPath(fs, cwd) {
8822
9068
  }
8823
9069
 
8824
9070
  // packages/context/src/lib/sandbox/daytona-sandbox.ts
8825
- import { randomUUID as randomUUID2 } from "node:crypto";
9071
+ import { randomUUID as randomUUID3 } from "node:crypto";
8826
9072
  import { setTimeout as setTimeout3 } from "node:timers/promises";
9073
+
9074
+ // packages/context/src/lib/sandbox/read-file.ts
9075
+ var decoder = new TextDecoder();
9076
+ function readFileContent(bytes, options) {
9077
+ return options?.encoding === "binary" ? bytes : decoder.decode(bytes);
9078
+ }
9079
+
9080
+ // packages/context/src/lib/sandbox/daytona-sandbox.ts
8827
9081
  var DAYTONA_DEFAULT_DESTINATION = "/home/daytona";
8828
9082
  var DAYTONA_EXIT_POLL_INTERVAL_MS = 250;
8829
9083
  var DAYTONA_EXIT_POLL_TIMEOUT_MS = 3e4;
@@ -9056,7 +9310,7 @@ function createDaytonaSandboxMethods(args) {
9056
9310
  return {
9057
9311
  executeCommand,
9058
9312
  async spawn(command, options) {
9059
- const sessionId = `deepagents-spawn-${randomUUID2()}`;
9313
+ const sessionId = `deepagents-spawn-${randomUUID3()}`;
9060
9314
  const stdout = createTextReadable();
9061
9315
  const stderr = createTextReadable();
9062
9316
  const signal = options?.signal;
@@ -9298,7 +9552,7 @@ function compactObject(input) {
9298
9552
  return output;
9299
9553
  }
9300
9554
  function toError(error) {
9301
- return error instanceof Error ? error : new Error(String(error));
9555
+ return Error.isError(error) ? error : new Error(String(error));
9302
9556
  }
9303
9557
 
9304
9558
  // packages/context/src/lib/sandbox/docker-sandbox.ts
@@ -9307,18 +9561,18 @@ import {
9307
9561
  ConnectionFailedError,
9308
9562
  ContainerNotFoundError,
9309
9563
  Docker,
9564
+ DockerEngineError,
9310
9565
  DockerError,
9311
9566
  ImageNotFoundError,
9312
9567
  NameConflictError,
9313
9568
  NotAFileError,
9314
- VolumeInUseError
9569
+ PathNotFoundError
9315
9570
  } from "@zukhruf/docker";
9316
- import spawn3, { SubprocessError as SubprocessError4 } from "nano-spawn";
9571
+ import spawn3, { SubprocessError as SubprocessError3 } from "nano-spawn";
9317
9572
  import { spawn as childSpawn2 } from "node:child_process";
9318
- import { hash, randomUUID as randomUUID3 } from "node:crypto";
9573
+ import { hash } from "node:crypto";
9319
9574
  import { readFileSync as readFileSync2 } from "node:fs";
9320
- import { posix as posix2 } from "node:path";
9321
- import { setTimeout as delay } from "node:timers/promises";
9575
+ import { posix as posix3 } from "node:path";
9322
9576
  function isDockerfileOptions(opts) {
9323
9577
  return "dockerfile" in opts;
9324
9578
  }
@@ -9489,6 +9743,7 @@ function runDockerBuild(args, stdin, showBuildLogs, env) {
9489
9743
  return new Promise((resolve3, reject) => {
9490
9744
  const child = childSpawn2("docker", args, { stdio, env });
9491
9745
  let stderr = "";
9746
+ child.stderr?.setEncoding("utf8");
9492
9747
  child.stderr?.on("data", (chunk) => {
9493
9748
  stderr += chunk;
9494
9749
  });
@@ -9524,7 +9779,7 @@ async function startContainer(container, image) {
9524
9779
  throw new ContainerCreationError(
9525
9780
  messageOf(error),
9526
9781
  image,
9527
- error instanceof Error ? error : void 0
9782
+ Error.isError(error) ? error : void 0
9528
9783
  );
9529
9784
  }
9530
9785
  }
@@ -9546,10 +9801,7 @@ var dockerErrors = {
9546
9801
  volumeInspect: (name, reason) => new VolumeInspectError(name, reason),
9547
9802
  volumeCreate: (name, reason) => new VolumeCreateError(name, reason)
9548
9803
  };
9549
- function withoutFinalNewline(text) {
9550
- return text.replace(/\r?\n$/, "");
9551
- }
9552
- function sandboxProcess(process2) {
9804
+ function engineProcess2(process2) {
9553
9805
  const queue = { highWaterMark: Number.POSITIVE_INFINITY };
9554
9806
  const stdout = new TransformStream(
9555
9807
  void 0,
@@ -9565,7 +9817,7 @@ function sandboxProcess(process2) {
9565
9817
  stdout: stdout.writable.getWriter(),
9566
9818
  stderr: stderr.writable.getWriter()
9567
9819
  };
9568
- const exit = (async () => {
9820
+ const exitCode = (async () => {
9569
9821
  try {
9570
9822
  for await (const { stream, data } of process2) {
9571
9823
  await writers[stream].write(data);
@@ -9578,40 +9830,15 @@ function sandboxProcess(process2) {
9578
9830
  throw error;
9579
9831
  }
9580
9832
  await Promise.all([writers.stdout.close(), writers.stderr.close()]);
9581
- const code = await process2.exitCode;
9582
- return { code, signal: null, success: code === 0 };
9833
+ return process2.exitCode;
9583
9834
  })();
9584
- return { stdout: stdout.readable, stderr: stderr.readable, exit };
9585
- }
9586
- function managedDockerCommand(command, controlPath, commandTimeout) {
9587
- return [
9588
- "set -m",
9589
- `control=${shellQuote(controlPath)}`,
9590
- ': > "$control" || exit 1',
9591
- "timer=",
9592
- `trap 'if [ -n "$timer" ]; then kill -TERM "$timer" 2>/dev/null || :; wait "$timer" 2>/dev/null || :; fi; rm -f "$control" "$control.timeout"' EXIT`,
9593
- `bash -lc ${shellQuote(command)} &`,
9594
- "pid=$!",
9595
- `printf '%s\\n' "$pid" > "$control"`,
9596
- ...commandTimeout ? [
9597
- // Keep the deadline on the engine host: SSH setup/round trips must not
9598
- // let the command run past its execution budget.
9599
- "(",
9600
- `sleep ${commandTimeout / 1e3} &`,
9601
- "alarm=$!",
9602
- `trap 'kill "$alarm" 2>/dev/null || :; wait "$alarm" 2>/dev/null || :; exit 0' TERM`,
9603
- 'wait "$alarm" || exit',
9604
- 'if kill -0 -- "-$pid" 2>/dev/null; then : > "$control.timeout"; kill -KILL -- "-$pid" 2>/dev/null || :; fi',
9605
- ") &",
9606
- "timer=$!"
9607
- ] : [],
9608
- 'wait "$pid"',
9609
- "status=$?",
9610
- '[ ! -e "$control.timeout" ] || exit 124',
9611
- 'exit "$status"'
9612
- ].join("\n");
9835
+ return {
9836
+ stdout: stdout.readable,
9837
+ stderr: stderr.readable,
9838
+ ...process2.stdin ? { stdin: process2.stdin } : {},
9839
+ exitCode
9840
+ };
9613
9841
  }
9614
- var MAX_SYMLINK_HOPS = 40;
9615
9842
  var KERNEL_FILESYSTEMS = ["/proc", "/sys", "/dev"];
9616
9843
  var RESOLVE_OWNER = [
9617
9844
  "user=$1 group=$2",
@@ -9646,284 +9873,151 @@ async function resolveOwner(container, user2) {
9646
9873
  return { uid, gid };
9647
9874
  }
9648
9875
  function messageOf(error) {
9649
- return error instanceof Error ? error.message : String(error);
9876
+ return Error.isError(error) ? error.message : String(error);
9877
+ }
9878
+ function isUnexplainedFailure(error) {
9879
+ return error instanceof DockerEngineError && error.status === 500;
9880
+ }
9881
+ function fileType(mode) {
9882
+ const DIRECTORY = 2147483648;
9883
+ const LINK_DEVICE_PIPE_SOCKET_IRREGULAR = 254279680;
9884
+ if ((mode & DIRECTORY) !== 0) return "directory";
9885
+ return (mode & LINK_DEVICE_PIPE_SOCKET_IRREGULAR) === 0 ? "file" : "other";
9650
9886
  }
9651
9887
  var DockerContainer = class {
9652
9888
  name;
9889
+ workdir;
9890
+ commandTimeout;
9653
9891
  #container;
9654
- #layout;
9892
+ #execOnly;
9655
9893
  /** Who owns the files the sandbox writes: the container user, or root. */
9656
9894
  #owner;
9657
- #commandTimeout;
9658
- constructor(name, container, layout, owner, commandTimeout) {
9895
+ #autoRemove;
9896
+ constructor(name, container, layout, owner, commandTimeout, autoRemove) {
9659
9897
  this.name = name;
9898
+ this.workdir = layout.workdir;
9899
+ this.commandTimeout = commandTimeout;
9660
9900
  this.#container = container;
9661
- this.#layout = layout;
9901
+ this.#execOnly = layout.execOnly;
9662
9902
  this.#owner = owner;
9663
- this.#commandTimeout = commandTimeout;
9903
+ this.#autoRemove = autoRemove;
9664
9904
  }
9665
- /** `command` under `bash -lc`, with the spawn options' directory and environment. */
9666
- #bash(command, options = {}) {
9667
- const env = Object.entries(options.env ?? {}).map(([key, value]) => {
9668
- if (key.length === 0 || key.includes("=")) {
9669
- throw new DockerSandboxError(
9670
- `Invalid environment variable key: "${key}"`
9671
- );
9672
- }
9673
- return `${key}=${value}`;
9674
- });
9905
+ #config(argv, { workingDirectory, env = {} }) {
9675
9906
  return {
9676
- Cmd: ["bash", "-lc", command],
9677
- Env: env,
9678
- ...options.cwd ? { WorkingDir: options.cwd } : {}
9907
+ Cmd: argv,
9908
+ Env: Object.entries(env).map(([key, value]) => `${key}=${value}`),
9909
+ ...workingDirectory ? { WorkingDir: workingDirectory } : {}
9679
9910
  };
9680
9911
  }
9681
- async #exec(config) {
9912
+ async exec(argv, options = {}) {
9682
9913
  try {
9683
- const { stdout, stderr, exitCode } = await this.#container.exec(config);
9684
- return {
9685
- stdout: withoutFinalNewline(stdout),
9686
- stderr: withoutFinalNewline(stderr),
9687
- exitCode
9688
- };
9914
+ const { stdout, stderr, exitCode } = await this.#container.exec(
9915
+ this.#config(argv, options),
9916
+ { signal: options.signal, stdin: options.stdin }
9917
+ );
9918
+ return { stdout, stderr, exitCode };
9689
9919
  } catch (error) {
9690
9920
  if (!(error instanceof DockerError)) throw error;
9691
9921
  return { stdout: "", stderr: error.message, exitCode: 1 };
9692
9922
  }
9693
9923
  }
9694
- async executeCommand(command, options = {}) {
9695
- if (!this.#commandTimeout && options.signal === void 0) {
9696
- return this.#exec(this.#bash(command));
9697
- }
9698
- const process2 = await this.spawn(command, { signal: options.signal });
9699
- const [stdout, stderr, info] = await Promise.all([
9700
- new Response(process2.stdout).text(),
9701
- new Response(process2.stderr).text(),
9702
- process2.exit
9703
- ]);
9704
- const result = {
9705
- stdout: withoutFinalNewline(stdout),
9706
- stderr: withoutFinalNewline(stderr)
9707
- };
9708
- if (info.signal === "SIGKILL") {
9709
- return {
9710
- ...result,
9711
- stderr: result.stderr || "Command aborted",
9712
- exitCode: 1
9713
- };
9714
- }
9715
- return { ...result, exitCode: info.code ?? 1 };
9716
- }
9717
- async spawn(command, options = {}) {
9718
- if (!this.#commandTimeout && options.signal === void 0) {
9719
- return sandboxProcess(
9720
- await this.#container.spawn(this.#bash(command, options))
9721
- );
9722
- }
9723
- const controlPath = `/dev/shm/deepagents-exec-${randomUUID3()}.pid`;
9724
- const execution = sandboxProcess(
9725
- await this.#container.spawn(
9726
- this.#bash(
9727
- managedDockerCommand(command, controlPath, this.#commandTimeout),
9728
- options
9729
- )
9730
- )
9731
- );
9732
- let termination;
9733
- const onAbort = () => {
9734
- termination ??= this.#terminate(controlPath, execution.exit);
9735
- void termination.catch(() => {
9736
- });
9737
- };
9738
- if (options.signal?.aborted) onAbort();
9739
- else options.signal?.addEventListener("abort", onAbort, { once: true });
9740
- return {
9741
- stdout: execution.stdout,
9742
- stderr: execution.stderr,
9743
- exit: execution.exit.then(async (info) => {
9744
- const activeTermination = termination;
9745
- if (!activeTermination || !await activeTermination) {
9746
- return info;
9747
- }
9748
- return { code: null, signal: "SIGKILL", success: false };
9749
- }).finally(() => {
9750
- options.signal?.removeEventListener("abort", onAbort);
9924
+ async spawn(argv, options) {
9925
+ return engineProcess2(
9926
+ await this.#container.spawn(this.#config(argv, options), {
9927
+ stdin: options.stdin
9751
9928
  })
9752
- };
9753
- }
9754
- /** The PID that the managed command wrote, or `undefined` once it exited. */
9755
- async #managedPid(controlPath, exit) {
9756
- const exited = exit.then(
9757
- () => true,
9758
- () => true
9759
9929
  );
9760
- const readPid = `if IFS= read -r pid < ${shellQuote(controlPath)}; then printf '%s' "$pid"; fi`;
9761
- while (true) {
9762
- const { stdout } = await this.#container.exec(this.#bash(readPid));
9763
- if (stdout) return Number(stdout);
9764
- if (await Promise.race([exited, delay(10).then(() => false)])) {
9765
- return void 0;
9766
- }
9767
- }
9768
- }
9769
- /** Kills the managed command's process group; `true` when it was still running. */
9770
- async #terminate(controlPath, exit) {
9771
- const pid = await this.#managedPid(controlPath, exit);
9772
- if (pid === void 0) return false;
9773
- const { stdout } = await this.#container.exec(
9774
- this.#bash(
9775
- [
9776
- `pid=${pid}`,
9777
- `IFS= read -r control_pid < ${shellQuote(controlPath)} || exit 0`,
9778
- '[ "$control_pid" = "$pid" ] || exit 0',
9779
- 'kill -KILL -- "-$pid" 2>/dev/null || exit 0',
9780
- "group_alive() {",
9781
- " local stat rest state pgrp",
9782
- " for stat_path in /proc/[0-9]*/stat; do",
9783
- ' IFS= read -r stat < "$stat_path" || continue',
9784
- " rest=${stat##*) }",
9785
- ' read -r state _ pgrp _ <<< "$rest"',
9786
- ' if [ "$pgrp" = "$pid" ] && [ "$state" != Z ]; then return 0; fi',
9787
- " done",
9788
- " return 1",
9789
- "}",
9790
- "while group_alive; do sleep 0.01; done",
9791
- "printf terminated"
9792
- ].join("\n")
9793
- )
9794
- );
9795
- return stdout === "terminated";
9796
9930
  }
9797
9931
  #resolve(path6) {
9798
- return posix2.resolve(this.#layout.workdir, path6);
9932
+ return posix3.resolve(this.workdir, path6);
9799
9933
  }
9800
9934
  /** The archive requests cannot reach a tmpfs mount or a kernel filesystem. */
9801
9935
  #isExecOnly(path6) {
9802
- return this.#layout.execOnly.some(
9936
+ return this.#execOnly.some(
9803
9937
  (root) => path6 === root || path6.startsWith(`${root}/`)
9804
9938
  );
9805
9939
  }
9806
- async readFile(path6) {
9940
+ /** The stat after symbolic links, which the engine's stat does not follow. */
9941
+ async #followLinks(path6, signal) {
9942
+ let target = path6;
9943
+ while (true) {
9944
+ const stat = await this.#container.stat(target, { signal });
9945
+ if (!stat) return void 0;
9946
+ if (stat.linkTarget === "") return { path: target, stat };
9947
+ target = posix3.resolve(posix3.dirname(target), stat.linkTarget);
9948
+ }
9949
+ }
9950
+ async readFile(path6, signal) {
9807
9951
  const target = this.#resolve(path6);
9952
+ if (this.#isExecOnly(target)) {
9953
+ return readFileOverExec(this, target, signal);
9954
+ }
9808
9955
  try {
9809
- return this.#isExecOnly(target) ? await this.#readByExec(target) : await this.#readArchive(target);
9956
+ return await this.#container.readFile(target, { signal });
9810
9957
  } catch (error) {
9811
- throw new Error(`Failed to read file "${path6}": ${messageOf(error)}`, {
9812
- cause: error
9813
- });
9958
+ if (error instanceof PathNotFoundError) return null;
9959
+ if (isUnexplainedFailure(error)) {
9960
+ return readFileOverExec(this, target, signal);
9961
+ }
9962
+ if (!(error instanceof NotAFileError && error.kind === "symlink")) {
9963
+ throw error;
9964
+ }
9814
9965
  }
9966
+ const followed = await this.#followLinks(target, signal);
9967
+ return followed ? this.#container.readFile(followed.path, { signal }) : null;
9815
9968
  }
9816
- /** Follows symbolic links, as reading through the container's shell does. */
9817
- async #readArchive(path6) {
9818
- let target = path6;
9819
- for (let hops = 0; ; hops++) {
9820
- try {
9821
- return await this.#container.readFile(target);
9822
- } catch (error) {
9823
- if (!(error instanceof NotAFileError && error.kind === "symlink") || hops === MAX_SYMLINK_HOPS) {
9824
- throw error;
9825
- }
9826
- const stat = await this.#container.stat(target);
9827
- if (!stat) throw error;
9828
- target = posix2.resolve(posix2.dirname(target), stat.linkTarget);
9969
+ async stat(path6, signal) {
9970
+ const target = this.#resolve(path6);
9971
+ if (this.#isExecOnly(target)) return statOverExec(this, target, signal);
9972
+ try {
9973
+ const followed = await this.#followLinks(target, signal);
9974
+ return followed ? { type: fileType(followed.stat.mode), size: followed.stat.size } : null;
9975
+ } catch (error) {
9976
+ if (isUnexplainedFailure(error)) {
9977
+ return statOverExec(this, target, signal);
9829
9978
  }
9979
+ throw error;
9830
9980
  }
9831
9981
  }
9832
- async #readByExec(path6) {
9833
- const process2 = await this.#container.spawn({ Cmd: ["cat", "--", path6] });
9834
- const stdout = [];
9835
- const stderr = [];
9836
- for await (const { stream, data } of process2) {
9837
- (stream === "stdout" ? stdout : stderr).push(data);
9838
- }
9839
- if (await process2.exitCode !== 0) {
9840
- throw new Error(Buffer.concat(stderr).toString("utf-8").trim());
9982
+ async writeFile(path6, content, signal) {
9983
+ const target = this.#resolve(path6);
9984
+ if (this.#isExecOnly(target)) {
9985
+ return writeFileOverExec(this, target, content, signal);
9841
9986
  }
9842
- return Buffer.concat(stdout);
9843
- }
9844
- async writeFiles(files) {
9845
- const resolved = files.map(({ path: path6, content }) => ({
9846
- path: this.#resolve(path6),
9847
- content
9848
- }));
9849
- const byArchive = resolved.filter(({ path: path6 }) => !this.#isExecOnly(path6));
9850
- if (byArchive.length > 0) {
9851
- try {
9852
- const owner = this.#owner;
9853
- const directories = owner ? await this.#missingDirectories(
9854
- byArchive.map(({ path: path6 }) => posix2.dirname(path6))
9855
- ) : [];
9856
- await this.#container.writeFiles([
9857
- ...directories.map((path6) => ({
9858
- path: path6,
9987
+ try {
9988
+ const owner = this.#owner;
9989
+ const directories = owner ? await this.#missingDirectories(posix3.dirname(target), signal) : [];
9990
+ await this.#container.writeFiles(
9991
+ [
9992
+ ...directories.map((directory) => ({
9993
+ path: directory,
9859
9994
  directory: true,
9860
9995
  ...owner
9861
9996
  })),
9862
- ...byArchive.map(({ path: path6, content }) => ({
9863
- path: path6,
9864
- data: content,
9865
- ...owner
9866
- }))
9867
- ]);
9868
- } catch (error) {
9869
- throw new Error(
9870
- `Failed to write file "${byArchive.map(({ path: path6 }) => path6).join('", "')}": ${messageOf(error)}`,
9871
- { cause: error }
9872
- );
9873
- }
9874
- }
9875
- for (const { path: path6, content } of resolved.filter(
9876
- ({ path: path7 }) => this.#isExecOnly(path7)
9877
- )) {
9878
- const result = await this.#container.exec(
9879
- {
9880
- Cmd: [
9881
- "sh",
9882
- "-c",
9883
- 'mkdir -p "$(dirname "$1")" && cat > "$1"',
9884
- "sh",
9885
- path6
9886
- ]
9887
- },
9888
- { stdin: content }
9997
+ { path: target, data: content, ...owner }
9998
+ ],
9999
+ { signal }
9889
10000
  );
9890
- if (result.exitCode !== 0) {
9891
- throw new Error(`Failed to write file "${path6}": ${result.stderr}`);
9892
- }
9893
- }
9894
- }
9895
- /** The directories, parents first, that a write into `directories` creates. */
9896
- async #missingDirectories(directories) {
9897
- const missing = /* @__PURE__ */ new Set();
9898
- for (const start of new Set(directories)) {
9899
- for (let directory = start; directory !== "/" && !missing.has(directory); directory = posix2.dirname(directory)) {
9900
- if (await this.#container.stat(directory)) break;
9901
- missing.add(directory);
9902
- }
9903
- }
9904
- return [...missing].sort((a, b) => a.length - b.length);
9905
- }
9906
- async exists(path6) {
9907
- let target = this.#resolve(path6);
9908
- if (this.#isExecOnly(target)) {
9909
- const { exitCode } = await this.#container.exec({
9910
- Cmd: ["test", "-e", target]
10001
+ } catch (error) {
10002
+ throw new Error(`Failed to write file "${path6}": ${messageOf(error)}`, {
10003
+ cause: error
9911
10004
  });
9912
- return exitCode === 0;
9913
10005
  }
9914
- for (let hops = 0; hops <= MAX_SYMLINK_HOPS; hops++) {
9915
- const stat = await this.#container.stat(target);
9916
- if (!stat) return false;
9917
- if (stat.linkTarget === "") return true;
9918
- target = posix2.resolve(posix2.dirname(target), stat.linkTarget);
10006
+ }
10007
+ /** The directories, parents first, that a write into `start` creates. */
10008
+ async #missingDirectories(start, signal) {
10009
+ const missing = [];
10010
+ for (let directory = start; directory !== "/"; directory = posix3.dirname(directory)) {
10011
+ if (await this.#container.stat(directory, { signal })) break;
10012
+ missing.unshift(directory);
9919
10013
  }
9920
- return false;
10014
+ return missing;
9921
10015
  }
9922
10016
  installerContext(image) {
9923
10017
  return createInstallerContext(
9924
10018
  {
9925
10019
  // Installers run with `sh -c`, before the sandbox knows Bash exists.
9926
- exec: (command) => this.#exec({ Cmd: ["sh", "-c", command] }),
10020
+ exec: (command) => this.exec(["sh", "-c", command]),
9927
10021
  SandboxError: DockerSandboxError
9928
10022
  },
9929
10023
  this.name,
@@ -9933,6 +10027,9 @@ var DockerContainer = class {
9933
10027
  async stop() {
9934
10028
  try {
9935
10029
  await this.#container.stop();
10030
+ if (this.#autoRemove) {
10031
+ await this.#container.wait({ condition: "removed" });
10032
+ }
9936
10033
  } catch (error) {
9937
10034
  if (error instanceof ContainerNotFoundError) return;
9938
10035
  throw error;
@@ -9971,7 +10068,8 @@ var DockerEngine = class _DockerEngine {
9971
10068
  container,
9972
10069
  layout,
9973
10070
  await resolveOwner(container, layout.user),
9974
- this.#commandTimeout
10071
+ this.#commandTimeout,
10072
+ info.HostConfig?.AutoRemove === true
9975
10073
  );
9976
10074
  }
9977
10075
  async attach(name, image) {
@@ -10032,16 +10130,16 @@ var DockerEngine = class _DockerEngine {
10032
10130
  );
10033
10131
  if (volume) {
10034
10132
  return new VolumePathError(
10035
- error.source,
10133
+ volume.hostPath,
10036
10134
  volume.containerPath,
10037
10135
  "hostPath does not exist on host"
10038
10136
  );
10039
10137
  }
10040
10138
  }
10041
10139
  return new ContainerCreationError(
10042
- error instanceof Error ? error.message : String(error),
10140
+ Error.isError(error) ? error.message : String(error),
10043
10141
  image,
10044
- error instanceof Error ? error : void 0
10142
+ Error.isError(error) ? error : void 0
10045
10143
  );
10046
10144
  }
10047
10145
  async volumeExists(name) {
@@ -10053,7 +10151,7 @@ var DockerEngine = class _DockerEngine {
10053
10151
  }
10054
10152
  throw new VolumeInspectError(
10055
10153
  name,
10056
- error instanceof Error ? error.message : String(error)
10154
+ Error.isError(error) ? error.message : String(error)
10057
10155
  );
10058
10156
  }
10059
10157
  }
@@ -10071,29 +10169,18 @@ var DockerEngine = class _DockerEngine {
10071
10169
  }
10072
10170
  throw new VolumeCreateError(
10073
10171
  volume.name,
10074
- error instanceof NameConflictError ? "managed volume already exists" : error instanceof Error ? error.message : String(error)
10172
+ error instanceof NameConflictError ? "managed volume already exists" : Error.isError(error) ? error.message : String(error)
10075
10173
  );
10076
10174
  }
10077
10175
  }
10078
10176
  async removeVolume(name) {
10079
- const deadline = performance.now() + 3e4;
10080
- while (true) {
10081
- try {
10082
- await this.docker.volumes.find(name).then((volume) => volume?.remove());
10083
- return;
10084
- } catch (error) {
10085
- if (error instanceof VolumeInUseError && performance.now() < deadline) {
10086
- await delay(25);
10087
- continue;
10088
- }
10089
- if (error instanceof ConnectionFailedError) {
10090
- throw new DockerNotAvailableError();
10091
- }
10092
- throw new VolumeRemoveError(
10093
- name,
10094
- error instanceof Error ? error.message : String(error)
10095
- );
10177
+ try {
10178
+ await this.docker.volumes.find(name).then((volume) => volume?.remove());
10179
+ } catch (error) {
10180
+ if (error instanceof ConnectionFailedError) {
10181
+ throw new DockerNotAvailableError();
10096
10182
  }
10183
+ throw new VolumeRemoveError(name, messageOf(error));
10097
10184
  }
10098
10185
  }
10099
10186
  async ensureWorkdir() {
@@ -10151,7 +10238,7 @@ var ComposeStrategy = class extends ContainerSandboxStrategy {
10151
10238
  } catch (error) {
10152
10239
  throw new ComposeStartError(
10153
10240
  this.composeFile,
10154
- error instanceof SubprocessError4 && error.stderr || (error instanceof Error ? error.message : String(error))
10241
+ error instanceof SubprocessError3 && error.stderr || (Error.isError(error) ? error.message : String(error))
10155
10242
  );
10156
10243
  }
10157
10244
  const { containers } = this.dockerEngine.docker;
@@ -10227,21 +10314,17 @@ async function createDockerSandbox(options = {}) {
10227
10314
  return strategy.create();
10228
10315
  }
10229
10316
  async function useSandbox(options, fn) {
10230
- const sandbox = await createDockerSandbox(options);
10231
- try {
10232
- return await fn(sandbox);
10233
- } finally {
10234
- await sandbox.dispose();
10235
- }
10317
+ await using sandbox = await createDockerSandbox(options);
10318
+ return await fn(sandbox);
10236
10319
  }
10237
10320
 
10238
10321
  // packages/context/src/lib/sandbox/strace/file-changes.ts
10239
10322
  import { randomUUID as randomUUID4 } from "node:crypto";
10240
- import { posix as posix4 } from "node:path";
10323
+ import { posix as posix5 } from "node:path";
10241
10324
 
10242
10325
  // packages/context/src/lib/sandbox/strace/index.ts
10243
- import spawn4, { SubprocessError as SubprocessError5 } from "nano-spawn";
10244
- import { posix as posix3 } from "node:path";
10326
+ import spawn4, { SubprocessError as SubprocessError4 } from "nano-spawn";
10327
+ import { posix as posix4 } from "node:path";
10245
10328
  var STRACE_FLAGS = "-f -y -qq -e trace=%file,write,pwrite64,writev";
10246
10329
  function buildStraceCommand(command, traceFile, traceDir) {
10247
10330
  return `mkdir -p ${shellQuote(traceDir)} 2>/dev/null; strace ${STRACE_FLAGS} -o ${shellQuote(traceFile)} -- bash -lc ${shellQuote(command)}`;
@@ -10359,14 +10442,14 @@ function openFlags(args) {
10359
10442
  return args.match(/\bO_[A-Z_]+(?:\|O_[A-Z_]+)*/)?.[0] ?? "";
10360
10443
  }
10361
10444
  function matchesGlobs(path6, include, exclude) {
10362
- return include.some((glob) => posix3.matchesGlob(path6, glob)) && !exclude?.some((glob) => posix3.matchesGlob(path6, glob));
10445
+ return include.some((glob) => posix4.matchesGlob(path6, glob)) && !exclude?.some((glob) => posix4.matchesGlob(path6, glob));
10363
10446
  }
10364
10447
  function parseStraceTrace(raw, options) {
10365
10448
  const { include, exclude, traceDir, traceFile } = options;
10366
10449
  const now = Date.now();
10367
10450
  const state = /* @__PURE__ */ new Map();
10368
10451
  const renames = [];
10369
- const resolve3 = (dir, p) => posix3.normalize(p.startsWith("/") ? p : posix3.join(dir, p));
10452
+ const resolve3 = (dir, p) => posix4.normalize(p.startsWith("/") ? p : posix4.join(dir, p));
10370
10453
  const write = (path6) => {
10371
10454
  state.set(path6, "write");
10372
10455
  };
@@ -10380,10 +10463,11 @@ function parseStraceTrace(raw, options) {
10380
10463
  const { syscall, args } = call;
10381
10464
  const dir = dirfdPath(args);
10382
10465
  if (RENAME_SYSCALLS.has(syscall)) {
10383
- const strings = quotedStrings(args);
10384
- if (strings.length < 2) continue;
10385
- const from = resolve3(dir, strings[0]);
10386
- const to = resolve3(dir, strings[strings.length - 1]);
10466
+ const [first2, ...rest] = quotedStrings(args);
10467
+ const last = rest.at(-1);
10468
+ if (last === void 0) continue;
10469
+ const from = resolve3(dir, first2);
10470
+ const to = resolve3(dir, last);
10387
10471
  state.delete(from);
10388
10472
  renames.push({ from, to });
10389
10473
  continue;
@@ -10399,8 +10483,8 @@ function parseStraceTrace(raw, options) {
10399
10483
  continue;
10400
10484
  }
10401
10485
  if (LINK_SYSCALLS.has(syscall)) {
10402
- const strings = quotedStrings(args);
10403
- if (strings.length) write(resolve3(dir, strings[strings.length - 1]));
10486
+ const last = quotedStrings(args).at(-1);
10487
+ if (last !== void 0) write(resolve3(dir, last));
10404
10488
  continue;
10405
10489
  }
10406
10490
  if (OPEN_SYSCALLS.has(syscall)) {
@@ -10411,7 +10495,7 @@ function parseStraceTrace(raw, options) {
10411
10495
  }
10412
10496
  if (WRITE_SYSCALLS.has(syscall)) {
10413
10497
  const p = fdPath(args);
10414
- if (p && Number(call.retval) > 0) write(posix3.normalize(p));
10498
+ if (p && Number(call.retval) > 0) write(posix4.normalize(p));
10415
10499
  continue;
10416
10500
  }
10417
10501
  if (TRUNCATE_SYSCALLS.has(syscall)) {
@@ -10465,18 +10549,15 @@ async function withStraceFileChanges(sandbox, options) {
10465
10549
  const { include, exclude, onFileChanges } = options;
10466
10550
  const onError = options.onError ?? warnOnFileChangesError;
10467
10551
  const traceDir = options.traceDir ?? DEFAULT_TRACE_DIR;
10468
- const innerExecute = sandbox.executeCommand.bind(sandbox);
10469
- const innerWriteFiles = sandbox.writeFiles.bind(sandbox);
10470
- const removeTrace = (traceFile) => void innerExecute(`rm -f ${shellQuote(traceFile)}`).catch(() => {
10552
+ const inner = "run" in sandbox ? sandbox : fromLegacySandbox(sandbox);
10553
+ const removeTrace = (traceFile) => void Promise.resolve(
10554
+ inner.run({ command: `rm -f ${shellQuote(traceFile)}` })
10555
+ ).catch(() => {
10471
10556
  });
10472
10557
  const readChanges = async (traceFile) => {
10473
10558
  try {
10474
- return parseStraceTrace(await sandbox.readFile(traceFile), {
10475
- include,
10476
- exclude,
10477
- traceFile,
10478
- traceDir
10479
- });
10559
+ const trace = await inner.readTextFile({ path: traceFile });
10560
+ return trace === null ? [] : parseStraceTrace(trace, { include, exclude, traceFile, traceDir });
10480
10561
  } catch {
10481
10562
  return [];
10482
10563
  } finally {
@@ -10492,19 +10573,60 @@ async function withStraceFileChanges(sandbox, options) {
10492
10573
  onError(error);
10493
10574
  }
10494
10575
  };
10495
- const decorated = {
10496
- async executeCommand(command, execOptions) {
10576
+ let baseDirectory;
10577
+ const absolutePath = async (path6) => {
10578
+ if (posix5.isAbsolute(path6)) return posix5.normalize(path6);
10579
+ baseDirectory ??= Promise.resolve(inner.run({ command: "pwd" })).then(
10580
+ ({ stdout }) => stdout.trimEnd()
10581
+ );
10582
+ return posix5.resolve(await baseDirectory, path6);
10583
+ };
10584
+ const observe = async (op, filePath) => {
10585
+ const path6 = await absolutePath(filePath);
10586
+ if (!matchesGlobs(path6, include, exclude)) return;
10587
+ await onFileChanges?.([{ op, path: path6, timestamp: Date.now() }]);
10588
+ };
10589
+ async function spawn5(spawnOptions) {
10590
+ const traceFile = `${traceDir}/${randomUUID4()}.strace`;
10591
+ const child = await inner.spawn({
10592
+ ...spawnOptions,
10593
+ command: buildStraceCommand(spawnOptions.command, traceFile, traceDir)
10594
+ });
10595
+ const exit = Promise.resolve(child.wait()).finally(
10596
+ () => collectSpawn(traceFile).catch(() => {
10597
+ })
10598
+ );
10599
+ exit.catch(() => {
10600
+ });
10601
+ return {
10602
+ stdout: child.stdout,
10603
+ stderr: child.stderr,
10604
+ ..."stdin" in child ? { stdin: child.stdin } : {},
10605
+ wait: () => exit,
10606
+ kill: () => child.kill()
10607
+ };
10608
+ }
10609
+ const dispose = async () => {
10610
+ await Promise.resolve(
10611
+ inner.run({ command: `rm -rf ${shellQuote(traceDir)}` })
10612
+ ).catch(() => {
10613
+ });
10614
+ await inner.dispose();
10615
+ };
10616
+ return {
10617
+ description: inner.description,
10618
+ async run(runOptions) {
10497
10619
  const traceFile = `${traceDir}/${randomUUID4()}.strace`;
10498
10620
  const sentinel = `__dat_trace_${randomUUID4()}__`;
10499
10621
  const wrapped = buildTracedCommand(
10500
- command,
10622
+ runOptions.command,
10501
10623
  traceFile,
10502
10624
  traceDir,
10503
10625
  sentinel
10504
10626
  );
10505
10627
  let raw;
10506
10628
  try {
10507
- raw = await innerExecute(wrapped, execOptions);
10629
+ raw = await inner.run({ ...runOptions, command: wrapped });
10508
10630
  } catch (error) {
10509
10631
  removeTrace(traceFile);
10510
10632
  throw error;
@@ -10515,7 +10637,7 @@ async function withStraceFileChanges(sandbox, options) {
10515
10637
  stdout,
10516
10638
  stderr: stripStraceDiagnostics(raw.stderr)
10517
10639
  };
10518
- if (execOptions?.signal?.aborted) return result;
10640
+ if (runOptions.abortSignal?.aborted) return result;
10519
10641
  const changes = trace ? parseStraceTrace(trace, { include, exclude, traceFile, traceDir }) : [];
10520
10642
  if (changes.length) {
10521
10643
  try {
@@ -10535,49 +10657,32 @@ async function withStraceFileChanges(sandbox, options) {
10535
10657
  }
10536
10658
  return result;
10537
10659
  },
10538
- readFile: (path6, options2) => sandbox.readFile(path6, options2),
10539
- exists: (path6) => sandbox.exists(path6),
10540
- // The writeFile tool mutates the filesystem outside strace's view, so
10541
- // observe it directly: synthesize a `write` change per file (under the
10542
- // observation root) and run it through onFileChanges. A throw propagates to
10543
- // the writeFile tool's execute (which rejects), the same gate as the bash
10544
- // path — except there's no CommandResult here, so throw a plain Error to
10545
- // reject; BashException.format() is meaningful only for bash commands.
10546
- writeFiles: async (files) => {
10547
- await innerWriteFiles(files);
10548
- const now = Date.now();
10549
- const changes = files.map((f) => posix4.normalize(f.path)).filter((path6) => matchesGlobs(path6, include, exclude)).map((path6) => ({ op: "write", path: path6, timestamp: now }));
10550
- if (changes.length) await onFileChanges?.(changes);
10660
+ spawn: spawn5,
10661
+ readFile: (readOptions) => inner.readFile(readOptions),
10662
+ readBinaryFile: (readOptions) => inner.readBinaryFile(readOptions),
10663
+ readTextFile: (readOptions) => inner.readTextFile(readOptions),
10664
+ stat: (statOptions) => inner.stat(statOptions),
10665
+ listDirectory: (listOptions) => inner.listDirectory(listOptions),
10666
+ deleteFile: async (deleteOptions) => {
10667
+ const deleted = await inner.deleteFile(deleteOptions);
10668
+ if (deleted) await observe("delete", deleteOptions.path);
10669
+ return deleted;
10551
10670
  },
10552
- dispose: async () => {
10553
- await innerExecute(`rm -rf ${shellQuote(traceDir)}`).catch(() => {
10554
- });
10555
- await sandbox.dispose();
10671
+ writeFile: async (writeOptions) => {
10672
+ await inner.writeFile(writeOptions);
10673
+ await observe("write", writeOptions.path);
10556
10674
  },
10557
- [Symbol.asyncDispose]() {
10558
- return this.dispose();
10559
- }
10675
+ writeBinaryFile: async (writeOptions) => {
10676
+ await inner.writeBinaryFile(writeOptions);
10677
+ await observe("write", writeOptions.path);
10678
+ },
10679
+ writeTextFile: async (writeOptions) => {
10680
+ await inner.writeTextFile(writeOptions);
10681
+ await observe("write", writeOptions.path);
10682
+ },
10683
+ dispose,
10684
+ [Symbol.asyncDispose]: dispose
10560
10685
  };
10561
- if (sandbox.spawn) {
10562
- const innerSpawn = sandbox.spawn.bind(sandbox);
10563
- decorated.spawn = async (command, spawnOptions) => {
10564
- const traceFile = `${traceDir}/${randomUUID4()}.strace`;
10565
- const child = await innerSpawn(
10566
- buildStraceCommand(command, traceFile, traceDir),
10567
- spawnOptions
10568
- );
10569
- const exit = (async () => {
10570
- try {
10571
- return await child.exit;
10572
- } finally {
10573
- await collectSpawn(traceFile).catch(() => {
10574
- });
10575
- }
10576
- })();
10577
- return { stdout: child.stdout, stderr: child.stderr, exit };
10578
- };
10579
- }
10580
- return decorated;
10581
10686
  }
10582
10687
 
10583
10688
  // packages/context/src/lib/sandbox/gcs.ts
@@ -10591,7 +10696,7 @@ function gcs(options) {
10591
10696
  }
10592
10697
 
10593
10698
  // packages/context/src/lib/sandbox/installers/bin.ts
10594
- import { basename, posix as posix5 } from "node:path";
10699
+ import { basename, posix as posix6 } from "node:path";
10595
10700
  var NOT_FOUND_EXIT = 11;
10596
10701
  var CHMOD_FAILED_EXIT = 12;
10597
10702
  var BinInstaller = class extends Installer {
@@ -10605,13 +10710,13 @@ var BinInstaller = class extends Installer {
10605
10710
  this.binary = binary;
10606
10711
  this.options = options;
10607
10712
  this.#name = resolveName(binary, options);
10608
- this.#target = options.target ?? posix5.join("/usr/local/bin", this.#name);
10713
+ this.#target = options.target ?? posix6.join("/usr/local/bin", this.#name);
10609
10714
  this.kind = `bin:${this.#name}`;
10610
10715
  }
10611
10716
  async install(ctx) {
10612
10717
  const b = shellQuote(this.binary);
10613
10718
  const t = shellQuote(this.#target);
10614
- const dir = shellQuote(posix5.dirname(this.#target));
10719
+ const dir = shellQuote(posix6.dirname(this.#target));
10615
10720
  const result = await ctx.exec(
10616
10721
  `test -f ${b} || { echo "binary not found at ${this.binary}" >&2; exit ${NOT_FOUND_EXIT}; }; if ! test -x ${b}; then chmod +x ${b} || exit ${CHMOD_FAILED_EXIT}; fi; mkdir -p ${dir} && ln -sf ${b} ${t}`
10617
10722
  );
@@ -10876,11 +10981,17 @@ function formatVersion(version) {
10876
10981
  }
10877
10982
 
10878
10983
  // packages/context/src/lib/sandbox/microsandbox-sandbox.ts
10984
+ import {
10985
+ extractLines as extractLines3
10986
+ } from "@ai-sdk/provider-utils";
10879
10987
  import { randomUUID as randomUUID5 } from "node:crypto";
10988
+ import { posix as posix7 } from "node:path";
10989
+ import { text as text2 } from "node:stream/consumers";
10880
10990
  var MICROSANDBOX_DEFAULT_DESTINATION = "/workspace";
10881
10991
  var MICROSANDBOX_DEFAULT_IMAGE = "bash:5.3-alpine3.24";
10882
10992
  var MICROSANDBOX_MAX_NAME_BYTES = 128;
10883
- var COMMAND_TIMEOUT_EXIT_CODE = 124;
10993
+ var COMMAND_TIMEOUT_EXIT_CODE2 = 124;
10994
+ var NOT_FOUND_MESSAGE = /\(os error (?:2|20)\)$/;
10884
10995
  var MicrosandboxSandboxError = class extends Error {
10885
10996
  constructor(message2, cause) {
10886
10997
  super(message2);
@@ -10903,12 +11014,6 @@ var MicrosandboxCreationError = class extends MicrosandboxSandboxError {
10903
11014
  this.name = "MicrosandboxCreationError";
10904
11015
  }
10905
11016
  };
10906
- var MicrosandboxCommandError = class extends MicrosandboxSandboxError {
10907
- constructor(message2, cause) {
10908
- super(message2, cause);
10909
- this.name = "MicrosandboxCommandError";
10910
- }
10911
- };
10912
11017
  async function createMicrosandboxSandbox(options = {}) {
10913
11018
  validateMicrosandboxOptions(options);
10914
11019
  const sdk = await importMicrosandbox();
@@ -10932,30 +11037,25 @@ async function createMicrosandboxSandbox(options = {}) {
10932
11037
  await vm.fs().mkdir(workdir);
10933
11038
  await assertMicrosandboxBash(vm);
10934
11039
  } catch (error) {
10935
- await vm[Symbol.asyncDispose]().catch(() => {
10936
- });
10937
- if (ephemeral) await sdk.Sandbox.remove(name).catch(() => {
10938
- });
11040
+ await vm[Symbol.asyncDispose]();
10939
11041
  throw normalizeMicrosandboxError(error, sdk);
10940
11042
  }
10941
- const backend = createMicrosandboxMethods({
11043
+ const sandbox = microsandboxSession({
10942
11044
  sdk,
10943
11045
  vm,
10944
- name,
10945
- ephemeral,
11046
+ workdir,
10946
11047
  commandTimeout: options.commandTimeout,
10947
11048
  reconnect: ephemeral ? void 0 : () => sandboxBuilder(false).connectOrCreate()
10948
11049
  });
10949
11050
  if (options.readiness) {
10950
11051
  try {
10951
- await options.readiness(backend);
11052
+ await options.readiness(sandbox);
10952
11053
  } catch (error) {
10953
- await backend.dispose().catch(() => {
10954
- });
11054
+ await sandbox.dispose();
10955
11055
  throw error;
10956
11056
  }
10957
11057
  }
10958
- return backend;
11058
+ return sandbox;
10959
11059
  }
10960
11060
  async function importMicrosandbox() {
10961
11061
  try {
@@ -11000,11 +11100,11 @@ function validateMicrosandboxOptions(options) {
11000
11100
  );
11001
11101
  }
11002
11102
  }
11003
- function createMicrosandboxMethods(args) {
11004
- const { sdk, name, ephemeral, commandTimeout, reconnect } = args;
11103
+ function microsandboxSession(args) {
11104
+ const { sdk, workdir, commandTimeout, reconnect } = args;
11005
11105
  let vm = args.vm;
11006
11106
  let reconnecting;
11007
- const run2 = async (operation) => {
11107
+ const withVm = async (operation) => {
11008
11108
  try {
11009
11109
  return await operation(vm);
11010
11110
  } catch (error) {
@@ -11018,161 +11118,227 @@ function createMicrosandboxMethods(args) {
11018
11118
  return operation(vm);
11019
11119
  }
11020
11120
  };
11021
- const spawn5 = (command, options = {}) => {
11022
- return spawnMicrosandboxProcess(sdk, run2, command, {
11023
- ...options,
11024
- commandTimeout
11121
+ const withFs = (operation) => withVm((current) => operation(current.fs()));
11122
+ const isNotFound = (error) => error instanceof sdk.SandboxFsOpsError && NOT_FOUND_MESSAGE.test(error.message);
11123
+ const orNull = async (operation) => {
11124
+ try {
11125
+ return await operation();
11126
+ } catch (error) {
11127
+ if (isNotFound(error)) return null;
11128
+ throw error;
11129
+ }
11130
+ };
11131
+ const resolve3 = (path6) => posix7.isAbsolute(path6) ? path6 : `${workdir}/${path6}`;
11132
+ const statAt = async (path6) => {
11133
+ const metadata = await orNull(() => withFs((fs) => fs.stat(path6)));
11134
+ if (!metadata) return null;
11135
+ const type = FILE_STAT_TYPES.find((known) => known === metadata.kind);
11136
+ if (!type) {
11137
+ throw new Error(
11138
+ `Failed to stat "${path6}": unknown type "${metadata.kind}"`
11139
+ );
11140
+ }
11141
+ return { type, size: metadata.size };
11142
+ };
11143
+ const readable = async (path6) => {
11144
+ const stat = await statAt(path6);
11145
+ if (stat?.type === "directory") {
11146
+ throw new Error(`Cannot read "${path6}": it is a directory.`);
11147
+ }
11148
+ return stat !== null;
11149
+ };
11150
+ const withParents = async (path6, operation) => {
11151
+ try {
11152
+ return await withFs(operation);
11153
+ } catch (error) {
11154
+ if (!isNotFound(error)) throw error;
11155
+ await withFs((fs) => fs.mkdir(posix7.dirname(path6)));
11156
+ return withFs(operation);
11157
+ }
11158
+ };
11159
+ async function spawn5(options) {
11160
+ const { command, workingDirectory, env, abortSignal, stdin } = options;
11161
+ abortSignal?.throwIfAborted();
11162
+ const handle = await withVm(
11163
+ (current) => current.execStreamWith("bash", (builder) => {
11164
+ builder.args(["-lc", command]).cwd(
11165
+ workingDirectory === void 0 ? workdir : resolve3(workingDirectory)
11166
+ );
11167
+ if (env) builder.envs(env);
11168
+ return stdin ? builder.stdinPipe() : builder.stdinNull();
11169
+ })
11170
+ );
11171
+ const sink = stdin ? await handle.takeStdin() : null;
11172
+ const stdout = createByteReadable();
11173
+ const stderr = createByteReadable();
11174
+ let exited = false;
11175
+ let timedOut = false;
11176
+ const kill = async () => {
11177
+ if (exited) return;
11178
+ await handle.kill().catch((error) => {
11179
+ if (!exited) throw error;
11180
+ });
11181
+ };
11182
+ const onAbort = () => {
11183
+ void kill().catch(() => {
11184
+ });
11185
+ };
11186
+ const timer = commandTimeout ? setTimeout(() => {
11187
+ timedOut = true;
11188
+ onAbort();
11189
+ }, commandTimeout).unref() : void 0;
11190
+ const pump = async () => {
11191
+ let code;
11192
+ for await (const event of handle) {
11193
+ if (event.kind === "stdout") stdout.enqueue(event.data);
11194
+ else if (event.kind === "stderr") stderr.enqueue(event.data);
11195
+ else if (event.kind === "exited") code = event.code;
11196
+ }
11197
+ if (timedOut) {
11198
+ stderr.enqueue(new TextEncoder().encode("Command timed out"));
11199
+ return COMMAND_TIMEOUT_EXIT_CODE2;
11200
+ }
11201
+ if (code === void 0) {
11202
+ throw new MicrosandboxSandboxError(
11203
+ `The command ended without an exit code: ${command}`
11204
+ );
11205
+ }
11206
+ return code;
11207
+ };
11208
+ const exitCode = pump().then(
11209
+ (code) => {
11210
+ stdout.close();
11211
+ stderr.close();
11212
+ return code;
11213
+ },
11214
+ async (error) => {
11215
+ const err = toError2(error);
11216
+ stdout.error(err);
11217
+ stderr.error(err);
11218
+ await handle[Symbol.asyncDispose]();
11219
+ throw err;
11220
+ }
11221
+ ).finally(() => {
11222
+ exited = true;
11223
+ clearTimeout(timer);
11224
+ abortSignal?.removeEventListener("abort", onAbort);
11025
11225
  });
11226
+ exitCode.catch(() => {
11227
+ });
11228
+ if (abortSignal?.aborted) onAbort();
11229
+ else abortSignal?.addEventListener("abort", onAbort, { once: true });
11230
+ return {
11231
+ stdout: stdout.stream,
11232
+ stderr: stderr.stream,
11233
+ ...sink ? {
11234
+ stdin: new WritableStream({
11235
+ write: (chunk) => sink.write(chunk),
11236
+ close: () => sink.close(),
11237
+ abort: () => sink.close()
11238
+ })
11239
+ } : {},
11240
+ wait: async () => ({
11241
+ exitCode: await exitCode.finally(() => abortSignal?.throwIfAborted())
11242
+ }),
11243
+ kill
11244
+ };
11245
+ }
11246
+ const readBinaryFile = async ({
11247
+ path: path6,
11248
+ abortSignal
11249
+ }) => {
11250
+ abortSignal?.throwIfAborted();
11251
+ const target = resolve3(path6);
11252
+ if (!await readable(target)) return null;
11253
+ return orNull(() => withFs((fs) => fs.read(target)));
11254
+ };
11255
+ const writeBinaryFile = async ({
11256
+ path: path6,
11257
+ content,
11258
+ abortSignal
11259
+ }) => {
11260
+ abortSignal?.throwIfAborted();
11261
+ const target = resolve3(path6);
11262
+ await withParents(target, (fs) => fs.write(target, content));
11263
+ };
11264
+ const dispose = async () => {
11265
+ await vm[Symbol.asyncDispose]();
11026
11266
  };
11027
11267
  return {
11028
- // `executeCommand` lowers onto the same streaming pump as `spawn` so a
11029
- // single code path supports real cancellation. Cooperative abort (abandon
11030
- // the promise, Daytona-style) is not an option here: the SDK is an
11031
- // in-process native binding, so an abandoned exec keeps the guest process
11032
- // and its libuv handle alive.
11033
- async executeCommand(command, options) {
11034
- const proc = spawn5(command, { signal: options?.signal });
11035
- const [stdout, stderr, info] = await Promise.all([
11036
- readAllText(proc.stdout),
11037
- readAllText(proc.stderr),
11038
- proc.exit
11268
+ description: `Commands run through bash -lc in a Microsandbox microVM, starting in ${workdir}.`,
11269
+ run: async (options) => {
11270
+ const process2 = await spawn5(options);
11271
+ const [stdout, stderr, { exitCode }] = await Promise.all([
11272
+ text2(process2.stdout),
11273
+ text2(process2.stderr),
11274
+ process2.wait()
11039
11275
  ]);
11040
- if (info.signal === "SIGKILL") {
11041
- return abortedCommandResult2();
11042
- }
11043
- return { stdout, stderr, exitCode: info.code ?? 1 };
11276
+ return { stdout, stderr, exitCode };
11044
11277
  },
11045
- spawn: async (command, options) => spawn5(command, options),
11046
- async readFile(path6, options) {
11047
- try {
11048
- const bytes = await run2((vm2) => vm2.fs().read(path6));
11049
- return readFileContent(bytes, options);
11050
- } catch (error) {
11051
- throw new MicrosandboxCommandError(
11052
- `Failed to read file "${path6}": ${toError2(error).message}`,
11053
- toError2(error)
11054
- );
11055
- }
11278
+ spawn: spawn5,
11279
+ readBinaryFile,
11280
+ readFile: async ({ path: path6, abortSignal }) => {
11281
+ abortSignal?.throwIfAborted();
11282
+ const target = resolve3(path6);
11283
+ if (!await readable(target)) return null;
11284
+ const stream = await orNull(() => withFs((fs) => fs.readStream(target)));
11285
+ return stream && ReadableStream.from(stream);
11056
11286
  },
11057
- async exists(path6) {
11287
+ readTextFile: async ({ startLine, endLine, encoding, ...options }) => {
11288
+ const bytes = await readBinaryFile(options);
11289
+ if (!bytes) return null;
11290
+ return extractLines3({
11291
+ text: Buffer.from(bytes).toString(bufferEncoding(encoding)),
11292
+ startLine,
11293
+ endLine
11294
+ });
11295
+ },
11296
+ writeBinaryFile,
11297
+ writeFile: async ({ path: path6, content, abortSignal }) => {
11298
+ abortSignal?.throwIfAborted();
11299
+ const target = resolve3(path6);
11300
+ await using sink = await withParents(
11301
+ target,
11302
+ (fs) => fs.writeStream(target)
11303
+ );
11304
+ for await (const chunk of content) await sink.write(chunk);
11305
+ await sink.close();
11306
+ },
11307
+ writeTextFile: ({ content, encoding, ...options }) => writeBinaryFile({
11308
+ ...options,
11309
+ content: Buffer.from(content, bufferEncoding(encoding))
11310
+ }),
11311
+ stat: async ({ path: path6, abortSignal }) => {
11312
+ abortSignal?.throwIfAborted();
11313
+ return statAt(resolve3(path6));
11314
+ },
11315
+ listDirectory: async ({ path: path6, abortSignal }) => {
11316
+ abortSignal?.throwIfAborted();
11317
+ const target = resolve3(path6);
11058
11318
  try {
11059
- return await run2((vm2) => vm2.fs().exists(path6));
11319
+ const entries = await withFs((fs) => fs.list(target));
11320
+ return entries.map((entry) => ({
11321
+ name: posix7.basename(entry.path),
11322
+ type: entry.kind
11323
+ }));
11060
11324
  } catch (error) {
11061
- throw new MicrosandboxCommandError(
11062
- `Failed to check "${path6}": ${toError2(error).message}`,
11063
- toError2(error)
11064
- );
11325
+ if (!isNotFound(error) || await statAt(target)) throw error;
11326
+ return null;
11065
11327
  }
11066
11328
  },
11067
- async writeFiles(files) {
11329
+ deleteFile: async ({ path: path6, abortSignal }) => {
11330
+ abortSignal?.throwIfAborted();
11068
11331
  try {
11069
- await run2(async (vm2) => {
11070
- const fs = vm2.fs();
11071
- for (const dir of uniqueParentDirectories2(files.map((f) => f.path))) {
11072
- await fs.mkdir(dir);
11073
- }
11074
- for (const file of files) {
11075
- await fs.write(file.path, file.content);
11076
- }
11077
- });
11332
+ await withFs((fs) => fs.remove(resolve3(path6)));
11333
+ return true;
11078
11334
  } catch (error) {
11079
- const err = toError2(error);
11080
- throw new MicrosandboxCommandError(
11081
- `Failed to write files: ${err.message}`,
11082
- err
11083
- );
11084
- }
11085
- },
11086
- async dispose() {
11087
- await vm[Symbol.asyncDispose]();
11088
- if (ephemeral) {
11089
- await sdk.Sandbox.remove(name).catch(() => {
11090
- });
11335
+ if (isNotFound(error)) return false;
11336
+ throw error;
11091
11337
  }
11092
11338
  },
11093
- [Symbol.asyncDispose]() {
11094
- return this.dispose();
11095
- }
11096
- };
11097
- }
11098
- function spawnMicrosandboxProcess(sdk, run2, command, options) {
11099
- const stdout = createByteReadable();
11100
- const stderr = createByteReadable();
11101
- const exit = pumpExecStream({ sdk, run: run2, command, options, stdout, stderr });
11102
- return { stdout: stdout.stream, stderr: stderr.stream, exit };
11103
- }
11104
- async function pumpExecStream(args) {
11105
- const { sdk, run: run2, command, options, stdout, stderr } = args;
11106
- const { signal } = options;
11107
- let handle;
11108
- let aborted = signal?.aborted ?? false;
11109
- let timedOut = false;
11110
- let timeoutTimer;
11111
- const abort = () => {
11112
- aborted = true;
11113
- handle?.kill().catch(() => {
11114
- });
11339
+ dispose,
11340
+ [Symbol.asyncDispose]: dispose
11115
11341
  };
11116
- if (aborted) {
11117
- stdout.close();
11118
- stderr.close();
11119
- return abortedExitInfo2();
11120
- }
11121
- signal?.addEventListener("abort", abort, { once: true });
11122
- try {
11123
- handle = await run2(
11124
- (vm) => vm.execStreamWith("bash", (builder) => {
11125
- builder.args(["-lc", command]).stdinNull();
11126
- if (options.cwd) builder.cwd(options.cwd);
11127
- if (options.env) builder.envs(options.env);
11128
- return builder;
11129
- })
11130
- );
11131
- if (aborted) {
11132
- return abortedExitInfo2();
11133
- }
11134
- if (options.commandTimeout) {
11135
- const startedHandle = handle;
11136
- timeoutTimer = setTimeout(() => {
11137
- timedOut = true;
11138
- startedHandle.kill().catch(() => {
11139
- });
11140
- }, options.commandTimeout);
11141
- timeoutTimer.unref();
11142
- }
11143
- let code = null;
11144
- for await (const event of handle) {
11145
- if (event.kind === "stdout") stdout.enqueue(event.data);
11146
- else if (event.kind === "stderr") stderr.enqueue(event.data);
11147
- else if (event.kind === "exited") code = event.code;
11148
- }
11149
- if (aborted) {
11150
- return abortedExitInfo2();
11151
- }
11152
- if (timedOut) {
11153
- stderr.enqueue(new TextEncoder().encode("Command timed out"));
11154
- return { code: COMMAND_TIMEOUT_EXIT_CODE, signal: null, success: false };
11155
- }
11156
- return { code, signal: null, success: code === 0 };
11157
- } catch (error) {
11158
- if (aborted) {
11159
- return abortedExitInfo2();
11160
- }
11161
- if (timedOut || error instanceof sdk.ExecTimeoutError) {
11162
- stderr.enqueue(new TextEncoder().encode("Command timed out"));
11163
- return { code: COMMAND_TIMEOUT_EXIT_CODE, signal: null, success: false };
11164
- }
11165
- const err = toError2(error);
11166
- stdout.error(err);
11167
- stderr.error(err);
11168
- throw err;
11169
- } finally {
11170
- clearTimeout(timeoutTimer);
11171
- signal?.removeEventListener("abort", abort);
11172
- stdout.close();
11173
- stderr.close();
11174
- await handle?.[Symbol.asyncDispose]();
11175
- }
11176
11342
  }
11177
11343
  function createByteReadable() {
11178
11344
  const ended = {
@@ -11211,40 +11377,8 @@ function createByteReadable() {
11211
11377
  error: (error) => sink.error(error)
11212
11378
  };
11213
11379
  }
11214
- async function readAllText(stream) {
11215
- const decoder2 = new TextDecoder();
11216
- let text = "";
11217
- for await (const chunk of stream) {
11218
- text += decoder2.decode(chunk, { stream: true });
11219
- }
11220
- return text + decoder2.decode();
11221
- }
11222
- function abortedCommandResult2() {
11223
- return {
11224
- stdout: "",
11225
- stderr: "Command aborted",
11226
- exitCode: 1
11227
- };
11228
- }
11229
- function abortedExitInfo2() {
11230
- return {
11231
- code: null,
11232
- signal: "SIGKILL",
11233
- success: false
11234
- };
11235
- }
11236
- function uniqueParentDirectories2(paths) {
11237
- const dirs = /* @__PURE__ */ new Set();
11238
- for (const path6 of paths) {
11239
- const index = path6.lastIndexOf("/");
11240
- if (index > 0) {
11241
- dirs.add(path6.slice(0, index));
11242
- }
11243
- }
11244
- return [...dirs];
11245
- }
11246
11380
  function toError2(error) {
11247
- return error instanceof Error ? error : new Error(String(error));
11381
+ return Error.isError(error) ? error : new Error(String(error));
11248
11382
  }
11249
11383
 
11250
11384
  // packages/context/src/lib/sandbox/subcommand.ts
@@ -11317,54 +11451,27 @@ function buildSubcommandRepair(name, subcommands) {
11317
11451
  }
11318
11452
 
11319
11453
  // packages/context/src/lib/sandbox/virtual-sandbox.ts
11454
+ import { createJustBashSandboxSessionFromNativeSandbox } from "@ai-sdk/sandbox-just-bash";
11320
11455
  import {
11321
- Bash
11456
+ Sandbox
11322
11457
  } from "just-bash";
11323
- async function createVirtualSandbox(options) {
11324
- const { fs } = options;
11325
- const bash = new Bash({
11326
- fs,
11327
- cwd: options.cwd,
11328
- env: options.env,
11329
- javascript: options.javascript,
11330
- customCommands: options.customCommands
11331
- });
11332
- const resolve3 = (path6) => fs.resolvePath(bash.getCwd(), path6);
11333
- const sandbox = {
11334
- async executeCommand(command, options2) {
11335
- const result = await bash.exec(
11336
- command,
11337
- options2?.signal ? { signal: options2.signal } : void 0
11338
- );
11339
- return {
11340
- stdout: result.stdout,
11341
- stderr: result.stderr,
11342
- exitCode: result.exitCode
11343
- };
11344
- },
11345
- async readFile(path6, readOptions) {
11346
- return readFileContent(
11347
- await fs.readFileBuffer(resolve3(path6)),
11348
- readOptions
11349
- );
11350
- },
11351
- async writeFiles(files) {
11352
- for (const file of files) {
11353
- await fs.writeFile(resolve3(file.path), file.content);
11354
- }
11355
- },
11356
- async exists(path6) {
11357
- return fs.exists(resolve3(path6));
11358
- },
11359
- async dispose() {
11360
- },
11361
- [Symbol.asyncDispose]() {
11362
- return this.dispose();
11363
- }
11364
- };
11365
- if (options.readiness) {
11458
+ async function createVirtualSandbox({
11459
+ readiness,
11460
+ ...options
11461
+ }) {
11462
+ const native = await Sandbox.create(options);
11463
+ const dispose = () => native.stop();
11464
+ const sandbox = Object.assign(
11465
+ // The adapter pins just-bash ^2 and we run ^3 for customCommands on Sandbox.
11466
+ // Its parameter is the other copy's class, whose private members make the two
11467
+ // nominally different, so no narrowing can reach it. Goes with #4043.
11468
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- two copies of one class
11469
+ createJustBashSandboxSessionFromNativeSandbox(native),
11470
+ { dispose, [Symbol.asyncDispose]: dispose }
11471
+ );
11472
+ if (readiness) {
11366
11473
  try {
11367
- await options.readiness(sandbox);
11474
+ await readiness(sandbox);
11368
11475
  } catch (error) {
11369
11476
  await sandbox.dispose().catch(() => {
11370
11477
  });
@@ -11910,7 +12017,7 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
11910
12017
  limitClause = ` LIMIT $${paramIndex++}`;
11911
12018
  params.push(options.limit);
11912
12019
  if (options.offset !== void 0) {
11913
- limitClause += ` OFFSET $${paramIndex++}`;
12020
+ limitClause += ` OFFSET $${paramIndex}`;
11914
12021
  params.push(options.offset);
11915
12022
  }
11916
12023
  }
@@ -12389,7 +12496,7 @@ END;
12389
12496
  }
12390
12497
 
12391
12498
  // packages/context/src/lib/store/sqlserver-schema-lock.ts
12392
- async function withSqlServerSchemaLock(mssql, pool, schema, run2) {
12499
+ async function withSqlServerSchemaLock(mssql, pool, schema, run) {
12393
12500
  const holder = new mssql.Transaction(pool);
12394
12501
  await holder.begin();
12395
12502
  let result;
@@ -12410,7 +12517,7 @@ async function withSqlServerSchemaLock(mssql, pool, schema, run2) {
12410
12517
  `Could not lock the DDL of schema "${schema}": sp_getapplock returned ${recordset[0].status}.`
12411
12518
  );
12412
12519
  }
12413
- result = await run2();
12520
+ result = await run();
12414
12521
  } catch (error) {
12415
12522
  await holder.rollback().catch(() => {
12416
12523
  });
@@ -12741,7 +12848,7 @@ var SqlServerContextStore = class _SqlServerContextStore extends ContextStore {
12741
12848
  write.input(name, mssql.NVarChar, updates.title);
12742
12849
  }
12743
12850
  if (updates.metadata !== void 0) {
12744
- const name = `p${paramIndex++}`;
12851
+ const name = `p${paramIndex}`;
12745
12852
  setClauses.push(`metadata = @${name}`);
12746
12853
  write.input(name, mssql.NVarChar, JSON.stringify(updates.metadata));
12747
12854
  }
@@ -13456,11 +13563,11 @@ function asStaticWordText(word, options = {}) {
13456
13563
  function asStaticWordPartText(parts, options = {}) {
13457
13564
  const texts = [];
13458
13565
  for (const part of parts) {
13459
- const text = staticPartText(part, options);
13460
- if (text == null) {
13566
+ const text3 = staticPartText(part, options);
13567
+ if (text3 == null) {
13461
13568
  return null;
13462
13569
  }
13463
- texts.push(text);
13570
+ texts.push(text3);
13464
13571
  }
13465
13572
  return texts.join("");
13466
13573
  }
@@ -13671,7 +13778,7 @@ var PostgresNotifyChangeSource = class _PostgresNotifyChangeSource {
13671
13778
  if (delivery instanceof ChangeDelivery) yield delivery.change;
13672
13779
  }
13673
13780
  } catch (error) {
13674
- if (error instanceof Error && error.name === "AbortError") return;
13781
+ if (Error.isError(error) && error.name === "AbortError") return;
13675
13782
  throw error;
13676
13783
  } finally {
13677
13784
  this.#subscriptions -= 1;
@@ -14534,7 +14641,7 @@ var StreamManager = class {
14534
14641
  throw err;
14535
14642
  }
14536
14643
  } else {
14537
- const message2 = err instanceof Error ? err.message : String(err);
14644
+ const message2 = Error.isError(err) ? err.message : String(err);
14538
14645
  if (pw) {
14539
14646
  await pw.fail(message2);
14540
14647
  } else {
@@ -14770,7 +14877,7 @@ async function drainAvailable(controller, store, streamId, lastSeqRef, pageSize,
14770
14877
  return total;
14771
14878
  }
14772
14879
  function isAbortError(error) {
14773
- return error instanceof Error && (error.name === "AbortError" || /aborted/i.test(error.message));
14880
+ return Error.isError(error) && (error.name === "AbortError" || /aborted/i.test(error.message));
14774
14881
  }
14775
14882
  async function drain(stream, signal) {
14776
14883
  await stream.pipeTo(new WritableStream(), { signal });
@@ -14855,7 +14962,6 @@ export {
14855
14962
  ContextStore,
14856
14963
  DAYTONA_DEFAULT_DESTINATION,
14857
14964
  DEFAULT_CANCEL_POLLING,
14858
- DEFAULT_MAX_OUTPUT_LENGTH,
14859
14965
  DEFAULT_STOP_WHEN,
14860
14966
  DEFAULT_WATCH_POLLING,
14861
14967
  DaytonaCommandError,
@@ -14877,7 +14983,6 @@ export {
14877
14983
  LOCALE_METADATA_KEY,
14878
14984
  MICROSANDBOX_DEFAULT_DESTINATION,
14879
14985
  MarkdownRenderer,
14880
- MicrosandboxCommandError,
14881
14986
  MicrosandboxCreationError,
14882
14987
  MicrosandboxNotAvailableError,
14883
14988
  MicrosandboxSandboxError,