@deepagents/context 7.5.2 → 7.7.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 (60) hide show
  1. package/README.md +12 -10
  2. package/dist/index.js +1409 -1807
  3. package/dist/index.js.map +4 -4
  4. package/dist/lib/agent.d.ts +21 -21
  5. package/dist/lib/agent.d.ts.map +1 -1
  6. package/dist/lib/fragments/plan-shared.d.ts.map +1 -1
  7. package/dist/lib/sandbox/apple-container-sandbox.d.ts +2 -2
  8. package/dist/lib/sandbox/apple-container-sandbox.d.ts.map +1 -1
  9. package/dist/lib/sandbox/bash-tool.d.ts +2 -4
  10. package/dist/lib/sandbox/bash-tool.d.ts.map +1 -1
  11. package/dist/lib/sandbox/container-engine.d.ts +53 -27
  12. package/dist/lib/sandbox/container-engine.d.ts.map +1 -1
  13. package/dist/lib/sandbox/container-sandbox.d.ts +6 -3
  14. package/dist/lib/sandbox/container-sandbox.d.ts.map +1 -1
  15. package/dist/lib/sandbox/container-session.d.ts +19 -0
  16. package/dist/lib/sandbox/container-session.d.ts.map +1 -0
  17. package/dist/lib/sandbox/daytona-sandbox.d.ts +39 -48
  18. package/dist/lib/sandbox/daytona-sandbox.d.ts.map +1 -1
  19. package/dist/lib/sandbox/docker-sandbox.d.ts +31 -131
  20. package/dist/lib/sandbox/docker-sandbox.d.ts.map +1 -1
  21. package/dist/lib/sandbox/index.d.ts +0 -1
  22. package/dist/lib/sandbox/index.d.ts.map +1 -1
  23. package/dist/lib/sandbox/microsandbox-sandbox.d.ts +6 -13
  24. package/dist/lib/sandbox/microsandbox-sandbox.d.ts.map +1 -1
  25. package/dist/lib/sandbox/read-file-tool/index.d.ts +2 -2
  26. package/dist/lib/sandbox/read-file-tool/index.d.ts.map +1 -1
  27. package/dist/lib/sandbox/read-file-tool/text.d.ts.map +1 -1
  28. package/dist/lib/sandbox/session.d.ts +40 -0
  29. package/dist/lib/sandbox/session.d.ts.map +1 -0
  30. package/dist/lib/sandbox/strace/file-changes.d.ts +20 -14
  31. package/dist/lib/sandbox/strace/file-changes.d.ts.map +1 -1
  32. package/dist/lib/sandbox/strace/index.d.ts +1 -1
  33. package/dist/lib/sandbox/strace/index.d.ts.map +1 -1
  34. package/dist/lib/sandbox/strace/index.js +7 -6
  35. package/dist/lib/sandbox/strace/index.js.map +2 -2
  36. package/dist/lib/sandbox/types.d.ts +38 -78
  37. package/dist/lib/sandbox/types.d.ts.map +1 -1
  38. package/dist/lib/sandbox/virtual-sandbox.d.ts +3 -3
  39. package/dist/lib/sandbox/virtual-sandbox.d.ts.map +1 -1
  40. package/dist/lib/telemetry/console-telemetry.d.ts +7 -1
  41. package/dist/lib/telemetry/console-telemetry.d.ts.map +1 -1
  42. package/dist/lib/telemetry/file/file-telemetry.d.ts +6 -0
  43. package/dist/lib/telemetry/file/file-telemetry.d.ts.map +1 -1
  44. package/dist/lib/telemetry/file/index.js +18 -12
  45. package/dist/lib/telemetry/file/index.js.map +2 -2
  46. package/dist/lib/telemetry/index.js +10 -6
  47. package/dist/lib/telemetry/index.js.map +2 -2
  48. package/dist/lib/telemetry/safe-serialize.d.ts +1 -1
  49. package/dist/lib/telemetry/safe-serialize.d.ts.map +1 -1
  50. package/dist/lib/tracing/batch-processor.d.ts +7 -1
  51. package/dist/lib/tracing/batch-processor.d.ts.map +1 -1
  52. package/dist/lib/tracing/index.js +24 -16
  53. package/dist/lib/tracing/index.js.map +2 -2
  54. package/dist/lib/tracing/openai-traces-integration.d.ts +9 -3
  55. package/dist/lib/tracing/openai-traces-integration.d.ts.map +1 -1
  56. package/package.json +23 -19
  57. package/dist/lib/sandbox/cli-process.d.ts +0 -35
  58. package/dist/lib/sandbox/cli-process.d.ts.map +0 -1
  59. package/dist/lib/sandbox/read-file.d.ts +0 -9
  60. package/dist/lib/sandbox/read-file.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 { 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,429 @@ 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";
7264
7275
 
7265
- // packages/context/src/lib/sandbox/shell-quote.ts
7266
- function shellQuote(s) {
7267
- return `'${s.replace(/'/g, `'\\''`)}'`;
7268
- }
7276
+ // packages/context/src/lib/sandbox/container-session.ts
7277
+ import "@ai-sdk/provider-utils";
7278
+ import { randomUUID } from "node:crypto";
7279
+ import { text as text2 } from "node:stream/consumers";
7280
+ import { setTimeout as delay } from "node:timers/promises";
7269
7281
 
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
- };
7278
- }
7282
+ // packages/context/src/lib/sandbox/session.ts
7283
+ import {
7284
+ extractLines
7285
+ } from "@ai-sdk/provider-utils";
7286
+ import { posix } from "node:path";
7287
+ import { text } from "node:stream/consumers";
7288
+ function bufferEncoding(encoding = "utf-8") {
7289
+ if (!Buffer.isEncoding(encoding)) {
7290
+ throw new TypeError(`Unknown encoding: ${encoding}`);
7291
+ }
7292
+ return encoding;
7293
+ }
7294
+ function resolveIn(directory, path6) {
7295
+ return posix.isAbsolute(path6) ? path6 : `${directory}/${path6}`;
7296
+ }
7297
+ function textCalls({
7298
+ readBinaryFile,
7299
+ writeBinaryFile
7300
+ }) {
7279
7301
  return {
7280
- stdout: "",
7281
- stderr: error instanceof Error ? error.message : "",
7282
- exitCode: 1
7302
+ readTextFile: async ({ startLine, endLine, encoding, ...options }) => {
7303
+ const bytes = await readBinaryFile(options);
7304
+ if (!bytes) return null;
7305
+ return extractLines({
7306
+ text: Buffer.from(bytes).toString(bufferEncoding(encoding)),
7307
+ startLine,
7308
+ endLine
7309
+ });
7310
+ },
7311
+ writeTextFile: ({ content, encoding, ...options }) => writeBinaryFile({
7312
+ ...options,
7313
+ content: Buffer.from(content, bufferEncoding(encoding))
7314
+ })
7283
7315
  };
7284
7316
  }
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");
7289
- }
7290
- const onAbort = () => child.kill("SIGKILL");
7291
- if (abortSignal) {
7292
- if (abortSignal.aborted) onAbort();
7293
- else abortSignal.addEventListener("abort", onAbort, { once: true });
7294
- }
7317
+ function controlProcess({
7318
+ exitCode,
7319
+ kill: stop2,
7320
+ abortSignal
7321
+ }) {
7322
+ let killing;
7323
+ const kill = () => killing ??= stop2();
7324
+ const onAbort = () => {
7325
+ void kill().catch(() => {
7326
+ });
7327
+ };
7328
+ if (abortSignal?.aborted) onAbort();
7329
+ else abortSignal?.addEventListener("abort", onAbort, { once: true });
7330
+ void exitCode.catch(() => {
7331
+ }).finally(() => abortSignal?.removeEventListener("abort", onAbort));
7295
7332
  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 });
7333
+ wait: async () => ({
7334
+ exitCode: await exitCode.finally(() => abortSignal?.throwIfAborted())
7335
+ }),
7336
+ kill
7337
+ };
7338
+ }
7339
+ async function collect(process2) {
7340
+ const [stdout, stderr, { exitCode }] = await Promise.all([
7341
+ text(process2.stdout),
7342
+ text(process2.stderr),
7343
+ process2.wait()
7344
+ ]);
7345
+ return { stdout, stderr, exitCode };
7346
+ }
7347
+ function createByteReadable() {
7348
+ const ended = {
7349
+ enqueue() {
7350
+ },
7351
+ close() {
7352
+ },
7353
+ error() {
7354
+ }
7355
+ };
7356
+ let sink = ended;
7357
+ const stream = new ReadableStream({
7358
+ start(controller) {
7359
+ sink = {
7360
+ enqueue(chunk) {
7361
+ if (chunk.length > 0) controller.enqueue(chunk);
7362
+ },
7363
+ close() {
7364
+ sink = ended;
7365
+ controller.close();
7366
+ },
7367
+ error(reason) {
7368
+ sink = ended;
7369
+ controller.error(reason);
7370
+ }
7311
7371
  };
7312
- child.on("exit", onExitEvent);
7313
- child.on("error", onError);
7314
- })
7372
+ },
7373
+ cancel() {
7374
+ sink = ended;
7375
+ }
7376
+ });
7377
+ return {
7378
+ stream,
7379
+ enqueue: (chunk) => sink.enqueue(chunk),
7380
+ close: () => sink.close(),
7381
+ error: (reason) => sink.error(reason)
7315
7382
  };
7316
7383
  }
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
- );
7384
+
7385
+ // packages/context/src/lib/sandbox/shell-quote.ts
7386
+ function shellQuote(s) {
7387
+ return `'${s.replace(/'/g, `'\\''`)}'`;
7388
+ }
7389
+
7390
+ // packages/context/src/lib/sandbox/container-session.ts
7391
+ var NOT_FOUND_EXIT_CODE = 3;
7392
+ var WRONG_TYPE_EXIT_CODE = 4;
7393
+ var FILE_STAT_TYPES = [
7394
+ "file",
7395
+ "directory",
7396
+ "other"
7397
+ ];
7398
+ var DIRECTORY_ENTRY_TYPES = [
7399
+ "file",
7400
+ "directory",
7401
+ "symlink",
7402
+ "other"
7403
+ ];
7404
+ var EXIT_MISSING_FUNCTION = `
7405
+ exit_missing() {
7406
+ error=$(LC_ALL=C; : 2>&1 < "$1")
7407
+ case $error in
7408
+ *": No such file or directory" | *": Not a directory") exit ${NOT_FOUND_EXIT_CODE} ;;
7409
+ esac
7410
+ echo "\${error:-Cannot access $1}" >&2
7411
+ exit 1
7412
+ }
7413
+ `;
7414
+ var STAT_SCRIPT = `${EXIT_MISSING_FUNCTION}
7415
+ [ -e "$1" ] || exit_missing "$1"
7416
+ if [ -f "$1" ]; then type=file; elif [ -d "$1" ]; then type=directory; else type=other; fi
7417
+ size=$(stat -L -c %s -- "$1") || exit 1
7418
+ printf '%s %s' "$type" "$size"
7419
+ `;
7420
+ var READ_FILE_SCRIPT = `${EXIT_MISSING_FUNCTION}
7421
+ [ -e "$1" ] || exit_missing "$1"
7422
+ base64 < "$1"
7423
+ `;
7424
+ var LIST_DIRECTORY_SCRIPT = `${EXIT_MISSING_FUNCTION}
7425
+ if [ ! -d "$1" ]; then
7426
+ [ -e "$1" ] || exit_missing "$1"
7427
+ echo "Not a directory" >&2
7428
+ exit ${WRONG_TYPE_EXIT_CODE}
7429
+ fi
7430
+ case $1 in /*) dir=$1 ;; *) dir=./$1 ;; esac
7431
+ cd -P -- "$dir" || exit 1
7432
+ [ -r . ] || { echo "Permission denied" >&2; exit 1; }
7433
+ shopt -s dotglob nullglob
7434
+ for name in *; do
7435
+ if [ -L "$name" ]; then type=symlink
7436
+ elif [ -f "$name" ]; then type=file
7437
+ elif [ -d "$name" ]; then type=directory
7438
+ else type=other
7439
+ fi
7440
+ printf '%s %s\\0' "$type" "$name"
7441
+ done
7442
+ `;
7443
+ var DELETE_FILE_SCRIPT = `${EXIT_MISSING_FUNCTION}
7444
+ if [ -d "$1" ] && [ ! -L "$1" ]; then
7445
+ echo "Is a directory" >&2
7446
+ exit ${WRONG_TYPE_EXIT_CODE}
7447
+ fi
7448
+ [ -e "$1" ] || [ -L "$1" ] || exit_missing "$1"
7449
+ rm -f -- "$1"
7450
+ `;
7451
+ async function runPathScript(container, script, path6, signal) {
7452
+ signal?.throwIfAborted();
7453
+ const result = await container.exec(["bash", "-c", script, "bash", path6], {
7454
+ signal
7455
+ });
7456
+ signal?.throwIfAborted();
7457
+ return result;
7458
+ }
7459
+ async function statOverExec(container, path6, signal) {
7460
+ const { exitCode, stdout, stderr } = await runPathScript(
7461
+ container,
7462
+ STAT_SCRIPT,
7463
+ path6,
7464
+ signal
7465
+ );
7466
+ if (exitCode === NOT_FOUND_EXIT_CODE) return null;
7467
+ if (exitCode !== 0) {
7468
+ throw new Error(`Failed to stat "${path6}": ${stderr.trim()}`);
7469
+ }
7470
+ const [printed, size] = stdout.split(" ");
7471
+ const type = FILE_STAT_TYPES.find((known) => known === printed);
7472
+ if (!type) {
7473
+ throw new Error(`Failed to stat "${path6}": unknown type "${printed}"`);
7474
+ }
7475
+ return { type, size: Number(size) };
7476
+ }
7477
+ async function readFileOverExec(container, path6, signal) {
7478
+ const { exitCode, stdout, stderr } = await runPathScript(
7479
+ container,
7480
+ READ_FILE_SCRIPT,
7481
+ path6,
7482
+ signal
7483
+ );
7484
+ if (exitCode === NOT_FOUND_EXIT_CODE) return null;
7485
+ if (exitCode !== 0) {
7486
+ throw new Error(`Failed to read file "${path6}": ${stderr.trim()}`);
7328
7487
  }
7329
- if (commands.length === 0) {
7330
- commands.push(`printf '' > ${quotedPath}`);
7488
+ return Buffer.from(stdout, "base64");
7489
+ }
7490
+ async function writeFileOverExec(container, path6, content, signal) {
7491
+ const { exitCode, stderr } = await container.exec(
7492
+ [
7493
+ "bash",
7494
+ "-c",
7495
+ 'mkdir -p -- "$(dirname -- "$1")" && cat > "$1"',
7496
+ "bash",
7497
+ path6
7498
+ ],
7499
+ { signal, stdin: content }
7500
+ );
7501
+ signal?.throwIfAborted();
7502
+ if (exitCode !== 0) {
7503
+ throw new Error(`Failed to write file "${path6}": ${stderr.trim()}`);
7331
7504
  }
7332
- return commands;
7333
7505
  }
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}`);
7506
+ async function listDirectoryOverExec(container, path6, signal) {
7507
+ const { exitCode, stdout, stderr } = await runPathScript(
7508
+ container,
7509
+ LIST_DIRECTORY_SCRIPT,
7510
+ path6,
7511
+ signal
7512
+ );
7513
+ if (exitCode === NOT_FOUND_EXIT_CODE) return null;
7514
+ if (exitCode !== 0) {
7515
+ throw new Error(`Failed to list "${path6}": ${stderr.trim()}`);
7516
+ }
7517
+ return stdout.split("\0").filter((record) => record !== "").map((record) => {
7518
+ const separator = record.indexOf(" ");
7519
+ const printed = record.slice(0, separator);
7520
+ const type = DIRECTORY_ENTRY_TYPES.find((known) => known === printed);
7521
+ if (!type) {
7522
+ throw new Error(`Failed to list "${path6}": unknown type "${printed}"`);
7523
+ }
7524
+ return { name: record.slice(separator + 1), type };
7525
+ });
7526
+ }
7527
+ async function deleteFileOverExec(container, path6, signal) {
7528
+ const { exitCode, stderr } = await runPathScript(
7529
+ container,
7530
+ DELETE_FILE_SCRIPT,
7531
+ path6,
7532
+ signal
7533
+ );
7534
+ if (exitCode === NOT_FOUND_EXIT_CODE) return false;
7535
+ if (exitCode === WRONG_TYPE_EXIT_CODE) {
7536
+ throw new Error(`Cannot delete "${path6}": it is a directory.`);
7338
7537
  }
7339
- return Buffer.from(result.stdout, "base64");
7538
+ if (exitCode !== 0) {
7539
+ throw new Error(`Failed to delete "${path6}": ${stderr.trim()}`);
7540
+ }
7541
+ return true;
7340
7542
  }
7341
- async function existsOverExec(executeCommand, path6) {
7342
- const result = await executeCommand(
7343
- `test -e ${shellQuote(path6)} && printf true || printf false`
7543
+ async function collectOutput(process2) {
7544
+ const [stdout, stderr, exitCode] = await Promise.all([
7545
+ text2(process2.stdout),
7546
+ text2(process2.stderr),
7547
+ process2.exitCode
7548
+ ]);
7549
+ return { stdout, stderr, exitCode };
7550
+ }
7551
+ function managedCommand(command, controlPath, commandTimeout) {
7552
+ return [
7553
+ "set -m",
7554
+ `control=${shellQuote(controlPath)}`,
7555
+ ': > "$control" || exit 1',
7556
+ "timer=",
7557
+ `trap 'if [ -n "$timer" ]; then kill -TERM "$timer" 2>/dev/null || :; wait "$timer" 2>/dev/null || :; fi; rm -f "$control" "$control.timeout"' EXIT`,
7558
+ `bash -lc ${shellQuote(command)} &`,
7559
+ "pid=$!",
7560
+ `printf '%s\\n' "$pid" > "$control"`,
7561
+ ...commandTimeout ? [
7562
+ // Keep the deadline on the engine host: SSH setup/round trips must not
7563
+ // let the command run past its execution budget.
7564
+ "(",
7565
+ `sleep ${commandTimeout / 1e3} &`,
7566
+ "alarm=$!",
7567
+ `trap 'kill "$alarm" 2>/dev/null || :; wait "$alarm" 2>/dev/null || :; exit 0' TERM`,
7568
+ 'wait "$alarm" || exit',
7569
+ 'if kill -0 -- "-$pid" 2>/dev/null; then : > "$control.timeout"; kill -KILL -- "-$pid" 2>/dev/null || :; fi',
7570
+ ") &",
7571
+ "timer=$!"
7572
+ ] : [],
7573
+ 'wait "$pid"',
7574
+ "status=$?",
7575
+ '[ ! -e "$control.timeout" ] || exit 124',
7576
+ 'exit "$status"'
7577
+ ].join("\n");
7578
+ }
7579
+ async function terminate(container, controlPath, exitCode) {
7580
+ const exited = exitCode.then(
7581
+ () => true,
7582
+ () => true
7344
7583
  );
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
- }
7584
+ const killGroup = [
7585
+ `IFS= read -r pid < ${shellQuote(controlPath)} || exit 0`,
7586
+ '[ -n "$pid" ] || exit 0',
7587
+ "printf found",
7588
+ 'kill -KILL -- "-$pid" 2>/dev/null || exit 0',
7589
+ "group_alive() {",
7590
+ " local stat rest state pgrp",
7591
+ " for stat_path in /proc/[0-9]*/stat; do",
7592
+ ' IFS= read -r stat < "$stat_path" || continue',
7593
+ " rest=${stat##*) }",
7594
+ ' read -r state _ pgrp _ <<< "$rest"',
7595
+ ' if [ "$pgrp" = "$pid" ] && [ "$state" != Z ]; then return 0; fi',
7596
+ " done",
7597
+ " return 1",
7598
+ "}",
7599
+ "while group_alive; do sleep 0.01; done"
7600
+ ].join("\n");
7601
+ while (true) {
7602
+ const { stdout } = await container.exec(["bash", "-c", killGroup]);
7603
+ if (stdout) return;
7604
+ if (await Promise.race([exited, delay(10).then(() => false)])) return;
7605
+ }
7606
+ }
7607
+ function validateEnv(env, errors) {
7608
+ for (const key of Object.keys(env ?? {})) {
7609
+ if (key.length === 0 || key.includes("=")) {
7610
+ throw errors.generic(`Invalid environment variable key: "${key}"`);
7362
7611
  }
7363
7612
  }
7364
7613
  }
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";
7614
+ function containerSession(container, errors) {
7615
+ const scope = ({
7616
+ workingDirectory,
7617
+ env
7618
+ }) => {
7619
+ validateEnv(env, errors);
7620
+ return {
7621
+ env,
7622
+ workingDirectory: workingDirectory === void 0 ? void 0 : resolveIn(container.workdir, workingDirectory)
7623
+ };
7624
+ };
7625
+ async function spawn5(options) {
7626
+ const { command, abortSignal, stdin } = options;
7627
+ abortSignal?.throwIfAborted();
7628
+ const controlPath = `/dev/shm/deepagents-exec-${randomUUID()}.pid`;
7629
+ const process2 = await container.spawn(
7630
+ [
7631
+ "bash",
7632
+ "-c",
7633
+ managedCommand(command, controlPath, container.commandTimeout)
7634
+ ],
7635
+ { ...scope(options), stdin }
7636
+ );
7637
+ const control = controlProcess({
7638
+ exitCode: process2.exitCode,
7639
+ kill: () => terminate(container, controlPath, process2.exitCode),
7640
+ abortSignal
7641
+ });
7642
+ return {
7643
+ stdout: process2.stdout,
7644
+ stderr: process2.stderr,
7645
+ ...process2.stdin ? { stdin: process2.stdin } : {},
7646
+ ...control
7647
+ };
7648
+ }
7649
+ const readBinaryFile = async ({
7650
+ path: path6,
7651
+ abortSignal
7652
+ }) => {
7653
+ abortSignal?.throwIfAborted();
7654
+ return container.readFile(path6, abortSignal);
7655
+ };
7656
+ const writeBinaryFile = async ({
7657
+ path: path6,
7658
+ content,
7659
+ abortSignal
7660
+ }) => {
7661
+ abortSignal?.throwIfAborted();
7662
+ return container.writeFile(path6, content, abortSignal);
7663
+ };
7664
+ return {
7665
+ description: `Commands run through bash -lc in a Linux container, starting in ${container.workdir}.`,
7666
+ run: async (options) => {
7667
+ const { command, abortSignal } = options;
7668
+ abortSignal?.throwIfAborted();
7669
+ if (!abortSignal && !container.commandTimeout) {
7670
+ return container.exec(["bash", "-lc", command], scope(options));
7671
+ }
7672
+ return collect(await spawn5(options));
7673
+ },
7674
+ spawn: spawn5,
7675
+ readBinaryFile,
7676
+ readFile: async (options) => {
7677
+ const bytes = await readBinaryFile(options);
7678
+ return bytes && ReadableStream.from([bytes]);
7679
+ },
7680
+ writeBinaryFile,
7681
+ writeFile: async ({ content, ...options }) => writeBinaryFile({
7682
+ ...options,
7683
+ content: await new Response(content).bytes()
7684
+ }),
7685
+ ...textCalls({ readBinaryFile, writeBinaryFile }),
7686
+ stat: async ({ path: path6, abortSignal }) => {
7687
+ abortSignal?.throwIfAborted();
7688
+ return container.stat(path6, abortSignal);
7689
+ },
7690
+ listDirectory: ({ path: path6, abortSignal }) => listDirectoryOverExec(container, path6, abortSignal),
7691
+ deleteFile: ({ path: path6, abortSignal }) => deleteFileOverExec(container, path6, abortSignal)
7692
+ };
7693
+ }
7370
7694
 
7371
7695
  // packages/context/src/lib/sandbox/docker-sandbox-errors.ts
7372
7696
  var DockerSandboxError = class extends ContainerSandboxError {
@@ -7577,20 +7901,10 @@ function createInstallerContext(shell, containerId, image) {
7577
7901
  };
7578
7902
  }
7579
7903
 
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
7904
  // packages/context/src/lib/sandbox/container-sandbox.ts
7587
7905
  var CONTAINER_NAME_PATTERN = /^[A-Za-z0-9_.-]+$/;
7588
7906
  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
- }
7907
+ validateEnv(opts.env, errors);
7594
7908
  if (opts.name !== void 0 && !CONTAINER_NAME_PATTERN.test(opts.name)) {
7595
7909
  throw errors.generic(
7596
7910
  `Invalid container name: "${opts.name}". Use only letters, numbers, underscore, period, or hyphen. The "sandbox-" prefix is added automatically.`
@@ -7598,7 +7912,7 @@ function validateSandboxOptions(opts, errors) {
7598
7912
  }
7599
7913
  }
7600
7914
  function suppress(originalError, cleanupError) {
7601
- if (!(originalError instanceof Error)) return;
7915
+ if (!Error.isError(originalError)) return;
7602
7916
  const suppressed = "suppressed" in originalError && Array.isArray(originalError.suppressed) ? originalError.suppressed : [];
7603
7917
  Object.assign(originalError, { suppressed: [...suppressed, cleanupError] });
7604
7918
  }
@@ -7644,7 +7958,7 @@ var ContainerSandboxStrategy = class {
7644
7958
  await this.engine.dispose();
7645
7959
  throw error;
7646
7960
  }
7647
- const sandbox = this.createSandboxMethods(acquired.container);
7961
+ const sandbox = this.createSandboxMethods(acquired);
7648
7962
  if (this.opts.readiness) {
7649
7963
  try {
7650
7964
  await this.opts.readiness(sandbox);
@@ -7657,7 +7971,7 @@ var ContainerSandboxStrategy = class {
7657
7971
  return sandbox;
7658
7972
  }
7659
7973
  containerName() {
7660
- return this.name ? `sandbox-${this.name}` : `sandbox-${randomUUID().slice(0, 8)}`;
7974
+ return this.name ? `sandbox-${this.name}` : `sandbox-${randomUUID2().slice(0, 8)}`;
7661
7975
  }
7662
7976
  async acquireContainer(image) {
7663
7977
  const name = this.containerName();
@@ -7787,12 +8101,12 @@ var ContainerSandboxStrategy = class {
7787
8101
  this.createdVolumes.delete(volume);
7788
8102
  }
7789
8103
  }
7790
- /** Ends the sandbox's hold on its container: stops it, by default. */
8104
+ /** Ends a container that this sandbox created: stops it, by default. */
7791
8105
  release(container) {
7792
8106
  return container.stop();
7793
8107
  }
7794
8108
  async assertBashAvailable(container) {
7795
- const result = await container.executeCommand(":");
8109
+ const result = await container.exec(["bash", "-lc", ":"]);
7796
8110
  if (result.exitCode === 0) return;
7797
8111
  const detail = result.stderr.trim() || result.stdout.trim();
7798
8112
  throw this.engine.errors.generic(
@@ -7800,26 +8114,24 @@ var ContainerSandboxStrategy = class {
7800
8114
  container.name
7801
8115
  );
7802
8116
  }
7803
- createSandboxMethods(container) {
8117
+ createSandboxMethods({
8118
+ container,
8119
+ attached
8120
+ }) {
7804
8121
  let disposal;
7805
8122
  const dispose = async () => {
7806
8123
  try {
7807
- await this.release(container);
8124
+ if (!attached) await this.release(container);
7808
8125
  await this.cleanupCreatedVolumes();
7809
8126
  } finally {
7810
8127
  await this.engine.dispose();
7811
8128
  }
7812
8129
  };
8130
+ const disposeOnce = () => disposal ??= dispose();
7813
8131
  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
- }
8132
+ ...containerSession(container, this.engine.errors),
8133
+ dispose: disposeOnce,
8134
+ [Symbol.asyncDispose]: disposeOnce
7823
8135
  };
7824
8136
  }
7825
8137
  };
@@ -7893,10 +8205,10 @@ function buildMountArg(volume) {
7893
8205
  return parts.join(",");
7894
8206
  }
7895
8207
  function getCliErrorMessage(error) {
7896
- if (error instanceof SubprocessError2) {
8208
+ if (error instanceof SubprocessError) {
7897
8209
  return error.stderr.trim() || error.stdout.trim() || error.message;
7898
8210
  }
7899
- return error instanceof Error && error.message || String(error);
8211
+ return Error.isError(error) && error.message || String(error);
7900
8212
  }
7901
8213
  function safeParseArray(stdout) {
7902
8214
  try {
@@ -7932,53 +8244,85 @@ function isMissing(message2) {
7932
8244
  function isNameConflict(message2) {
7933
8245
  return /already exists/i.test(message2);
7934
8246
  }
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];
8247
+ function drained(pipe) {
8248
+ const readable = createByteReadable();
8249
+ pipe.on("data", (chunk) => readable.enqueue(chunk));
8250
+ pipe.once("end", () => readable.close());
8251
+ pipe.once("error", (error) => readable.error(error));
8252
+ return readable.stream;
7946
8253
  }
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
- }
8254
+ function engineProcess(child) {
8255
+ return {
8256
+ stdout: drained(child.stdout),
8257
+ stderr: drained(child.stderr),
8258
+ exitCode: once2(child, "close").then(([code]) => code ?? 1)
8259
+ };
7954
8260
  }
7955
8261
  var AppleContainer = class {
7956
8262
  name;
8263
+ workdir = WORKDIR;
7957
8264
  constructor(name) {
7958
8265
  this.name = name;
7959
8266
  }
7960
- executeCommand(command, options) {
7961
- return run(execArgs(this.name, command), options?.signal);
8267
+ async exec(argv, { stdin, ...options } = {}) {
8268
+ try {
8269
+ const child = this.#exec(argv, options, stdin !== void 0);
8270
+ child.stdin.on("error", () => {
8271
+ });
8272
+ child.stdin.end(stdin);
8273
+ return await collectOutput(engineProcess(child));
8274
+ } catch (error) {
8275
+ return {
8276
+ stdout: "",
8277
+ stderr: Error.isError(error) ? error.message : String(error),
8278
+ exitCode: 1
8279
+ };
8280
+ }
8281
+ }
8282
+ async spawn(argv, { stdin, ...options }) {
8283
+ const child = this.#exec(argv, options, stdin === true);
8284
+ if (stdin) {
8285
+ return { ...engineProcess(child), stdin: Writable.toWeb(child.stdin) };
8286
+ }
8287
+ child.stdin.end();
8288
+ return engineProcess(child);
7962
8289
  }
7963
- async spawn(command, options) {
7964
- return toSandboxProcess(
7965
- childSpawn(CLI, execArgs(this.name, command, options)),
7966
- options?.signal
8290
+ #exec(argv, {
8291
+ workingDirectory = WORKDIR,
8292
+ env = {},
8293
+ signal
8294
+ }, interactive) {
8295
+ return childSpawn(
8296
+ CLI,
8297
+ [
8298
+ "exec",
8299
+ ...interactive ? ["--interactive"] : [],
8300
+ "--cwd",
8301
+ workingDirectory,
8302
+ ...Object.entries(env).flatMap(([key, value]) => [
8303
+ "--env",
8304
+ `${key}=${value}`
8305
+ ]),
8306
+ this.name,
8307
+ ...argv
8308
+ ],
8309
+ // The CLI traps SIGTERM and exits 0, which would read as a success.
8310
+ { signal, killSignal: "SIGKILL" }
7967
8311
  );
7968
8312
  }
7969
- readFile(path6) {
7970
- return readFileOverExec((command) => this.executeCommand(command), path6);
8313
+ readFile(path6, signal) {
8314
+ return readFileOverExec(this, path6, signal);
7971
8315
  }
7972
- writeFiles(files) {
7973
- return writeFilesOverExec((command) => this.executeCommand(command), files);
8316
+ stat(path6, signal) {
8317
+ return statOverExec(this, path6, signal);
7974
8318
  }
7975
- exists(path6) {
7976
- return existsOverExec((command) => this.executeCommand(command), path6);
8319
+ writeFile(path6, content, signal) {
8320
+ return writeFileOverExec(this, path6, content, signal);
7977
8321
  }
7978
8322
  installerContext(image) {
7979
8323
  return createInstallerContext(
7980
8324
  {
7981
- exec: (command) => run(["exec", this.name, "sh", "-c", command]),
8325
+ exec: (command) => this.exec(["sh", "-c", command]),
7982
8326
  SandboxError: AppleContainerSandboxError
7983
8327
  },
7984
8328
  this.name,
@@ -7996,18 +8340,14 @@ var appleEngine = {
7996
8340
  bindMountsOnClient: true,
7997
8341
  defaultImage: "docker.io/library/bash:5.3-alpine3.24",
7998
8342
  runArgs(image, containerId, opts) {
7999
- const { memory = "1024M", cpus = 2 } = opts.resources ?? {};
8000
- const args = [
8001
- "run",
8002
- "--detach",
8003
- "--rm",
8004
- "--name",
8005
- containerId,
8006
- "--memory",
8007
- memory,
8008
- "--cpus",
8009
- String(cpus)
8010
- ];
8343
+ const { memory, cpus } = opts.resources ?? {};
8344
+ const args = ["run", "--detach", "--rm", "--name", containerId];
8345
+ if (memory) {
8346
+ args.push("--memory", memory);
8347
+ }
8348
+ if (cpus !== void 0) {
8349
+ args.push("--cpus", String(cpus));
8350
+ }
8011
8351
  if (opts.arch) {
8012
8352
  args.push("--arch", opts.arch);
8013
8353
  }
@@ -8059,7 +8399,7 @@ var appleEngine = {
8059
8399
  throw new AppleContainerCreationError(
8060
8400
  message2,
8061
8401
  image,
8062
- error instanceof Error ? error : void 0
8402
+ Error.isError(error) ? error : void 0
8063
8403
  );
8064
8404
  }
8065
8405
  }
@@ -8075,7 +8415,7 @@ var appleEngine = {
8075
8415
  throw new AppleContainerCreationError(
8076
8416
  message2,
8077
8417
  image,
8078
- error instanceof Error ? error : void 0
8418
+ Error.isError(error) ? error : void 0
8079
8419
  );
8080
8420
  }
8081
8421
  return { created: true, container: new AppleContainer(name) };
@@ -8129,17 +8469,23 @@ var appleEngine = {
8129
8469
  async buildImage(spec) {
8130
8470
  const archFlag = spec.identity ? ["--arch", spec.identity] : [];
8131
8471
  if (spec.dockerfile.includes("\n")) {
8132
- const tempDir = await mkdtemp(join(tmpdir(), "sandbox-containerfile-"));
8133
- const dockerfilePath = join(tempDir, "Dockerfile");
8472
+ await using tempDir = await new TemporaryFiles().directory(
8473
+ "sandbox-containerfile-"
8474
+ );
8475
+ const dockerfilePath = join(tempDir.path, "Dockerfile");
8134
8476
  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
- }
8477
+ await runAppleBuild(
8478
+ [
8479
+ "build",
8480
+ ...archFlag,
8481
+ "-t",
8482
+ spec.tag,
8483
+ "-f",
8484
+ dockerfilePath,
8485
+ tempDir.path
8486
+ ],
8487
+ spec.showBuildLogs
8488
+ );
8143
8489
  return;
8144
8490
  }
8145
8491
  await runAppleBuild(
@@ -8166,28 +8512,14 @@ var appleEngine = {
8166
8512
  };
8167
8513
  async function runAppleBuild(args, showBuildLogs) {
8168
8514
  try {
8169
- if (showBuildLogs) {
8170
- await runStreamed(CLI, args);
8171
- } else {
8172
- await spawn(CLI, args);
8173
- }
8515
+ await spawn(CLI, args, showBuildLogs ? { stdio: "inherit" } : {});
8174
8516
  } catch (error) {
8175
- throw new AppleContainerImageBuildError(getCliErrorMessage(error));
8176
- }
8177
- }
8178
- function runStreamed(command, args) {
8179
- return new Promise((resolve3, reject) => {
8180
- const child = childSpawn(command, args, { stdio: "inherit" });
8181
- child.once("error", reject);
8182
- child.once(
8183
- "exit",
8184
- (code) => code === 0 ? resolve3() : reject(
8185
- new Error(
8186
- `${command} build exited with code ${code} (see build output above)`
8187
- )
8517
+ throw new AppleContainerImageBuildError(
8518
+ getCliErrorMessage(
8519
+ error instanceof SubprocessError ? error.cause ?? error : error
8188
8520
  )
8189
8521
  );
8190
- });
8522
+ }
8191
8523
  }
8192
8524
  async function createAppleContainerSandbox(options = {}) {
8193
8525
  if (isAppleContainerfileOptions(options)) {
@@ -8204,12 +8536,8 @@ async function createAppleContainerSandbox(options = {}) {
8204
8536
  }).create();
8205
8537
  }
8206
8538
  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
- }
8539
+ await using sandbox = await createAppleContainerSandbox(options);
8540
+ return await fn(sandbox);
8213
8541
  }
8214
8542
 
8215
8543
  // packages/context/src/lib/sandbox/bash-exception.ts
@@ -8356,7 +8684,7 @@ var textFileFormat = {
8356
8684
  value: `Text file exceeds ${formatBytes(TEXT_MAX_BYTES)} limit (got ${formatBytes(bytes.byteLength)}). Use offset/limit to slice.`
8357
8685
  };
8358
8686
  }
8359
- const content = readFileContent(bytes, { encoding: "utf-8" });
8687
+ const content = new TextDecoder().decode(bytes);
8360
8688
  if (offset === void 0 && limit === void 0) {
8361
8689
  return { type: "text", value: content };
8362
8690
  }
@@ -8384,7 +8712,7 @@ var inputSchema = z11.strictObject({
8384
8712
  });
8385
8713
  function createReadFileTool({
8386
8714
  sandbox,
8387
- destination
8715
+ workingDirectory
8388
8716
  }) {
8389
8717
  return tool2({
8390
8718
  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 +8723,12 @@ function createReadFileTool({
8395
8723
  inputSchema,
8396
8724
  execute: async (input, options) => {
8397
8725
  options.abortSignal?.throwIfAborted();
8398
- const bytes = await sandbox.readFile(
8399
- path3.posix.resolve(destination, input.path),
8400
- { encoding: "binary" }
8401
- );
8726
+ const bytes = await sandbox.readBinaryFile({
8727
+ path: workingDirectory === void 0 ? input.path : path3.posix.resolve(workingDirectory, input.path),
8728
+ abortSignal: options.abortSignal
8729
+ });
8402
8730
  options.abortSignal?.throwIfAborted();
8731
+ if (bytes === null) throw new Error(`File not found: ${input.path}`);
8403
8732
  for (const format of formats) {
8404
8733
  const result = format.read({ ...input, bytes, options });
8405
8734
  if (result !== void 0) return result;
@@ -8411,111 +8740,12 @@ function createReadFileTool({
8411
8740
  }
8412
8741
 
8413
8742
  // packages/context/src/lib/sandbox/bash-tool.ts
8414
- var DEFAULT_DESTINATION = "/workspace";
8415
8743
  var DEFAULT_MAX_FILES = 1e3;
8416
8744
  var DEFAULT_MAX_OUTPUT_LENGTH = 3e4;
8417
8745
  var TEE_OUTPUT_DIR = "/tmp/bash-tool";
8418
- var WRITE_BATCH_SIZE = 20;
8746
+ var MAX_CONCURRENT_WRITES = 20;
8747
+ var COMMAND_TIMEOUT_EXIT_CODE = 124;
8419
8748
  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
8749
  function truncateOutput(output, maxLength, streamName) {
8520
8750
  if (output.length <= maxLength) return output;
8521
8751
  const removed = output.length - maxLength;
@@ -8530,6 +8760,9 @@ function makeTeeScriptPortable(script) {
8530
8760
  );
8531
8761
  return `set -o pipefail; ${withoutStatusAssignments}`;
8532
8762
  }
8763
+ function isTimeoutOf(signal, error) {
8764
+ return error === signal?.reason && error instanceof DOMException && error.name === "TimeoutError";
8765
+ }
8533
8766
  async function listInitialFiles(options) {
8534
8767
  const files = /* @__PURE__ */ new Map();
8535
8768
  if (options.uploadDirectory) {
@@ -8559,101 +8792,48 @@ async function listInitialFiles(options) {
8559
8792
  }
8560
8793
  return [...files.values()];
8561
8794
  }
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
- }))
8795
+ async function uploadInitialFiles(sandbox, workingDirectory, files) {
8796
+ for (let index = 0; index < files.length; index += MAX_CONCURRENT_WRITES) {
8797
+ await Promise.all(
8798
+ files.slice(index, index + MAX_CONCURRENT_WRITES).map(async (file) => {
8799
+ const target = workingDirectory === void 0 ? file.path : path4.posix.join(workingDirectory, file.path);
8800
+ await ("content" in file ? sandbox.writeTextFile({ path: target, content: file.content }) : sandbox.writeBinaryFile({
8801
+ path: target,
8802
+ content: await readFile(file.sourcePath)
8803
+ }));
8804
+ })
8569
8805
  );
8570
- await sandbox.writeFiles(batch);
8571
- }
8572
- }
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
8806
  }
8597
- return lines.join("\n");
8598
8807
  }
8599
8808
  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();
8809
+ return [
8810
+ "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.",
8811
+ options.sandboxDescription,
8812
+ options.experimentalTeeTransform && `Pipeline stdout is captured under ${TEE_OUTPUT_DIR}/. Use the returned teeFiles paths to inspect full intermediate output.`,
8813
+ options.extraInstructions,
8814
+ REASONING_INSTRUCTION
8815
+ ].filter(Boolean).join("\n\n");
8638
8816
  }
8639
8817
  async function createBashTool(options) {
8640
- const destination = options.destination ?? DEFAULT_DESTINATION;
8818
+ const { workingDirectory, sandbox } = options;
8641
8819
  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");
8820
+ if (workingDirectory !== void 0) {
8821
+ const created = await sandbox.run({
8822
+ command: `mkdir -p -- ${shellQuote(workingDirectory)}`
8823
+ });
8824
+ if (created.exitCode !== 0) {
8825
+ throw new Error(
8826
+ `Could not set up working directory ${workingDirectory}: ${created.stderr}`
8827
+ );
8828
+ }
8829
+ }
8830
+ await uploadInitialFiles(sandbox, workingDirectory, initialFiles);
8650
8831
  const experimentalTeeTransform = options.experimentalTeeTransform ?? false;
8651
8832
  const bash = tool3({
8652
8833
  description: createBashDescription({
8653
- destination,
8654
- filenames: initialFiles.map((file) => file.path),
8655
- toolPrompt,
8656
- extraInstructions,
8834
+ workingDirectory,
8835
+ sandboxDescription: sandbox.description,
8836
+ extraInstructions: options.extraInstructions,
8657
8837
  experimentalTeeTransform
8658
8838
  }),
8659
8839
  inputSchema: z12.object({
@@ -8664,32 +8844,49 @@ async function createBashTool(options) {
8664
8844
  let command = originalCommand;
8665
8845
  const before = options.onBeforeBashCall?.({ command });
8666
8846
  if (before?.command !== void 0) command = before.command;
8667
- let fullCommand;
8847
+ let script = command;
8668
8848
  let teeFiles;
8669
8849
  if (experimentalTeeTransform) {
8670
8850
  const pipeline = new BashTransformPipeline().use(
8671
8851
  new TeePlugin({ outputDir: TEE_OUTPUT_DIR })
8672
8852
  );
8673
8853
  const transformed = pipeline.transform(command);
8674
- fullCommand = `mkdir -p ${shellQuote(TEE_OUTPUT_DIR)} ${shellQuote(destination)} && cd ${shellQuote(destination)} && ${makeTeeScriptPortable(transformed.script)}`;
8854
+ script = `mkdir -p ${shellQuote(TEE_OUTPUT_DIR)} && ${makeTeeScriptPortable(transformed.script)}`;
8675
8855
  teeFiles = transformed.metadata.teeFiles.map(
8676
8856
  (file) => ({
8677
8857
  command: file.command,
8678
8858
  stdoutFile: file.stdoutFile
8679
8859
  })
8680
8860
  );
8681
- } else {
8682
- fullCommand = `mkdir -p ${shellQuote(destination)} && cd ${shellQuote(destination)} && ${command}`;
8683
8861
  }
8684
- let result = await sandbox.executeCommand(fullCommand, {
8685
- signal: executionOptions.abortSignal
8686
- });
8687
- const maxOutputLength = options.maxOutputLength ?? DEFAULT_MAX_OUTPUT_LENGTH;
8688
- result = {
8689
- ...result,
8690
- stdout: truncateOutput(result.stdout, maxOutputLength, "stdout"),
8691
- stderr: truncateOutput(result.stderr, maxOutputLength, "stderr"),
8692
- ...teeFiles ? { teeFiles } : {}
8862
+ const { abortSignal } = executionOptions;
8863
+ const startedAt = performance.now();
8864
+ let result;
8865
+ try {
8866
+ result = await sandbox.run({
8867
+ command: script,
8868
+ ...workingDirectory !== void 0 ? { workingDirectory } : {},
8869
+ abortSignal
8870
+ });
8871
+ } catch (error) {
8872
+ if (error instanceof BashException) {
8873
+ result = error.format();
8874
+ } else if (isTimeoutOf(abortSignal, error)) {
8875
+ result = {
8876
+ stdout: "",
8877
+ stderr: `Command timed out after ${Math.round(performance.now() - startedAt)} ms`,
8878
+ exitCode: COMMAND_TIMEOUT_EXIT_CODE
8879
+ };
8880
+ } else {
8881
+ throw error;
8882
+ }
8883
+ }
8884
+ const maxOutputLength = options.maxOutputLength ?? DEFAULT_MAX_OUTPUT_LENGTH;
8885
+ result = {
8886
+ ...result,
8887
+ stdout: truncateOutput(result.stdout, maxOutputLength, "stdout"),
8888
+ stderr: truncateOutput(result.stderr, maxOutputLength, "stderr"),
8889
+ ...teeFiles ? { teeFiles } : {}
8693
8890
  };
8694
8891
  const executionMeta = result.meta;
8695
8892
  const after = options.onAfterBashCall?.({ command, result });
@@ -8698,7 +8895,7 @@ async function createBashTool(options) {
8698
8895
  return Object.keys(meta).length > 0 ? { ...result, meta } : result;
8699
8896
  }
8700
8897
  });
8701
- const readFile2 = createReadFileTool({ sandbox, destination });
8898
+ const readFileTool = createReadFileTool({ sandbox, workingDirectory });
8702
8899
  const writeFile2 = tool3({
8703
8900
  description: "Write content to a file in the sandbox. Creates parent directories if needed.",
8704
8901
  inputSchema: z12.object({
@@ -8707,12 +8904,10 @@ async function createBashTool(options) {
8707
8904
  }),
8708
8905
  execute: async ({ path: filePath, content }) => {
8709
8906
  try {
8710
- await sandbox.writeFiles([
8711
- {
8712
- path: path4.posix.resolve(destination, filePath),
8713
- content
8714
- }
8715
- ]);
8907
+ await sandbox.writeTextFile({
8908
+ path: workingDirectory === void 0 ? filePath : path4.posix.resolve(workingDirectory, filePath),
8909
+ content
8910
+ });
8716
8911
  return { success: true };
8717
8912
  } catch (error) {
8718
8913
  if (error instanceof BashException) return error.format();
@@ -8720,14 +8915,18 @@ async function createBashTool(options) {
8720
8915
  }
8721
8916
  }
8722
8917
  });
8723
- const tools = withHostOnlyToolMetadata2({ bash, readFile: readFile2, writeFile: writeFile2 });
8918
+ const tools = withHostOnlyToolMetadata2({
8919
+ bash,
8920
+ readFile: readFileTool,
8921
+ writeFile: writeFile2
8922
+ });
8724
8923
  return { bash: tools.bash, tools, sandbox };
8725
8924
  }
8726
8925
 
8727
8926
  // packages/context/src/lib/sandbox/binary-bridges.ts
8728
8927
  import { existsSync as existsSync2 } from "fs";
8729
8928
  import { defineCommand } from "just-bash";
8730
- import spawn2, { SubprocessError as SubprocessError3 } from "nano-spawn";
8929
+ import spawn2, { SubprocessError as SubprocessError2 } from "nano-spawn";
8731
8930
  import * as path5 from "path";
8732
8931
  function createBinaryBridges(...binaries) {
8733
8932
  return binaries.map((input) => {
@@ -8775,7 +8974,7 @@ function createBinaryBridges(...binaries) {
8775
8974
  exitCode: 0
8776
8975
  };
8777
8976
  } catch (error) {
8778
- if (error instanceof SubprocessError3) {
8977
+ if (error instanceof SubprocessError2) {
8779
8978
  if (hasErrorCode(error.cause, "ENOENT")) {
8780
8979
  return {
8781
8980
  stdout: "",
@@ -8793,7 +8992,7 @@ function createBinaryBridges(...binaries) {
8793
8992
  }
8794
8993
  return {
8795
8994
  stdout: "",
8796
- stderr: `${name}: ${error instanceof Error ? error.message : String(error)}`,
8995
+ stderr: `${name}: ${Error.isError(error) ? error.message : String(error)}`,
8797
8996
  exitCode: 127
8798
8997
  };
8799
8998
  }
@@ -8822,11 +9021,17 @@ function mapToRealPath(fs, cwd) {
8822
9021
  }
8823
9022
 
8824
9023
  // packages/context/src/lib/sandbox/daytona-sandbox.ts
8825
- import { randomUUID as randomUUID2 } from "node:crypto";
9024
+ import "@ai-sdk/provider-utils";
9025
+ import { constants } from "node:os";
8826
9026
  import { setTimeout as setTimeout3 } from "node:timers/promises";
8827
- var DAYTONA_DEFAULT_DESTINATION = "/home/daytona";
8828
- var DAYTONA_EXIT_POLL_INTERVAL_MS = 250;
8829
- var DAYTONA_EXIT_POLL_TIMEOUT_MS = 3e4;
9027
+ var COMMAND_TIMEOUT_EXIT_CODE2 = 124;
9028
+ var TIMED_OUT_MESSAGE = "Command timed out";
9029
+ var SIGNAL_NUMBERS = new Map(Object.entries(constants.signals));
9030
+ var NOT_A_DIRECTORY = /\(os error 20\)$/;
9031
+ var ALREADY_EXISTS = /\(os error 17\)$/;
9032
+ var GATEWAY_NOT_READY = /not available/;
9033
+ var GATEWAY_ATTEMPTS = 10;
9034
+ var GATEWAY_RETRY_MS = 500;
8830
9035
  var DaytonaSandboxError = class extends Error {
8831
9036
  constructor(message2, cause) {
8832
9037
  super(message2);
@@ -8840,53 +9045,51 @@ var DaytonaCreationError = class extends DaytonaSandboxError {
8840
9045
  this.name = "DaytonaCreationError";
8841
9046
  }
8842
9047
  };
8843
- var DaytonaCommandError = class extends DaytonaSandboxError {
8844
- constructor(message2, cause) {
8845
- super(message2, cause);
8846
- this.name = "DaytonaCommandError";
8847
- }
8848
- };
8849
9048
  async function createDaytonaSandbox(client, options = {}) {
8850
- const target = validateDaytonaOptions(options);
8851
- const sdk = await import("@daytona/sdk");
8852
- let sandbox;
9049
+ const { commandTimeout, readiness, ...target } = options;
9050
+ const sdk = await import("@daytona/sdk/v2");
9051
+ const { sandbox, created } = await acquire(client, target);
9052
+ let session;
8853
9053
  try {
8854
- if ("sandboxId" in target) {
8855
- sandbox = await client.get(target.sandboxId);
8856
- await startIfStopped(sandbox, options);
8857
- } else {
8858
- sandbox = await acquireReusedSandbox(client, target.name, options, sdk);
8859
- }
9054
+ session = daytonaSession({
9055
+ sdk,
9056
+ sandbox,
9057
+ created,
9058
+ workdir: await startingDirectory(sdk, sandbox),
9059
+ commandTimeout
9060
+ });
8860
9061
  } catch (error) {
8861
- throw normalizeDaytonaError(error, sdk);
9062
+ if (created) await sandbox.delete();
9063
+ throw error;
8862
9064
  }
8863
- await assertDaytonaBash(sandbox, options.commandTimeout);
8864
- const backend = createDaytonaSandboxMethods({
8865
- sdk,
8866
- sandbox,
8867
- commandTimeout: options.commandTimeout
8868
- });
8869
- if (options.readiness) {
9065
+ if (readiness) {
8870
9066
  try {
8871
- await options.readiness(backend);
9067
+ await readiness(session);
8872
9068
  } catch (error) {
8873
- await backend.dispose().catch(() => {
8874
- });
9069
+ await session.dispose();
8875
9070
  throw error;
8876
9071
  }
8877
9072
  }
8878
- return backend;
9073
+ return session;
9074
+ }
9075
+ async function acquire(client, target) {
9076
+ if (target.sandboxId !== void 0) {
9077
+ return { sandbox: await client.get(target.sandboxId), created: false };
9078
+ }
9079
+ const { image, ...create } = target;
9080
+ const sandbox = await client.create(image, create);
9081
+ return { sandbox, created: sandbox.accessToken !== void 0 };
8879
9082
  }
8880
- async function assertDaytonaBash(sandbox, commandTimeout) {
9083
+ async function startingDirectory(sdk, sandbox) {
8881
9084
  try {
8882
- const result = await sandbox.process.executeCommand(
8883
- "bash -lc ':'",
8884
- void 0,
8885
- void 0,
8886
- commandTimeout
9085
+ const result = await whenGatewayReady(
9086
+ sdk,
9087
+ () => sandbox.process.run('printf %s "$PWD"', { shell: "bash", login: true })
8887
9088
  );
8888
- if (result.exitCode === void 0 || result.exitCode === 0) return;
8889
- throw new Error(result.result || `exit code ${result.exitCode}`);
9089
+ if (result.reason === "exited" && result.exitCode === 0) {
9090
+ return result.stdout;
9091
+ }
9092
+ throw new Error(result.stderr || result.reason);
8890
9093
  } catch (error) {
8891
9094
  const err = toError(error);
8892
9095
  throw new DaytonaCreationError(
@@ -8895,410 +9098,235 @@ async function assertDaytonaBash(sandbox, commandTimeout) {
8895
9098
  );
8896
9099
  }
8897
9100
  }
8898
- var UNRECOVERABLE_SANDBOX_STATES = /* @__PURE__ */ new Set([
8899
- "error",
8900
- "build_failed",
8901
- "destroyed"
8902
- ]);
8903
- async function acquireReusedSandbox(client, name, options, sdk) {
8904
- let existing;
8905
- try {
8906
- existing = await client.get(name);
8907
- } catch (error) {
8908
- if (error instanceof sdk.DaytonaNotFoundError) {
8909
- return createSandbox(client, options);
8910
- }
8911
- throw error;
8912
- }
8913
- if (existing.state && UNRECOVERABLE_SANDBOX_STATES.has(existing.state)) {
8914
- await deleteSandboxQuietly(existing, options);
8915
- return createSandbox(client, options);
8916
- }
8917
- await startIfStopped(existing, options);
8918
- return existing;
8919
- }
8920
- async function deleteSandboxQuietly(sandbox, options) {
8921
- try {
8922
- await sandbox.delete(options.deleteTimeout);
8923
- } catch {
8924
- }
8925
- }
8926
- async function startIfStopped(sandbox, options) {
8927
- if (sandbox.state && sandbox.state !== "started") {
8928
- await sandbox.start(options.startTimeout ?? options.createTimeout);
8929
- }
9101
+ async function whenGatewayReady(sdk, call) {
9102
+ for (let attempt = 1; ; attempt++) {
9103
+ try {
9104
+ return await call();
9105
+ } catch (error) {
9106
+ const notReady = error instanceof sdk.InternalServerError && GATEWAY_NOT_READY.test(error.message);
9107
+ if (!notReady || attempt === GATEWAY_ATTEMPTS) throw error;
9108
+ await setTimeout3(GATEWAY_RETRY_MS);
9109
+ }
9110
+ }
9111
+ }
9112
+ function exitCodeOf(result) {
9113
+ switch (result.reason) {
9114
+ case "exited":
9115
+ if (result.exitCode !== void 0) return result.exitCode;
9116
+ break;
9117
+ case "signaled": {
9118
+ const number = SIGNAL_NUMBERS.get(`SIG${result.signal}`);
9119
+ if (number !== void 0) return 128 + number;
9120
+ break;
9121
+ }
9122
+ case "timed_out":
9123
+ return COMMAND_TIMEOUT_EXIT_CODE2;
9124
+ case "lost":
9125
+ case "failed":
9126
+ case "unknown":
9127
+ break;
9128
+ }
9129
+ throw new DaytonaSandboxError(
9130
+ `The command ended without an exit code: ${result.rawReason ?? result.reason}`
9131
+ );
8930
9132
  }
8931
- function normalizeDaytonaError(error, sdk) {
8932
- const err = toError(error);
8933
- if (err instanceof sdk.DaytonaError) {
8934
- return err;
8935
- }
8936
- return new DaytonaCreationError(err.message, err);
8937
- }
8938
- function createSandbox(client, options) {
8939
- const base = compactObject({
8940
- name: options.name,
8941
- user: options.user,
8942
- language: options.language,
8943
- envVars: options.envVars,
8944
- labels: options.labels,
8945
- public: options.public,
8946
- autoStopInterval: options.autoStopInterval,
8947
- autoArchiveInterval: options.autoArchiveInterval,
8948
- autoDeleteInterval: options.autoDeleteInterval,
8949
- volumes: options.volumes,
8950
- networkBlockAll: options.networkBlockAll,
8951
- networkAllowList: options.networkAllowList,
8952
- ephemeral: options.ephemeral
8953
- });
8954
- if (options.image !== void 0) {
8955
- const params2 = compactObject({
8956
- ...base,
8957
- image: options.image,
8958
- resources: options.resources
8959
- });
8960
- return client.create(params2, {
8961
- timeout: options.createTimeout,
8962
- onSnapshotCreateLogs: options.onSnapshotCreateLogs
8963
- });
8964
- }
8965
- const params = compactObject({
8966
- ...base,
8967
- snapshot: options.snapshot
9133
+ function entryType(mode) {
9134
+ switch (mode[0]) {
9135
+ case "-":
9136
+ return "file";
9137
+ case "d":
9138
+ return "directory";
9139
+ case "L":
9140
+ return "symlink";
9141
+ default:
9142
+ return "other";
9143
+ }
9144
+ }
9145
+ function daytonaSession(args) {
9146
+ const { sdk, sandbox, created, workdir, commandTimeout } = args;
9147
+ const resolve3 = (path6) => resolveIn(workdir, path6);
9148
+ const processOptions = ({
9149
+ workingDirectory,
9150
+ env
9151
+ }) => ({
9152
+ shell: "bash",
9153
+ login: true,
9154
+ cwd: workingDirectory === void 0 ? workdir : resolve3(workingDirectory),
9155
+ ...env ? { env } : {},
9156
+ ...commandTimeout ? { executionTimeoutSeconds: Math.ceil(commandTimeout / 1e3) } : {}
8968
9157
  });
8969
- return client.create(params, { timeout: options.createTimeout });
8970
- }
8971
- function validateDaytonaOptions(options) {
8972
- if (options.image && options.snapshot) {
8973
- throw new DaytonaSandboxError(
8974
- 'Daytona sandbox options cannot include both "image" and "snapshot". Choose one environment source.'
8975
- );
8976
- }
8977
- if (options.resources && !options.image) {
8978
- throw new DaytonaSandboxError(
8979
- 'Daytona sandbox options can only include "resources" when creating from "image". The Daytona SDK does not apply resources during default or snapshot creation.'
8980
- );
8981
- }
8982
- if (options.sandboxId === void 0) {
8983
- if (options.name === void 0) {
8984
- throw new DaytonaSandboxError(
8985
- 'Daytona sandbox options require "name" (get-or-create) or "sandboxId" (attach). An unnamed sandbox cannot be reclaimed, since dispose() does not delete it.'
8986
- );
9158
+ const isMissing2 = (error) => error instanceof sdk.FileNotFoundError || error instanceof sdk.BadRequestError && NOT_A_DIRECTORY.test(error.message);
9159
+ const orNull = async (operation) => {
9160
+ try {
9161
+ return await operation();
9162
+ } catch (error) {
9163
+ if (isMissing2(error)) return null;
9164
+ throw error;
8987
9165
  }
8988
- return { name: options.name };
8989
- }
8990
- if (!options.sandboxId) {
8991
- return { sandboxId: options.sandboxId };
8992
- }
8993
- const creationOnlyFields = [
8994
- "name",
8995
- "user",
8996
- "snapshot",
8997
- "image",
8998
- "language",
8999
- "envVars",
9000
- "labels",
9001
- "public",
9002
- "resources",
9003
- "volumes",
9004
- "networkAllowList",
9005
- "networkBlockAll",
9006
- "autoStopInterval",
9007
- "autoArchiveInterval",
9008
- "autoDeleteInterval",
9009
- "ephemeral",
9010
- "onSnapshotCreateLogs"
9011
- ];
9012
- const present = creationOnlyFields.filter((field) => {
9013
- return options[field] !== void 0;
9014
- });
9015
- if (present.length > 0) {
9016
- throw new DaytonaSandboxError(
9017
- `Daytona sandbox options cannot combine "sandboxId" with creation options: ${present.join(", ")}`
9018
- );
9019
- }
9020
- return { sandboxId: options.sandboxId };
9021
- }
9022
- function createDaytonaSandboxMethods(args) {
9023
- const { sdk, sandbox, commandTimeout } = args;
9024
- const executeCommand = async (command, options) => {
9025
- if (options?.signal?.aborted) {
9026
- return abortedCommandResult();
9166
+ };
9167
+ const execRunner = {
9168
+ exec: async (argv) => {
9169
+ const result = await sandbox.process.run({ argv });
9170
+ return {
9171
+ stdout: result.stdout,
9172
+ stderr: result.stderr,
9173
+ exitCode: exitCodeOf(result)
9174
+ };
9027
9175
  }
9028
- let aborted = false;
9029
- const abort = () => {
9030
- aborted = true;
9176
+ };
9177
+ const stat = async ({ path: path6, abortSignal }) => {
9178
+ abortSignal?.throwIfAborted();
9179
+ const target = resolve3(path6);
9180
+ const info = await orNull(() => sandbox.fs.stat(target));
9181
+ if (!info) return null;
9182
+ const type = entryType(info.mode);
9183
+ if (type === "symlink")
9184
+ return statOverExec(execRunner, target, abortSignal);
9185
+ return { type, size: info.size };
9186
+ };
9187
+ async function spawn5(options) {
9188
+ const { command, abortSignal, stdin } = options;
9189
+ abortSignal?.throwIfAborted();
9190
+ const handle = await sandbox.process.start(command, {
9191
+ ...processOptions(options),
9192
+ stdin: stdin ? "open" : "closed"
9193
+ });
9194
+ const stdout = createByteReadable();
9195
+ const stderr = createByteReadable();
9196
+ const pump = async () => {
9197
+ for await (const event of handle.streamLogs({ encoding: "base64" })) {
9198
+ if (event.type !== "log") continue;
9199
+ const bytes = Buffer.from(event.frame.data, "base64");
9200
+ if (event.frame.channel === "stdout") stdout.enqueue(bytes);
9201
+ else if (event.frame.channel === "stderr") stderr.enqueue(bytes);
9202
+ }
9031
9203
  };
9032
- options?.signal?.addEventListener("abort", abort, { once: true });
9204
+ const exitCode = Promise.all([handle.wait(), pump()]).then(([result]) => {
9205
+ if (result.reason === "timed_out") {
9206
+ stderr.enqueue(new TextEncoder().encode(TIMED_OUT_MESSAGE));
9207
+ }
9208
+ return exitCodeOf(result);
9209
+ }).then(
9210
+ (code) => {
9211
+ stdout.close();
9212
+ stderr.close();
9213
+ return code;
9214
+ },
9215
+ (error) => {
9216
+ const err = toError(error);
9217
+ stdout.error(err);
9218
+ stderr.error(err);
9219
+ throw err;
9220
+ }
9221
+ );
9222
+ exitCode.catch(() => {
9223
+ });
9224
+ const control = controlProcess({
9225
+ exitCode,
9226
+ kill: () => handle.kill().catch((error) => {
9227
+ if (!(error instanceof sdk.ProcessTerminalError)) throw error;
9228
+ }),
9229
+ abortSignal
9230
+ });
9231
+ return {
9232
+ stdout: stdout.stream,
9233
+ stderr: stderr.stream,
9234
+ ...stdin ? {
9235
+ stdin: new WritableStream({
9236
+ write: (chunk) => handle.writeStdin(chunk),
9237
+ close: () => handle.closeStdin(),
9238
+ abort: () => handle.closeStdin()
9239
+ })
9240
+ } : {},
9241
+ ...control
9242
+ };
9243
+ }
9244
+ const readBinaryFile = async ({
9245
+ path: path6,
9246
+ abortSignal
9247
+ }) => {
9248
+ abortSignal?.throwIfAborted();
9249
+ return orNull(() => sandbox.fs.readBytes(resolve3(path6)));
9250
+ };
9251
+ const writeBinaryFile = async ({
9252
+ path: path6,
9253
+ content,
9254
+ abortSignal
9255
+ }) => {
9256
+ abortSignal?.throwIfAborted();
9257
+ const target = resolve3(path6);
9033
9258
  try {
9034
- if (aborted || options?.signal?.aborted) {
9035
- return abortedCommandResult();
9036
- }
9037
- const response = await sandbox.process.executeCommand(
9038
- `bash -lc ${shellQuote(command)}`,
9039
- void 0,
9040
- void 0,
9041
- commandTimeout
9042
- );
9043
- if (aborted) return abortedCommandResult();
9044
- return {
9045
- stdout: response.result ?? response.artifacts?.stdout ?? "",
9046
- stderr: "",
9047
- exitCode: response.exitCode ?? 0
9048
- };
9259
+ await sandbox.fs.writeBytes(target, content);
9049
9260
  } catch (error) {
9050
- if (aborted) return abortedCommandResult();
9051
- return { stdout: "", stderr: toError(error).message, exitCode: 1 };
9052
- } finally {
9053
- options?.signal?.removeEventListener("abort", abort);
9261
+ if (error instanceof sdk.BadRequestError && ALREADY_EXISTS.test(error.message) && (await stat({ path: target }))?.type === "directory") {
9262
+ throw new Error(`Cannot write "${path6}": it is a directory.`, {
9263
+ cause: error
9264
+ });
9265
+ }
9266
+ throw error;
9054
9267
  }
9055
9268
  };
9269
+ let disposing;
9270
+ const dispose = () => disposing ??= created ? sandbox.delete() : Promise.resolve();
9056
9271
  return {
9057
- executeCommand,
9058
- async spawn(command, options) {
9059
- const sessionId = `deepagents-spawn-${randomUUID2()}`;
9060
- const stdout = createTextReadable();
9061
- const stderr = createTextReadable();
9062
- const signal = options?.signal;
9063
- const sessionCommand = buildSessionCommand(command, { ...options });
9064
- const exit = (async () => {
9065
- let sessionCreated = false;
9066
- let aborted = signal?.aborted === true;
9067
- const { promise: abortPromise, resolve: resolveAbort } = Promise.withResolvers();
9068
- const abort = () => {
9069
- aborted = true;
9070
- resolveAbort("aborted");
9071
- if (sessionCreated) {
9072
- sandbox.process.deleteSession(sessionId).catch(() => {
9073
- });
9074
- }
9075
- };
9076
- if (signal) {
9077
- if (signal.aborted) abort();
9078
- else signal.addEventListener("abort", abort, { once: true });
9079
- }
9080
- try {
9081
- await sandbox.process.createSession(sessionId);
9082
- sessionCreated = true;
9083
- if (aborted) return abortedExitInfo();
9084
- const response = await sandbox.process.executeSessionCommand(
9085
- sessionId,
9086
- {
9087
- command: sessionCommand,
9088
- runAsync: true,
9089
- suppressInputEcho: true
9090
- },
9091
- commandTimeout
9092
- );
9093
- const commandId = response.cmdId;
9094
- if (!commandId) {
9095
- throw new DaytonaCommandError(
9096
- "Daytona did not return a command id for the spawned session command."
9097
- );
9098
- }
9099
- if (aborted) return abortedExitInfo();
9100
- const logsTask = sandbox.process.getSessionCommandLogs(
9101
- sessionId,
9102
- commandId,
9103
- stdout.enqueue,
9104
- stderr.enqueue
9105
- );
9106
- logsTask.catch(() => {
9107
- });
9108
- const winner = await Promise.race([logsTask, abortPromise]);
9109
- if (winner === "aborted") {
9110
- await sandbox.process.deleteSession(sessionId).catch(() => {
9111
- });
9112
- return abortedExitInfo();
9113
- }
9114
- const timeoutMs = commandTimeout === void 0 ? DAYTONA_EXIT_POLL_TIMEOUT_MS : Math.max(commandTimeout * 1e3, DAYTONA_EXIT_POLL_TIMEOUT_MS);
9115
- const deadline = Date.now() + timeoutMs;
9116
- while (true) {
9117
- if (aborted)
9118
- throw new DaytonaCommandError("Daytona command aborted.");
9119
- const info = await sandbox.process.getSessionCommand(
9120
- sessionId,
9121
- commandId
9122
- );
9123
- if (typeof info.exitCode === "number") {
9124
- return {
9125
- code: info.exitCode,
9126
- signal: null,
9127
- success: info.exitCode === 0
9128
- };
9129
- }
9130
- if (Date.now() >= deadline) {
9131
- throw new DaytonaCommandError(
9132
- `Daytona session command "${commandId}" logs closed before an exit code became available.`
9133
- );
9134
- }
9135
- await setTimeout3(DAYTONA_EXIT_POLL_INTERVAL_MS);
9136
- }
9137
- } catch (error) {
9138
- if (aborted) return abortedExitInfo();
9139
- const err = toError(error);
9140
- stdout.error(err);
9141
- stderr.error(err);
9142
- throw err;
9143
- } finally {
9144
- if (signal) {
9145
- signal.removeEventListener("abort", abort);
9146
- }
9147
- stdout.close();
9148
- stderr.close();
9149
- if (sessionCreated) {
9150
- await sandbox.process.deleteSession(sessionId).catch(() => {
9151
- });
9152
- }
9153
- }
9154
- })();
9155
- return { stdout: stdout.stream, stderr: stderr.stream, exit };
9272
+ description: `Commands run through bash -lc in a Daytona sandbox, starting in ${workdir}.`,
9273
+ run: async (options) => {
9274
+ const { command, abortSignal } = options;
9275
+ abortSignal?.throwIfAborted();
9276
+ if (abortSignal) return collect(await spawn5(options));
9277
+ const result = await sandbox.process.run(
9278
+ command,
9279
+ processOptions(options)
9280
+ );
9281
+ return {
9282
+ stdout: result.stdout,
9283
+ stderr: result.reason === "timed_out" ? `${result.stderr}${TIMED_OUT_MESSAGE}` : result.stderr,
9284
+ exitCode: exitCodeOf(result)
9285
+ };
9156
9286
  },
9157
- async readFile(path6, options) {
9158
- try {
9159
- const bytes = await sandbox.fs.downloadFile(path6);
9160
- return readFileContent(bytes, options);
9161
- } catch (error) {
9162
- throw new DaytonaCommandError(
9163
- `Failed to read file "${path6}": ${toError(error).message}`,
9164
- toError(error)
9165
- );
9166
- }
9287
+ spawn: spawn5,
9288
+ readBinaryFile,
9289
+ readFile: async (options) => {
9290
+ const bytes = await readBinaryFile(options);
9291
+ return bytes && ReadableStream.from([bytes]);
9167
9292
  },
9168
- async exists(path6) {
9293
+ writeBinaryFile,
9294
+ writeFile: async ({ content, ...options }) => writeBinaryFile({
9295
+ ...options,
9296
+ content: await new Response(content).bytes()
9297
+ }),
9298
+ ...textCalls({ readBinaryFile, writeBinaryFile }),
9299
+ stat,
9300
+ listDirectory: async ({ path: path6, abortSignal }) => {
9301
+ abortSignal?.throwIfAborted();
9302
+ const target = resolve3(path6);
9169
9303
  try {
9170
- await sandbox.fs.getFileDetails(path6);
9171
- return true;
9304
+ const { items } = await sandbox.fs.list(target);
9305
+ return items.map((info) => ({
9306
+ name: info.name,
9307
+ type: entryType(info.mode)
9308
+ }));
9172
9309
  } catch (error) {
9173
- if (error instanceof sdk.DaytonaNotFoundError) return false;
9174
- throw new DaytonaCommandError(
9175
- `Failed to check "${path6}": ${toError(error).message}`,
9176
- toError(error)
9177
- );
9310
+ if (!isMissing2(error) || await stat({ path: target })) throw error;
9311
+ return null;
9178
9312
  }
9179
9313
  },
9180
- async writeFiles(files) {
9314
+ deleteFile: async ({ path: path6, abortSignal }) => {
9315
+ abortSignal?.throwIfAborted();
9181
9316
  try {
9182
- for (const dir of uniqueParentDirectories(files.map((f) => f.path))) {
9183
- const result = await executeCommand(`mkdir -p ${shellQuote(dir)}`);
9184
- if (result.exitCode !== 0) {
9185
- throw new DaytonaCommandError(
9186
- `Failed to create directory "${dir}": ${result.stderr}`
9187
- );
9188
- }
9189
- }
9190
- await sandbox.fs.uploadFiles(
9191
- files.map((file) => ({
9192
- source: Buffer.from(file.content),
9193
- destination: file.path
9194
- }))
9195
- );
9317
+ await sandbox.fs.remove(resolve3(path6));
9318
+ return true;
9196
9319
  } catch (error) {
9197
- if (error instanceof DaytonaSandboxError) throw error;
9198
- const err = toError(error);
9199
- throw new DaytonaCommandError(
9200
- `Failed to write files: ${err.message}`,
9201
- err
9202
- );
9320
+ if (isMissing2(error)) return false;
9321
+ throw error;
9203
9322
  }
9204
9323
  },
9205
- async dispose() {
9206
- },
9207
- [Symbol.asyncDispose]() {
9208
- return this.dispose();
9209
- }
9210
- };
9211
- }
9212
- function createTextReadable() {
9213
- const encoder = new TextEncoder();
9214
- const ended = {
9215
- enqueue() {
9216
- },
9217
- close() {
9218
- },
9219
- error() {
9220
- }
9221
- };
9222
- let sink = ended;
9223
- const stream = new ReadableStream({
9224
- start(controller) {
9225
- sink = {
9226
- enqueue(chunk) {
9227
- if (chunk) controller.enqueue(encoder.encode(chunk));
9228
- },
9229
- close() {
9230
- sink = ended;
9231
- controller.close();
9232
- },
9233
- error(error) {
9234
- sink = ended;
9235
- controller.error(error);
9236
- }
9237
- };
9238
- }
9239
- });
9240
- return {
9241
- stream,
9242
- enqueue: (chunk) => sink.enqueue(chunk),
9243
- close: () => sink.close(),
9244
- error: (error) => sink.error(error)
9324
+ dispose,
9325
+ [Symbol.asyncDispose]: dispose
9245
9326
  };
9246
9327
  }
9247
- function buildSessionCommand(command, options) {
9248
- const cwdPrefix = options.cwd ? `cd ${shellQuote(options.cwd)} && ` : "";
9249
- const env = options.env ?? {};
9250
- const entries = Object.entries(env);
9251
- if (entries.length === 0) {
9252
- return `bash -lc ${shellQuote(`${cwdPrefix}${command}`)}`;
9253
- }
9254
- for (const [key] of entries) {
9255
- validateEnvKey(key);
9256
- }
9257
- const exports = entries.map(([key, value]) => `export ${key}=${shellQuote(value)}`).join("; ");
9258
- return `bash -lc ${shellQuote(`${exports}; ${cwdPrefix}${command}`)}`;
9259
- }
9260
- function validateEnvKey(key) {
9261
- if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) {
9262
- throw new DaytonaSandboxError(
9263
- `Invalid environment variable key: "${key}". Use shell-compatible environment variable names.`
9264
- );
9265
- }
9266
- }
9267
- function abortedCommandResult() {
9268
- return {
9269
- stdout: "",
9270
- stderr: "Command aborted",
9271
- exitCode: 1
9272
- };
9273
- }
9274
- function abortedExitInfo() {
9275
- return {
9276
- code: null,
9277
- signal: "SIGKILL",
9278
- success: false
9279
- };
9280
- }
9281
- function uniqueParentDirectories(paths) {
9282
- const dirs = /* @__PURE__ */ new Set();
9283
- for (const path6 of paths) {
9284
- const index = path6.lastIndexOf("/");
9285
- if (index > 0) {
9286
- dirs.add(path6.slice(0, index));
9287
- }
9288
- }
9289
- return [...dirs];
9290
- }
9291
- function compactObject(input) {
9292
- const output = { ...input };
9293
- for (const [key, value] of Object.entries(output)) {
9294
- if (value === void 0) {
9295
- Reflect.deleteProperty(output, key);
9296
- }
9297
- }
9298
- return output;
9299
- }
9300
9328
  function toError(error) {
9301
- return error instanceof Error ? error : new Error(String(error));
9329
+ return Error.isError(error) ? error : new Error(String(error));
9302
9330
  }
9303
9331
 
9304
9332
  // packages/context/src/lib/sandbox/docker-sandbox.ts
@@ -9307,89 +9335,23 @@ import {
9307
9335
  ConnectionFailedError,
9308
9336
  ContainerNotFoundError,
9309
9337
  Docker,
9338
+ DockerEngineError,
9310
9339
  DockerError,
9311
9340
  ImageNotFoundError,
9312
9341
  NameConflictError,
9313
9342
  NotAFileError,
9314
- VolumeInUseError
9343
+ PathNotFoundError
9315
9344
  } from "@zukhruf/docker";
9316
- import spawn3, { SubprocessError as SubprocessError4 } from "nano-spawn";
9317
- import { spawn as childSpawn2 } from "node:child_process";
9318
- import { hash, randomUUID as randomUUID3 } from "node:crypto";
9345
+ import spawn3, { SubprocessError as SubprocessError3 } from "nano-spawn";
9346
+ import { hash } from "node:crypto";
9319
9347
  import { readFileSync as readFileSync2 } from "node:fs";
9320
- import { posix as posix2 } from "node:path";
9321
- import { setTimeout as delay } from "node:timers/promises";
9348
+ import { posix as posix3 } from "node:path";
9322
9349
  function isDockerfileOptions(opts) {
9323
9350
  return "dockerfile" in opts;
9324
9351
  }
9325
9352
  function isComposeOptions(opts) {
9326
9353
  return "compose" in opts;
9327
9354
  }
9328
- var SIZE_UNITS = {
9329
- "": 1,
9330
- k: 1024,
9331
- m: 1024 ** 2,
9332
- g: 1024 ** 3,
9333
- t: 1024 ** 4,
9334
- p: 1024 ** 5
9335
- };
9336
- function sizeInBytes(flag, value) {
9337
- const match = /^(\d+(?:\.\d+)?)\s*([kmgtp]?)(?:i?b)?$/i.exec(value);
9338
- if (!match) {
9339
- throw new DockerSandboxError(`Invalid ${flag} size: "${value}"`);
9340
- }
9341
- return Math.floor(Number(match[1]) * SIZE_UNITS[match[2].toLowerCase()]);
9342
- }
9343
- function ulimit(value) {
9344
- const match = /^([a-z]+)=(-?\d+)(?::(-?\d+))?$/.exec(value);
9345
- if (!match) {
9346
- throw new DockerSandboxError(`Invalid ulimit: "${value}"`);
9347
- }
9348
- const soft = Number(match[2]);
9349
- return {
9350
- Name: match[1],
9351
- Soft: soft,
9352
- Hard: match[3] === void 0 ? soft : Number(match[3])
9353
- };
9354
- }
9355
- function device(value) {
9356
- const [host, container = host, permissions = "rwm"] = value.split(":");
9357
- return {
9358
- PathOnHost: host,
9359
- PathInContainer: container,
9360
- CgroupPermissions: permissions
9361
- };
9362
- }
9363
- function gpuRequest(value) {
9364
- if (value === "all") return { Count: -1, Capabilities: [["gpu"]] };
9365
- if (/^\d+$/.test(value)) {
9366
- return { Count: Number(value), Capabilities: [["gpu"]] };
9367
- }
9368
- const devices = /^device=(.+)$/.exec(value);
9369
- if (devices) {
9370
- return { DeviceIDs: devices[1].split(","), Capabilities: [["gpu"]] };
9371
- }
9372
- throw new DockerSandboxError(`Invalid gpus value: "${value}"`);
9373
- }
9374
- function publishedPort(value) {
9375
- const [address, protocol = "tcp"] = value.split("/");
9376
- const parts = address.split(":");
9377
- const containerPort = parts.pop();
9378
- const hostPort = parts.pop() ?? "";
9379
- const hostIp = parts.join(":");
9380
- if (!containerPort || !/^\d+$/.test(containerPort)) {
9381
- throw new DockerSandboxError(`Invalid publish value: "${value}"`);
9382
- }
9383
- return {
9384
- port: `${containerPort}/${protocol}`,
9385
- binding: { HostIp: hostIp, HostPort: hostPort }
9386
- };
9387
- }
9388
- function securityOption(entry) {
9389
- const match = /^seccomp[=:](.+)$/.exec(entry);
9390
- if (!match || match[1] === "unconfined") return entry;
9391
- return `seccomp=${JSON.stringify(JSON.parse(readFileSync2(match[1], "utf-8")))}`;
9392
- }
9393
9355
  function mount(volume) {
9394
9356
  const ReadOnly = volume.readOnly !== false;
9395
9357
  if (volume.type === "bind") {
@@ -9414,106 +9376,22 @@ function mount(volume) {
9414
9376
  };
9415
9377
  }
9416
9378
  function containerCreateRequest(image, opts, workdir) {
9417
- const {
9418
- memory = "1g",
9419
- cpus = 2,
9420
- memorySwap,
9421
- shmSize,
9422
- pidsLimit,
9423
- ulimits = [],
9424
- cpusetCpus,
9425
- cpuShares
9426
- } = opts.resources ?? {};
9427
- const security = opts.security ?? {};
9428
- const network = opts.network ?? {};
9429
- const published = (network.publish ?? []).map(publishedPort);
9379
+ const { HostConfig, ...config } = opts.container ?? {};
9430
9380
  return {
9381
+ ...config,
9431
9382
  Image: image,
9432
9383
  WorkingDir: workdir,
9433
9384
  Env: Object.entries(opts.env ?? {}).map(
9434
9385
  ([key, value]) => `${key}=${value}`
9435
9386
  ),
9436
- Labels: opts.labels ?? {},
9437
9387
  ...opts.command === void 0 ? { Cmd: ["tail", "-f", "/dev/null"] } : opts.command === null || opts.command.length === 0 ? {} : { Cmd: [...opts.command] },
9438
- ...opts.entrypoint === void 0 ? {} : { Entrypoint: [opts.entrypoint] },
9439
- ...security.user ? { User: security.user } : {},
9440
- ...network.hostname ? { Hostname: network.hostname } : {},
9441
- ExposedPorts: Object.fromEntries(published.map(({ port }) => [port, {}])),
9442
9388
  HostConfig: {
9389
+ ...HostConfig,
9443
9390
  AutoRemove: true,
9444
- Memory: sizeInBytes("memory", memory),
9445
- NanoCpus: Math.round(cpus * 1e9),
9446
- ...memorySwap ? {
9447
- MemorySwap: memorySwap === "-1" ? -1 : sizeInBytes("memorySwap", memorySwap)
9448
- } : {},
9449
- ...shmSize ? { ShmSize: sizeInBytes("shmSize", shmSize) } : {},
9450
- ...pidsLimit === void 0 ? {} : { PidsLimit: pidsLimit },
9451
- Ulimits: ulimits.map(ulimit),
9452
- ...cpusetCpus ? { CpusetCpus: cpusetCpus } : {},
9453
- ...cpuShares === void 0 ? {} : { CpuShares: cpuShares },
9454
- ...opts.runtime ? { Runtime: opts.runtime } : {},
9455
- CapDrop: security.capDrop ?? [],
9456
- CapAdd: security.capAdd ?? [],
9457
- ReadonlyRootfs: security.readOnly === true,
9458
- Tmpfs: Object.fromEntries(
9459
- (security.tmpfs ?? []).map((entry) => {
9460
- const separator = entry.indexOf(":");
9461
- return separator < 0 ? [entry, ""] : [entry.slice(0, separator), entry.slice(separator + 1)];
9462
- })
9463
- ),
9464
- SecurityOpt: (security.securityOpt ?? []).map(securityOption),
9465
- ...network.mode ? { NetworkMode: network.mode } : {},
9466
- PortBindings: published.reduce(
9467
- (bindings, { port, binding }) => ({
9468
- ...bindings,
9469
- [port]: [...bindings[port] ?? [], binding]
9470
- }),
9471
- {}
9472
- ),
9473
- Dns: network.dns ?? [],
9474
- ExtraHosts: network.addHost ?? [],
9475
- ...opts.gpus ? { DeviceRequests: [gpuRequest(opts.gpus)] } : {},
9476
- Devices: (opts.devices ?? []).map(device),
9477
- ...opts.init ? { Init: true } : {},
9478
- Sysctls: opts.sysctls ?? {},
9479
9391
  Mounts: (opts.volumes ?? []).map(mount)
9480
9392
  }
9481
9393
  };
9482
9394
  }
9483
- function runDockerBuild(args, stdin, showBuildLogs, env) {
9484
- const stdio = [
9485
- stdin === void 0 ? "inherit" : "pipe",
9486
- showBuildLogs ? "inherit" : "ignore",
9487
- showBuildLogs ? "inherit" : "pipe"
9488
- ];
9489
- return new Promise((resolve3, reject) => {
9490
- const child = childSpawn2("docker", args, { stdio, env });
9491
- let stderr = "";
9492
- child.stderr?.on("data", (chunk) => {
9493
- stderr += chunk;
9494
- });
9495
- child.once(
9496
- "error",
9497
- (error) => reject(new DockerfileBuildError(error.message))
9498
- );
9499
- child.once("exit", (code) => {
9500
- if (code === 0) {
9501
- resolve3();
9502
- return;
9503
- }
9504
- reject(
9505
- new DockerfileBuildError(
9506
- showBuildLogs ? `docker build exited with code ${code} (see build output above)` : stderr || `docker build exited with code ${code}`
9507
- )
9508
- );
9509
- });
9510
- if (stdin !== void 0 && child.stdin) {
9511
- child.stdin.on("error", () => {
9512
- });
9513
- child.stdin.end(stdin);
9514
- }
9515
- });
9516
- }
9517
9395
  async function startContainer(container, image) {
9518
9396
  try {
9519
9397
  await container.start();
@@ -9524,7 +9402,7 @@ async function startContainer(container, image) {
9524
9402
  throw new ContainerCreationError(
9525
9403
  messageOf(error),
9526
9404
  image,
9527
- error instanceof Error ? error : void 0
9405
+ Error.isError(error) ? error : void 0
9528
9406
  );
9529
9407
  }
9530
9408
  }
@@ -9546,384 +9424,164 @@ var dockerErrors = {
9546
9424
  volumeInspect: (name, reason) => new VolumeInspectError(name, reason),
9547
9425
  volumeCreate: (name, reason) => new VolumeCreateError(name, reason)
9548
9426
  };
9549
- function withoutFinalNewline(text) {
9550
- return text.replace(/\r?\n$/, "");
9551
- }
9552
- function sandboxProcess(process2) {
9553
- const queue = { highWaterMark: Number.POSITIVE_INFINITY };
9554
- const stdout = new TransformStream(
9555
- void 0,
9556
- void 0,
9557
- queue
9558
- );
9559
- const stderr = new TransformStream(
9560
- void 0,
9561
- void 0,
9562
- queue
9563
- );
9564
- const writers = {
9565
- stdout: stdout.writable.getWriter(),
9566
- stderr: stderr.writable.getWriter()
9427
+ function engineProcess2(process2) {
9428
+ const streams = {
9429
+ stdout: createByteReadable(),
9430
+ stderr: createByteReadable()
9567
9431
  };
9568
- const exit = (async () => {
9432
+ const exitCode = (async () => {
9569
9433
  try {
9570
9434
  for await (const { stream, data } of process2) {
9571
- await writers[stream].write(data);
9435
+ streams[stream].enqueue(data);
9572
9436
  }
9573
9437
  } catch (error) {
9574
- await Promise.all([
9575
- writers.stdout.abort(error),
9576
- writers.stderr.abort(error)
9577
- ]);
9438
+ streams.stdout.error(error);
9439
+ streams.stderr.error(error);
9578
9440
  throw error;
9579
9441
  }
9580
- await Promise.all([writers.stdout.close(), writers.stderr.close()]);
9581
- const code = await process2.exitCode;
9582
- return { code, signal: null, success: code === 0 };
9442
+ streams.stdout.close();
9443
+ streams.stderr.close();
9444
+ return process2.exitCode;
9583
9445
  })();
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");
9446
+ return {
9447
+ stdout: streams.stdout.stream,
9448
+ stderr: streams.stderr.stream,
9449
+ ...process2.stdin ? { stdin: process2.stdin } : {},
9450
+ exitCode
9451
+ };
9613
9452
  }
9614
- var MAX_SYMLINK_HOPS = 40;
9615
9453
  var KERNEL_FILESYSTEMS = ["/proc", "/sys", "/dev"];
9616
- var RESOLVE_OWNER = [
9617
- "user=$1 group=$2",
9618
- 'case $user in *[!0-9]*) uid=$(id -u "$user") || exit 1 ;; *) uid=$user ;; esac',
9619
- "case $group in",
9620
- ' "") gid=$(id -g "$user" 2>/dev/null) || gid=0 ;;',
9621
- ` *[!0-9]*) gid=$(awk -F: -v name="$group" '$1 == name { print $3 }' /etc/group); [ -n "$gid" ] || { echo "unknown group $group" >&2; exit 1; } ;;`,
9622
- " *) gid=$group ;;",
9623
- "esac",
9624
- `printf '%s %s' "$uid" "$gid"`
9625
- ].join("\n");
9626
9454
  function fileLayout(config, hostConfig) {
9627
9455
  return {
9628
9456
  workdir: config?.WorkingDir || "/",
9629
- execOnly: [...KERNEL_FILESYSTEMS, ...Object.keys(hostConfig?.Tmpfs ?? {})],
9630
- user: config?.User ?? ""
9457
+ execOnly: [...KERNEL_FILESYSTEMS, ...Object.keys(hostConfig?.Tmpfs ?? {})]
9631
9458
  };
9632
9459
  }
9633
- async function resolveOwner(container, user2) {
9634
- if (user2 === "") return void 0;
9635
- const separator = user2.indexOf(":");
9636
- const [name, group] = separator < 0 ? [user2, ""] : [user2.slice(0, separator), user2.slice(separator + 1)];
9637
- const result = await container.exec({
9638
- Cmd: ["sh", "-c", RESOLVE_OWNER, "sh", name, group]
9639
- });
9640
- if (result.exitCode !== 0) {
9641
- throw new DockerSandboxError(
9642
- `Failed to resolve the container user "${user2}": ${result.stderr.trim()}`
9643
- );
9644
- }
9645
- const [uid, gid] = result.stdout.split(" ").map(Number);
9646
- return { uid, gid };
9647
- }
9648
9460
  function messageOf(error) {
9649
- return error instanceof Error ? error.message : String(error);
9461
+ return Error.isError(error) ? error.message : String(error);
9462
+ }
9463
+ function isUnexplainedFailure(error) {
9464
+ return error instanceof DockerEngineError && error.status === 500;
9465
+ }
9466
+ function fileType(mode) {
9467
+ const DIRECTORY = 2147483648;
9468
+ const LINK_DEVICE_PIPE_SOCKET_IRREGULAR = 254279680;
9469
+ if ((mode & DIRECTORY) !== 0) return "directory";
9470
+ return (mode & LINK_DEVICE_PIPE_SOCKET_IRREGULAR) === 0 ? "file" : "other";
9650
9471
  }
9651
9472
  var DockerContainer = class {
9652
9473
  name;
9474
+ workdir;
9475
+ commandTimeout;
9653
9476
  #container;
9654
- #layout;
9655
- /** Who owns the files the sandbox writes: the container user, or root. */
9656
- #owner;
9657
- #commandTimeout;
9658
- constructor(name, container, layout, owner, commandTimeout) {
9477
+ #execOnly;
9478
+ #autoRemove;
9479
+ constructor(name, container, layout, commandTimeout, autoRemove) {
9659
9480
  this.name = name;
9481
+ this.workdir = layout.workdir;
9482
+ this.commandTimeout = commandTimeout;
9660
9483
  this.#container = container;
9661
- this.#layout = layout;
9662
- this.#owner = owner;
9663
- this.#commandTimeout = commandTimeout;
9484
+ this.#execOnly = layout.execOnly;
9485
+ this.#autoRemove = autoRemove;
9664
9486
  }
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
- });
9487
+ #config(argv, { workingDirectory, env = {} }) {
9675
9488
  return {
9676
- Cmd: ["bash", "-lc", command],
9677
- Env: env,
9678
- ...options.cwd ? { WorkingDir: options.cwd } : {}
9489
+ Cmd: argv,
9490
+ Env: Object.entries(env).map(([key, value]) => `${key}=${value}`),
9491
+ ...workingDirectory ? { WorkingDir: workingDirectory } : {}
9679
9492
  };
9680
9493
  }
9681
- async #exec(config) {
9494
+ async exec(argv, options = {}) {
9682
9495
  try {
9683
- const { stdout, stderr, exitCode } = await this.#container.exec(config);
9684
- return {
9685
- stdout: withoutFinalNewline(stdout),
9686
- stderr: withoutFinalNewline(stderr),
9687
- exitCode
9688
- };
9496
+ const { stdout, stderr, exitCode } = await this.#container.exec(
9497
+ this.#config(argv, options),
9498
+ { signal: options.signal, stdin: options.stdin }
9499
+ );
9500
+ return { stdout, stderr, exitCode };
9689
9501
  } catch (error) {
9690
9502
  if (!(error instanceof DockerError)) throw error;
9691
9503
  return { stdout: "", stderr: error.message, exitCode: 1 };
9692
9504
  }
9693
9505
  }
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);
9506
+ async spawn(argv, options) {
9507
+ return engineProcess2(
9508
+ await this.#container.spawn(this.#config(argv, options), {
9509
+ stdin: options.stdin
9751
9510
  })
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
- );
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
9511
  );
9795
- return stdout === "terminated";
9796
9512
  }
9797
9513
  #resolve(path6) {
9798
- return posix2.resolve(this.#layout.workdir, path6);
9514
+ return posix3.resolve(this.workdir, path6);
9799
9515
  }
9800
9516
  /** The archive requests cannot reach a tmpfs mount or a kernel filesystem. */
9801
9517
  #isExecOnly(path6) {
9802
- return this.#layout.execOnly.some(
9518
+ return this.#execOnly.some(
9803
9519
  (root) => path6 === root || path6.startsWith(`${root}/`)
9804
- );
9805
- }
9806
- async readFile(path6) {
9807
- const target = this.#resolve(path6);
9808
- try {
9809
- return this.#isExecOnly(target) ? await this.#readByExec(target) : await this.#readArchive(target);
9810
- } catch (error) {
9811
- throw new Error(`Failed to read file "${path6}": ${messageOf(error)}`, {
9812
- cause: error
9813
- });
9814
- }
9520
+ );
9815
9521
  }
9816
- /** Follows symbolic links, as reading through the container's shell does. */
9817
- async #readArchive(path6) {
9522
+ /** The stat after symbolic links, which the engine's stat does not follow. */
9523
+ async #followLinks(path6, signal) {
9818
9524
  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);
9829
- }
9525
+ while (true) {
9526
+ const stat = await this.#container.stat(target, { signal });
9527
+ if (!stat) return void 0;
9528
+ if (stat.linkTarget === "") return { path: target, stat };
9529
+ target = posix3.resolve(posix3.dirname(target), stat.linkTarget);
9830
9530
  }
9831
9531
  }
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());
9532
+ async readFile(path6, signal) {
9533
+ const target = this.#resolve(path6);
9534
+ if (this.#isExecOnly(target)) {
9535
+ return readFileOverExec(this, target, signal);
9841
9536
  }
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,
9859
- directory: true,
9860
- ...owner
9861
- })),
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
- );
9537
+ try {
9538
+ return await this.#container.readFile(target, { signal });
9539
+ } catch (error) {
9540
+ if (error instanceof PathNotFoundError) return null;
9541
+ if (isUnexplainedFailure(error)) {
9542
+ return readFileOverExec(this, target, signal);
9873
9543
  }
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 }
9889
- );
9890
- if (result.exitCode !== 0) {
9891
- throw new Error(`Failed to write file "${path6}": ${result.stderr}`);
9544
+ if (!(error instanceof NotAFileError && error.kind === "symlink")) {
9545
+ throw error;
9892
9546
  }
9893
9547
  }
9548
+ const followed = await this.#followLinks(target, signal);
9549
+ return followed ? this.#container.readFile(followed.path, { signal }) : null;
9894
9550
  }
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);
9551
+ async stat(path6, signal) {
9552
+ const target = this.#resolve(path6);
9553
+ if (this.#isExecOnly(target)) return statOverExec(this, target, signal);
9554
+ try {
9555
+ const followed = await this.#followLinks(target, signal);
9556
+ return followed ? { type: fileType(followed.stat.mode), size: followed.stat.size } : null;
9557
+ } catch (error) {
9558
+ if (isUnexplainedFailure(error)) {
9559
+ return statOverExec(this, target, signal);
9902
9560
  }
9561
+ throw error;
9903
9562
  }
9904
- return [...missing].sort((a, b) => a.length - b.length);
9905
9563
  }
9906
- async exists(path6) {
9907
- let target = this.#resolve(path6);
9564
+ async writeFile(path6, content, signal) {
9565
+ const target = this.#resolve(path6);
9908
9566
  if (this.#isExecOnly(target)) {
9909
- const { exitCode } = await this.#container.exec({
9910
- Cmd: ["test", "-e", target]
9911
- });
9912
- return exitCode === 0;
9567
+ return writeFileOverExec(this, target, content, signal);
9913
9568
  }
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);
9569
+ try {
9570
+ await this.#container.writeFiles([{ path: target, data: content }], {
9571
+ signal,
9572
+ copyUIDGID: true
9573
+ });
9574
+ } catch (error) {
9575
+ throw new Error(`Failed to write file "${path6}": ${messageOf(error)}`, {
9576
+ cause: error
9577
+ });
9919
9578
  }
9920
- return false;
9921
9579
  }
9922
9580
  installerContext(image) {
9923
9581
  return createInstallerContext(
9924
9582
  {
9925
9583
  // Installers run with `sh -c`, before the sandbox knows Bash exists.
9926
- exec: (command) => this.#exec({ Cmd: ["sh", "-c", command] }),
9584
+ exec: (command) => this.exec(["sh", "-c", command]),
9927
9585
  SandboxError: DockerSandboxError
9928
9586
  },
9929
9587
  this.name,
@@ -9933,6 +9591,9 @@ var DockerContainer = class {
9933
9591
  async stop() {
9934
9592
  try {
9935
9593
  await this.#container.stop();
9594
+ if (this.#autoRemove) {
9595
+ await this.#container.wait({ condition: "removed" });
9596
+ }
9936
9597
  } catch (error) {
9937
9598
  if (error instanceof ContainerNotFoundError) return;
9938
9599
  throw error;
@@ -9964,14 +9625,13 @@ var DockerEngine = class _DockerEngine {
9964
9625
  return new _DockerEngine(docker, commandTimeout);
9965
9626
  }
9966
9627
  /** A sandbox container handle for a container of this engine. */
9967
- async container(name, container, info) {
9968
- const layout = fileLayout(info.Config, info.HostConfig);
9628
+ container(name, container, info) {
9969
9629
  return new DockerContainer(
9970
9630
  name,
9971
9631
  container,
9972
- layout,
9973
- await resolveOwner(container, layout.user),
9974
- this.#commandTimeout
9632
+ fileLayout(info.Config, info.HostConfig),
9633
+ this.#commandTimeout,
9634
+ info.HostConfig?.AutoRemove === true
9975
9635
  );
9976
9636
  }
9977
9637
  async attach(name, image) {
@@ -9990,7 +9650,7 @@ var DockerEngine = class _DockerEngine {
9990
9650
  return {
9991
9651
  created: true,
9992
9652
  // The image's own USER and WORKDIR are in the inspect, not the body.
9993
- container: await this.container(name, started, await started.inspect())
9653
+ container: this.container(name, started, await started.inspect())
9994
9654
  };
9995
9655
  } catch (error) {
9996
9656
  await started[Symbol.asyncDispose]();
@@ -10032,16 +9692,16 @@ var DockerEngine = class _DockerEngine {
10032
9692
  );
10033
9693
  if (volume) {
10034
9694
  return new VolumePathError(
10035
- error.source,
9695
+ volume.hostPath,
10036
9696
  volume.containerPath,
10037
9697
  "hostPath does not exist on host"
10038
9698
  );
10039
9699
  }
10040
9700
  }
10041
9701
  return new ContainerCreationError(
10042
- error instanceof Error ? error.message : String(error),
9702
+ Error.isError(error) ? error.message : String(error),
10043
9703
  image,
10044
- error instanceof Error ? error : void 0
9704
+ Error.isError(error) ? error : void 0
10045
9705
  );
10046
9706
  }
10047
9707
  async volumeExists(name) {
@@ -10053,7 +9713,7 @@ var DockerEngine = class _DockerEngine {
10053
9713
  }
10054
9714
  throw new VolumeInspectError(
10055
9715
  name,
10056
- error instanceof Error ? error.message : String(error)
9716
+ Error.isError(error) ? error.message : String(error)
10057
9717
  );
10058
9718
  }
10059
9719
  }
@@ -10061,7 +9721,7 @@ var DockerEngine = class _DockerEngine {
10061
9721
  try {
10062
9722
  await this.docker.volumes.create({
10063
9723
  Name: volume.name,
10064
- Labels: opts.labels ?? {},
9724
+ Labels: opts.container?.Labels,
10065
9725
  ...volume.driver ? { Driver: volume.driver } : {},
10066
9726
  DriverOpts: volume.driverOptions ?? {}
10067
9727
  });
@@ -10071,29 +9731,18 @@ var DockerEngine = class _DockerEngine {
10071
9731
  }
10072
9732
  throw new VolumeCreateError(
10073
9733
  volume.name,
10074
- error instanceof NameConflictError ? "managed volume already exists" : error instanceof Error ? error.message : String(error)
9734
+ error instanceof NameConflictError ? "managed volume already exists" : Error.isError(error) ? error.message : String(error)
10075
9735
  );
10076
9736
  }
10077
9737
  }
10078
9738
  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
- );
9739
+ try {
9740
+ await this.docker.volumes.find(name).then((volume) => volume?.remove());
9741
+ } catch (error) {
9742
+ if (error instanceof ConnectionFailedError) {
9743
+ throw new DockerNotAvailableError();
10096
9744
  }
9745
+ throw new VolumeRemoveError(name, messageOf(error));
10097
9746
  }
10098
9747
  }
10099
9748
  async ensureWorkdir() {
@@ -10101,23 +9750,33 @@ var DockerEngine = class _DockerEngine {
10101
9750
  async imageExists(tag) {
10102
9751
  return await this.docker.images.inspect(tag) !== void 0;
10103
9752
  }
9753
+ /** An inline Dockerfile goes to `docker build -f -` on stdin. */
10104
9754
  async buildImage(spec) {
10105
9755
  const inline = spec.dockerfile.includes("\n");
10106
- const args = [
10107
- "build",
10108
- ...spec.identity ? ["--platform", spec.identity] : [],
10109
- "-t",
10110
- spec.tag,
10111
- "-f",
10112
- inline ? "-" : spec.dockerfile,
10113
- spec.context
10114
- ];
10115
- await runDockerBuild(
10116
- args,
10117
- inline ? spec.dockerfile : void 0,
10118
- spec.showBuildLogs,
10119
- this.cliEnv
10120
- );
9756
+ try {
9757
+ await spawn3(
9758
+ "docker",
9759
+ [
9760
+ "build",
9761
+ ...spec.identity ? ["--platform", spec.identity] : [],
9762
+ "-t",
9763
+ spec.tag,
9764
+ "-f",
9765
+ inline ? "-" : spec.dockerfile,
9766
+ spec.context
9767
+ ],
9768
+ {
9769
+ stdin: inline ? { string: spec.dockerfile } : "inherit",
9770
+ stdout: spec.showBuildLogs ? "inherit" : "ignore",
9771
+ stderr: spec.showBuildLogs ? "inherit" : "pipe",
9772
+ env: this.cliEnv
9773
+ }
9774
+ );
9775
+ } catch (error) {
9776
+ throw new DockerfileBuildError(
9777
+ error instanceof SubprocessError3 ? error.stderr || messageOf(error.cause ?? error) : messageOf(error)
9778
+ );
9779
+ }
10121
9780
  }
10122
9781
  dispose() {
10123
9782
  return this.docker[Symbol.asyncDispose]();
@@ -10129,7 +9788,7 @@ var ComposeStrategy = class extends ContainerSandboxStrategy {
10129
9788
  service;
10130
9789
  dockerEngine;
10131
9790
  constructor(args, engine) {
10132
- super({ resources: args.resources }, engine);
9791
+ super({}, engine);
10133
9792
  this.dockerEngine = engine;
10134
9793
  this.composeFile = args.compose;
10135
9794
  this.service = args.service;
@@ -10151,7 +9810,7 @@ var ComposeStrategy = class extends ContainerSandboxStrategy {
10151
9810
  } catch (error) {
10152
9811
  throw new ComposeStartError(
10153
9812
  this.composeFile,
10154
- error instanceof SubprocessError4 && error.stderr || (error instanceof Error ? error.message : String(error))
9813
+ error instanceof SubprocessError3 && error.stderr || (Error.isError(error) ? error.message : String(error))
10155
9814
  );
10156
9815
  }
10157
9816
  const { containers } = this.dockerEngine.docker;
@@ -10173,7 +9832,7 @@ var ComposeStrategy = class extends ContainerSandboxStrategy {
10173
9832
  );
10174
9833
  }
10175
9834
  return {
10176
- container: await this.dockerEngine.container(
9835
+ container: this.dockerEngine.container(
10177
9836
  this.projectName,
10178
9837
  container,
10179
9838
  await container.inspect()
@@ -10200,11 +9859,7 @@ async function createDockerSandbox(options = {}) {
10200
9859
  try {
10201
9860
  if (isComposeOptions(options)) {
10202
9861
  strategy = new ComposeStrategy(
10203
- {
10204
- compose: options.compose,
10205
- service: options.service,
10206
- resources: options.resources
10207
- },
9862
+ { compose: options.compose, service: options.service },
10208
9863
  engine
10209
9864
  );
10210
9865
  } else if (isDockerfileOptions(options)) {
@@ -10227,21 +9882,17 @@ async function createDockerSandbox(options = {}) {
10227
9882
  return strategy.create();
10228
9883
  }
10229
9884
  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
- }
9885
+ await using sandbox = await createDockerSandbox(options);
9886
+ return await fn(sandbox);
10236
9887
  }
10237
9888
 
10238
9889
  // packages/context/src/lib/sandbox/strace/file-changes.ts
10239
- import { randomUUID as randomUUID4 } from "node:crypto";
10240
- import { posix as posix4 } from "node:path";
9890
+ import { randomUUID as randomUUID3 } from "node:crypto";
9891
+ import { posix as posix5 } from "node:path";
10241
9892
 
10242
9893
  // 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";
9894
+ import spawn4, { SubprocessError as SubprocessError4 } from "nano-spawn";
9895
+ import { posix as posix4 } from "node:path";
10245
9896
  var STRACE_FLAGS = "-f -y -qq -e trace=%file,write,pwrite64,writev";
10246
9897
  function buildStraceCommand(command, traceFile, traceDir) {
10247
9898
  return `mkdir -p ${shellQuote(traceDir)} 2>/dev/null; strace ${STRACE_FLAGS} -o ${shellQuote(traceFile)} -- bash -lc ${shellQuote(command)}`;
@@ -10359,14 +10010,14 @@ function openFlags(args) {
10359
10010
  return args.match(/\bO_[A-Z_]+(?:\|O_[A-Z_]+)*/)?.[0] ?? "";
10360
10011
  }
10361
10012
  function matchesGlobs(path6, include, exclude) {
10362
- return include.some((glob) => posix3.matchesGlob(path6, glob)) && !exclude?.some((glob) => posix3.matchesGlob(path6, glob));
10013
+ return include.some((glob) => posix4.matchesGlob(path6, glob)) && !exclude?.some((glob) => posix4.matchesGlob(path6, glob));
10363
10014
  }
10364
10015
  function parseStraceTrace(raw, options) {
10365
10016
  const { include, exclude, traceDir, traceFile } = options;
10366
10017
  const now = Date.now();
10367
10018
  const state = /* @__PURE__ */ new Map();
10368
10019
  const renames = [];
10369
- const resolve3 = (dir, p) => posix3.normalize(p.startsWith("/") ? p : posix3.join(dir, p));
10020
+ const resolve3 = (dir, p) => posix4.normalize(p.startsWith("/") ? p : posix4.join(dir, p));
10370
10021
  const write = (path6) => {
10371
10022
  state.set(path6, "write");
10372
10023
  };
@@ -10380,10 +10031,11 @@ function parseStraceTrace(raw, options) {
10380
10031
  const { syscall, args } = call;
10381
10032
  const dir = dirfdPath(args);
10382
10033
  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]);
10034
+ const [first2, ...rest] = quotedStrings(args);
10035
+ const last = rest.at(-1);
10036
+ if (last === void 0) continue;
10037
+ const from = resolve3(dir, first2);
10038
+ const to = resolve3(dir, last);
10387
10039
  state.delete(from);
10388
10040
  renames.push({ from, to });
10389
10041
  continue;
@@ -10399,8 +10051,8 @@ function parseStraceTrace(raw, options) {
10399
10051
  continue;
10400
10052
  }
10401
10053
  if (LINK_SYSCALLS.has(syscall)) {
10402
- const strings = quotedStrings(args);
10403
- if (strings.length) write(resolve3(dir, strings[strings.length - 1]));
10054
+ const last = quotedStrings(args).at(-1);
10055
+ if (last !== void 0) write(resolve3(dir, last));
10404
10056
  continue;
10405
10057
  }
10406
10058
  if (OPEN_SYSCALLS.has(syscall)) {
@@ -10411,7 +10063,7 @@ function parseStraceTrace(raw, options) {
10411
10063
  }
10412
10064
  if (WRITE_SYSCALLS.has(syscall)) {
10413
10065
  const p = fdPath(args);
10414
- if (p && Number(call.retval) > 0) write(posix3.normalize(p));
10066
+ if (p && Number(call.retval) > 0) write(posix4.normalize(p));
10415
10067
  continue;
10416
10068
  }
10417
10069
  if (TRUNCATE_SYSCALLS.has(syscall)) {
@@ -10465,18 +10117,14 @@ async function withStraceFileChanges(sandbox, options) {
10465
10117
  const { include, exclude, onFileChanges } = options;
10466
10118
  const onError = options.onError ?? warnOnFileChangesError;
10467
10119
  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(() => {
10120
+ const removeTrace = (traceFile) => void Promise.resolve(
10121
+ sandbox.run({ command: `rm -f ${shellQuote(traceFile)}` })
10122
+ ).catch(() => {
10471
10123
  });
10472
10124
  const readChanges = async (traceFile) => {
10473
10125
  try {
10474
- return parseStraceTrace(await sandbox.readFile(traceFile), {
10475
- include,
10476
- exclude,
10477
- traceFile,
10478
- traceDir
10479
- });
10126
+ const trace = await sandbox.readTextFile({ path: traceFile });
10127
+ return trace === null ? [] : parseStraceTrace(trace, { include, exclude, traceFile, traceDir });
10480
10128
  } catch {
10481
10129
  return [];
10482
10130
  } finally {
@@ -10492,19 +10140,60 @@ async function withStraceFileChanges(sandbox, options) {
10492
10140
  onError(error);
10493
10141
  }
10494
10142
  };
10495
- const decorated = {
10496
- async executeCommand(command, execOptions) {
10497
- const traceFile = `${traceDir}/${randomUUID4()}.strace`;
10498
- const sentinel = `__dat_trace_${randomUUID4()}__`;
10143
+ let baseDirectory;
10144
+ const absolutePath = async (path6) => {
10145
+ if (posix5.isAbsolute(path6)) return posix5.normalize(path6);
10146
+ baseDirectory ??= Promise.resolve(sandbox.run({ command: "pwd" })).then(
10147
+ ({ stdout }) => stdout.trimEnd()
10148
+ );
10149
+ return posix5.resolve(await baseDirectory, path6);
10150
+ };
10151
+ const observe = async (op, filePath) => {
10152
+ const path6 = await absolutePath(filePath);
10153
+ if (!matchesGlobs(path6, include, exclude)) return;
10154
+ await onFileChanges?.([{ op, path: path6, timestamp: Date.now() }]);
10155
+ };
10156
+ async function spawn5(spawnOptions) {
10157
+ const traceFile = `${traceDir}/${randomUUID3()}.strace`;
10158
+ const child = await sandbox.spawn({
10159
+ ...spawnOptions,
10160
+ command: buildStraceCommand(spawnOptions.command, traceFile, traceDir)
10161
+ });
10162
+ const exit = Promise.resolve(child.wait()).finally(
10163
+ () => collectSpawn(traceFile).catch(() => {
10164
+ })
10165
+ );
10166
+ exit.catch(() => {
10167
+ });
10168
+ return {
10169
+ stdout: child.stdout,
10170
+ stderr: child.stderr,
10171
+ ..."stdin" in child ? { stdin: child.stdin } : {},
10172
+ wait: () => exit,
10173
+ kill: () => child.kill()
10174
+ };
10175
+ }
10176
+ const dispose = async () => {
10177
+ await Promise.resolve(
10178
+ sandbox.run({ command: `rm -rf ${shellQuote(traceDir)}` })
10179
+ ).catch(() => {
10180
+ });
10181
+ await sandbox.dispose();
10182
+ };
10183
+ return {
10184
+ description: sandbox.description,
10185
+ async run(runOptions) {
10186
+ const traceFile = `${traceDir}/${randomUUID3()}.strace`;
10187
+ const sentinel = `__dat_trace_${randomUUID3()}__`;
10499
10188
  const wrapped = buildTracedCommand(
10500
- command,
10189
+ runOptions.command,
10501
10190
  traceFile,
10502
10191
  traceDir,
10503
10192
  sentinel
10504
10193
  );
10505
10194
  let raw;
10506
10195
  try {
10507
- raw = await innerExecute(wrapped, execOptions);
10196
+ raw = await sandbox.run({ ...runOptions, command: wrapped });
10508
10197
  } catch (error) {
10509
10198
  removeTrace(traceFile);
10510
10199
  throw error;
@@ -10515,7 +10204,7 @@ async function withStraceFileChanges(sandbox, options) {
10515
10204
  stdout,
10516
10205
  stderr: stripStraceDiagnostics(raw.stderr)
10517
10206
  };
10518
- if (execOptions?.signal?.aborted) return result;
10207
+ if (runOptions.abortSignal?.aborted) return result;
10519
10208
  const changes = trace ? parseStraceTrace(trace, { include, exclude, traceFile, traceDir }) : [];
10520
10209
  if (changes.length) {
10521
10210
  try {
@@ -10535,49 +10224,32 @@ async function withStraceFileChanges(sandbox, options) {
10535
10224
  }
10536
10225
  return result;
10537
10226
  },
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);
10227
+ spawn: spawn5,
10228
+ readFile: (readOptions) => sandbox.readFile(readOptions),
10229
+ readBinaryFile: (readOptions) => sandbox.readBinaryFile(readOptions),
10230
+ readTextFile: (readOptions) => sandbox.readTextFile(readOptions),
10231
+ stat: (statOptions) => sandbox.stat(statOptions),
10232
+ listDirectory: (listOptions) => sandbox.listDirectory(listOptions),
10233
+ deleteFile: async (deleteOptions) => {
10234
+ const deleted = await sandbox.deleteFile(deleteOptions);
10235
+ if (deleted) await observe("delete", deleteOptions.path);
10236
+ return deleted;
10551
10237
  },
10552
- dispose: async () => {
10553
- await innerExecute(`rm -rf ${shellQuote(traceDir)}`).catch(() => {
10554
- });
10555
- await sandbox.dispose();
10238
+ writeFile: async (writeOptions) => {
10239
+ await sandbox.writeFile(writeOptions);
10240
+ await observe("write", writeOptions.path);
10556
10241
  },
10557
- [Symbol.asyncDispose]() {
10558
- return this.dispose();
10559
- }
10242
+ writeBinaryFile: async (writeOptions) => {
10243
+ await sandbox.writeBinaryFile(writeOptions);
10244
+ await observe("write", writeOptions.path);
10245
+ },
10246
+ writeTextFile: async (writeOptions) => {
10247
+ await sandbox.writeTextFile(writeOptions);
10248
+ await observe("write", writeOptions.path);
10249
+ },
10250
+ dispose,
10251
+ [Symbol.asyncDispose]: dispose
10560
10252
  };
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
10253
  }
10582
10254
 
10583
10255
  // packages/context/src/lib/sandbox/gcs.ts
@@ -10591,7 +10263,7 @@ function gcs(options) {
10591
10263
  }
10592
10264
 
10593
10265
  // packages/context/src/lib/sandbox/installers/bin.ts
10594
- import { basename, posix as posix5 } from "node:path";
10266
+ import { basename, posix as posix6 } from "node:path";
10595
10267
  var NOT_FOUND_EXIT = 11;
10596
10268
  var CHMOD_FAILED_EXIT = 12;
10597
10269
  var BinInstaller = class extends Installer {
@@ -10605,13 +10277,13 @@ var BinInstaller = class extends Installer {
10605
10277
  this.binary = binary;
10606
10278
  this.options = options;
10607
10279
  this.#name = resolveName(binary, options);
10608
- this.#target = options.target ?? posix5.join("/usr/local/bin", this.#name);
10280
+ this.#target = options.target ?? posix6.join("/usr/local/bin", this.#name);
10609
10281
  this.kind = `bin:${this.#name}`;
10610
10282
  }
10611
10283
  async install(ctx) {
10612
10284
  const b = shellQuote(this.binary);
10613
10285
  const t = shellQuote(this.#target);
10614
- const dir = shellQuote(posix5.dirname(this.#target));
10286
+ const dir = shellQuote(posix6.dirname(this.#target));
10615
10287
  const result = await ctx.exec(
10616
10288
  `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
10289
  );
@@ -10876,11 +10548,13 @@ function formatVersion(version) {
10876
10548
  }
10877
10549
 
10878
10550
  // packages/context/src/lib/sandbox/microsandbox-sandbox.ts
10879
- import { randomUUID as randomUUID5 } from "node:crypto";
10551
+ import "@ai-sdk/provider-utils";
10552
+ import { randomUUID as randomUUID4 } from "node:crypto";
10553
+ import { posix as posix7 } from "node:path";
10880
10554
  var MICROSANDBOX_DEFAULT_DESTINATION = "/workspace";
10881
10555
  var MICROSANDBOX_DEFAULT_IMAGE = "bash:5.3-alpine3.24";
10882
- var MICROSANDBOX_MAX_NAME_BYTES = 128;
10883
- var COMMAND_TIMEOUT_EXIT_CODE = 124;
10556
+ var COMMAND_TIMEOUT_EXIT_CODE3 = 124;
10557
+ var NOT_FOUND_MESSAGE = /\(os error (?:2|20)\)$/;
10884
10558
  var MicrosandboxSandboxError = class extends Error {
10885
10559
  constructor(message2, cause) {
10886
10560
  super(message2);
@@ -10903,17 +10577,11 @@ var MicrosandboxCreationError = class extends MicrosandboxSandboxError {
10903
10577
  this.name = "MicrosandboxCreationError";
10904
10578
  }
10905
10579
  };
10906
- var MicrosandboxCommandError = class extends MicrosandboxSandboxError {
10907
- constructor(message2, cause) {
10908
- super(message2, cause);
10909
- this.name = "MicrosandboxCommandError";
10910
- }
10911
- };
10912
10580
  async function createMicrosandboxSandbox(options = {}) {
10913
10581
  validateMicrosandboxOptions(options);
10914
10582
  const sdk = await importMicrosandbox();
10915
10583
  const ephemeral = options.name === void 0;
10916
- const name = options.name ?? `deepagents-msb-${randomUUID5()}`;
10584
+ const name = options.name ?? `deepagents-msb-${randomUUID4()}`;
10917
10585
  const workdir = options.workdir ?? MICROSANDBOX_DEFAULT_DESTINATION;
10918
10586
  const sandboxBuilder = (replace) => {
10919
10587
  let builder = sdk.Sandbox.builder(name).image(MICROSANDBOX_DEFAULT_IMAGE).patch((patch) => patch.mkdir(workdir));
@@ -10932,30 +10600,25 @@ async function createMicrosandboxSandbox(options = {}) {
10932
10600
  await vm.fs().mkdir(workdir);
10933
10601
  await assertMicrosandboxBash(vm);
10934
10602
  } catch (error) {
10935
- await vm[Symbol.asyncDispose]().catch(() => {
10936
- });
10937
- if (ephemeral) await sdk.Sandbox.remove(name).catch(() => {
10938
- });
10603
+ await vm[Symbol.asyncDispose]();
10939
10604
  throw normalizeMicrosandboxError(error, sdk);
10940
10605
  }
10941
- const backend = createMicrosandboxMethods({
10606
+ const sandbox = microsandboxSession({
10942
10607
  sdk,
10943
10608
  vm,
10944
- name,
10945
- ephemeral,
10609
+ workdir,
10946
10610
  commandTimeout: options.commandTimeout,
10947
10611
  reconnect: ephemeral ? void 0 : () => sandboxBuilder(false).connectOrCreate()
10948
10612
  });
10949
10613
  if (options.readiness) {
10950
10614
  try {
10951
- await options.readiness(backend);
10615
+ await options.readiness(sandbox);
10952
10616
  } catch (error) {
10953
- await backend.dispose().catch(() => {
10954
- });
10617
+ await sandbox.dispose();
10955
10618
  throw error;
10956
10619
  }
10957
10620
  }
10958
- return backend;
10621
+ return sandbox;
10959
10622
  }
10960
10623
  async function importMicrosandbox() {
10961
10624
  try {
@@ -10989,22 +10652,17 @@ function normalizeMicrosandboxError(error, sdk) {
10989
10652
  return new MicrosandboxCreationError(err.message, err);
10990
10653
  }
10991
10654
  function validateMicrosandboxOptions(options) {
10992
- if (options.name !== void 0 && Buffer.byteLength(options.name, "utf-8") > MICROSANDBOX_MAX_NAME_BYTES) {
10993
- throw new MicrosandboxSandboxError(
10994
- `Microsandbox names are limited to ${MICROSANDBOX_MAX_NAME_BYTES} UTF-8 bytes.`
10995
- );
10996
- }
10997
10655
  if (options.replace && options.name === void 0) {
10998
10656
  throw new MicrosandboxSandboxError(
10999
10657
  'Microsandbox options can only include "replace" together with "name" \u2014 an unnamed sandbox is always created fresh.'
11000
10658
  );
11001
10659
  }
11002
10660
  }
11003
- function createMicrosandboxMethods(args) {
11004
- const { sdk, name, ephemeral, commandTimeout, reconnect } = args;
10661
+ function microsandboxSession(args) {
10662
+ const { sdk, workdir, commandTimeout, reconnect } = args;
11005
10663
  let vm = args.vm;
11006
10664
  let reconnecting;
11007
- const run2 = async (operation) => {
10665
+ const withVm = async (operation) => {
11008
10666
  try {
11009
10667
  return await operation(vm);
11010
10668
  } catch (error) {
@@ -11018,233 +10676,209 @@ function createMicrosandboxMethods(args) {
11018
10676
  return operation(vm);
11019
10677
  }
11020
10678
  };
11021
- const spawn5 = (command, options = {}) => {
11022
- return spawnMicrosandboxProcess(sdk, run2, command, {
11023
- ...options,
11024
- commandTimeout
11025
- });
10679
+ const withFs = (operation) => withVm((current) => operation(current.fs()));
10680
+ const isNotFound = (error) => error instanceof sdk.SandboxFsOpsError && NOT_FOUND_MESSAGE.test(error.message);
10681
+ const orNull = async (operation) => {
10682
+ try {
10683
+ return await operation();
10684
+ } catch (error) {
10685
+ if (isNotFound(error)) return null;
10686
+ throw error;
10687
+ }
11026
10688
  };
11027
- 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
11039
- ]);
11040
- if (info.signal === "SIGKILL") {
11041
- return abortedCommandResult2();
11042
- }
11043
- return { stdout, stderr, exitCode: info.code ?? 1 };
11044
- },
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)
10689
+ const resolve3 = (path6) => resolveIn(workdir, path6);
10690
+ const statAt = async (path6) => {
10691
+ const metadata = await orNull(() => withFs((fs) => fs.stat(path6)));
10692
+ if (!metadata) return null;
10693
+ const type = FILE_STAT_TYPES.find((known) => known === metadata.kind);
10694
+ if (!type) {
10695
+ throw new Error(
10696
+ `Failed to stat "${path6}": unknown type "${metadata.kind}"`
10697
+ );
10698
+ }
10699
+ return { type, size: metadata.size };
10700
+ };
10701
+ const streamable = async (path6) => {
10702
+ const stat = await statAt(path6);
10703
+ if (stat?.type === "directory") {
10704
+ throw new Error(`Cannot read "${path6}": it is a directory.`);
10705
+ }
10706
+ return stat !== null;
10707
+ };
10708
+ const withParents = async (path6, operation) => {
10709
+ try {
10710
+ return await withFs(operation);
10711
+ } catch (error) {
10712
+ if (!isNotFound(error)) throw error;
10713
+ await withFs((fs) => fs.mkdir(posix7.dirname(path6)));
10714
+ return withFs(operation);
10715
+ }
10716
+ };
10717
+ async function spawn5(options) {
10718
+ const { command, workingDirectory, env, abortSignal, stdin } = options;
10719
+ abortSignal?.throwIfAborted();
10720
+ const handle = await withVm(
10721
+ (current) => current.execStreamWith("bash", (builder) => {
10722
+ builder.args(["-lc", command]).cwd(
10723
+ workingDirectory === void 0 ? workdir : resolve3(workingDirectory)
11054
10724
  );
11055
- }
11056
- },
11057
- async exists(path6) {
11058
- try {
11059
- return await run2((vm2) => vm2.fs().exists(path6));
11060
- } catch (error) {
11061
- throw new MicrosandboxCommandError(
11062
- `Failed to check "${path6}": ${toError2(error).message}`,
11063
- toError2(error)
10725
+ if (env) builder.envs(env);
10726
+ return stdin ? builder.stdinPipe() : builder.stdinNull();
10727
+ })
10728
+ );
10729
+ const sink = stdin ? await handle.takeStdin() : null;
10730
+ const stdout = createByteReadable();
10731
+ const stderr = createByteReadable();
10732
+ let exited = false;
10733
+ let timedOut = false;
10734
+ let timer;
10735
+ const pump = async () => {
10736
+ let code;
10737
+ for await (const event of handle) {
10738
+ if (event.kind === "stdout") stdout.enqueue(event.data);
10739
+ else if (event.kind === "stderr") stderr.enqueue(event.data);
10740
+ else if (event.kind === "exited") code = event.code;
10741
+ }
10742
+ if (timedOut) {
10743
+ stderr.enqueue(new TextEncoder().encode("Command timed out"));
10744
+ return COMMAND_TIMEOUT_EXIT_CODE3;
10745
+ }
10746
+ if (code === void 0) {
10747
+ throw new MicrosandboxSandboxError(
10748
+ `The command ended without an exit code: ${command}`
11064
10749
  );
11065
10750
  }
11066
- },
11067
- async writeFiles(files) {
11068
- 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
- });
11078
- } catch (error) {
10751
+ return code;
10752
+ };
10753
+ const exitCode = pump().then(
10754
+ (code) => {
10755
+ stdout.close();
10756
+ stderr.close();
10757
+ return code;
10758
+ },
10759
+ async (error) => {
11079
10760
  const err = toError2(error);
11080
- throw new MicrosandboxCommandError(
11081
- `Failed to write files: ${err.message}`,
11082
- err
11083
- );
10761
+ stdout.error(err);
10762
+ stderr.error(err);
10763
+ await handle[Symbol.asyncDispose]();
10764
+ throw err;
11084
10765
  }
11085
- },
11086
- async dispose() {
11087
- await vm[Symbol.asyncDispose]();
11088
- if (ephemeral) {
11089
- await sdk.Sandbox.remove(name).catch(() => {
10766
+ ).finally(() => {
10767
+ exited = true;
10768
+ clearTimeout(timer);
10769
+ });
10770
+ exitCode.catch(() => {
10771
+ });
10772
+ const control = controlProcess({
10773
+ exitCode,
10774
+ // A kill after the exit fails with `execution_closed` instead of doing
10775
+ // nothing.
10776
+ kill: async () => {
10777
+ if (exited) return;
10778
+ await handle.kill().catch((error) => {
10779
+ if (!exited) throw error;
11090
10780
  });
11091
- }
11092
- },
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(() => {
10781
+ },
10782
+ abortSignal
11114
10783
  });
11115
- };
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(() => {
10784
+ if (commandTimeout) {
10785
+ timer = setTimeout(() => {
11137
10786
  timedOut = true;
11138
- startedHandle.kill().catch(() => {
10787
+ void control.kill().catch(() => {
11139
10788
  });
11140
- }, options.commandTimeout);
11141
- timeoutTimer.unref();
10789
+ }, commandTimeout).unref();
11142
10790
  }
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]();
10791
+ return {
10792
+ stdout: stdout.stream,
10793
+ stderr: stderr.stream,
10794
+ ...sink ? {
10795
+ stdin: new WritableStream({
10796
+ write: (chunk) => sink.write(chunk),
10797
+ close: () => sink.close(),
10798
+ abort: () => sink.close()
10799
+ })
10800
+ } : {},
10801
+ ...control
10802
+ };
11175
10803
  }
11176
- }
11177
- function createByteReadable() {
11178
- const ended = {
11179
- enqueue() {
11180
- },
11181
- close() {
11182
- },
11183
- error() {
11184
- }
10804
+ const readBinaryFile = async ({
10805
+ path: path6,
10806
+ abortSignal
10807
+ }) => {
10808
+ abortSignal?.throwIfAborted();
10809
+ const target = resolve3(path6);
10810
+ return orNull(() => withFs((fs) => fs.read(target)));
11185
10811
  };
11186
- let sink = ended;
11187
- const stream = new ReadableStream({
11188
- start(controller) {
11189
- sink = {
11190
- enqueue(chunk) {
11191
- if (chunk.length > 0) controller.enqueue(chunk);
11192
- },
11193
- close() {
11194
- sink = ended;
11195
- controller.close();
11196
- },
11197
- error(error) {
11198
- sink = ended;
11199
- controller.error(error);
11200
- }
11201
- };
11202
- },
11203
- cancel() {
11204
- sink = ended;
11205
- }
11206
- });
11207
- return {
11208
- stream,
11209
- enqueue: (chunk) => sink.enqueue(chunk),
11210
- close: () => sink.close(),
11211
- error: (error) => sink.error(error)
10812
+ const writeBinaryFile = async ({
10813
+ path: path6,
10814
+ content,
10815
+ abortSignal
10816
+ }) => {
10817
+ abortSignal?.throwIfAborted();
10818
+ const target = resolve3(path6);
10819
+ await withParents(target, (fs) => fs.write(target, content));
11212
10820
  };
11213
- }
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
10821
+ const dispose = async () => {
10822
+ await vm[Symbol.asyncDispose]();
11227
10823
  };
11228
- }
11229
- function abortedExitInfo2() {
11230
10824
  return {
11231
- code: null,
11232
- signal: "SIGKILL",
11233
- success: false
10825
+ description: `Commands run through bash -lc in a Microsandbox microVM, starting in ${workdir}.`,
10826
+ run: async (options) => collect(await spawn5(options)),
10827
+ spawn: spawn5,
10828
+ readBinaryFile,
10829
+ readFile: async ({ path: path6, abortSignal }) => {
10830
+ abortSignal?.throwIfAborted();
10831
+ const target = resolve3(path6);
10832
+ if (!await streamable(target)) return null;
10833
+ const stream = await orNull(() => withFs((fs) => fs.readStream(target)));
10834
+ return stream && ReadableStream.from(stream);
10835
+ },
10836
+ writeBinaryFile,
10837
+ writeFile: async ({ path: path6, content, abortSignal }) => {
10838
+ abortSignal?.throwIfAborted();
10839
+ const target = resolve3(path6);
10840
+ await using sink = await withParents(
10841
+ target,
10842
+ (fs) => fs.writeStream(target)
10843
+ );
10844
+ for await (const chunk of content) await sink.write(chunk);
10845
+ await sink.close();
10846
+ },
10847
+ ...textCalls({ readBinaryFile, writeBinaryFile }),
10848
+ stat: async ({ path: path6, abortSignal }) => {
10849
+ abortSignal?.throwIfAborted();
10850
+ return statAt(resolve3(path6));
10851
+ },
10852
+ listDirectory: async ({ path: path6, abortSignal }) => {
10853
+ abortSignal?.throwIfAborted();
10854
+ const target = resolve3(path6);
10855
+ try {
10856
+ const entries = await withFs((fs) => fs.list(target));
10857
+ return entries.map((entry) => ({
10858
+ name: posix7.basename(entry.path),
10859
+ type: entry.kind
10860
+ }));
10861
+ } catch (error) {
10862
+ if (!isNotFound(error) || await statAt(target)) throw error;
10863
+ return null;
10864
+ }
10865
+ },
10866
+ deleteFile: async ({ path: path6, abortSignal }) => {
10867
+ abortSignal?.throwIfAborted();
10868
+ try {
10869
+ await withFs((fs) => fs.remove(resolve3(path6)));
10870
+ return true;
10871
+ } catch (error) {
10872
+ if (isNotFound(error)) return false;
10873
+ throw error;
10874
+ }
10875
+ },
10876
+ dispose,
10877
+ [Symbol.asyncDispose]: dispose
11234
10878
  };
11235
10879
  }
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
10880
  function toError2(error) {
11247
- return error instanceof Error ? error : new Error(String(error));
10881
+ return Error.isError(error) ? error : new Error(String(error));
11248
10882
  }
11249
10883
 
11250
10884
  // packages/context/src/lib/sandbox/subcommand.ts
@@ -11317,54 +10951,27 @@ function buildSubcommandRepair(name, subcommands) {
11317
10951
  }
11318
10952
 
11319
10953
  // packages/context/src/lib/sandbox/virtual-sandbox.ts
10954
+ import { createJustBashSandboxSessionFromNativeSandbox } from "@ai-sdk/sandbox-just-bash";
11320
10955
  import {
11321
- Bash
10956
+ Sandbox
11322
10957
  } 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) {
10958
+ async function createVirtualSandbox({
10959
+ readiness,
10960
+ ...options
10961
+ }) {
10962
+ const native = await Sandbox.create(options);
10963
+ const dispose = () => native.stop();
10964
+ const sandbox = Object.assign(
10965
+ // The adapter pins just-bash ^2 and we run ^3 for customCommands on Sandbox.
10966
+ // Its parameter is the other copy's class, whose private members make the two
10967
+ // nominally different, so no narrowing can reach it. Goes with #4043.
10968
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- two copies of one class
10969
+ createJustBashSandboxSessionFromNativeSandbox(native),
10970
+ { dispose, [Symbol.asyncDispose]: dispose }
10971
+ );
10972
+ if (readiness) {
11366
10973
  try {
11367
- await options.readiness(sandbox);
10974
+ await readiness(sandbox);
11368
10975
  } catch (error) {
11369
10976
  await sandbox.dispose().catch(() => {
11370
10977
  });
@@ -11910,7 +11517,7 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
11910
11517
  limitClause = ` LIMIT $${paramIndex++}`;
11911
11518
  params.push(options.limit);
11912
11519
  if (options.offset !== void 0) {
11913
- limitClause += ` OFFSET $${paramIndex++}`;
11520
+ limitClause += ` OFFSET $${paramIndex}`;
11914
11521
  params.push(options.offset);
11915
11522
  }
11916
11523
  }
@@ -12389,7 +11996,7 @@ END;
12389
11996
  }
12390
11997
 
12391
11998
  // packages/context/src/lib/store/sqlserver-schema-lock.ts
12392
- async function withSqlServerSchemaLock(mssql, pool, schema, run2) {
11999
+ async function withSqlServerSchemaLock(mssql, pool, schema, run) {
12393
12000
  const holder = new mssql.Transaction(pool);
12394
12001
  await holder.begin();
12395
12002
  let result;
@@ -12410,7 +12017,7 @@ async function withSqlServerSchemaLock(mssql, pool, schema, run2) {
12410
12017
  `Could not lock the DDL of schema "${schema}": sp_getapplock returned ${recordset[0].status}.`
12411
12018
  );
12412
12019
  }
12413
- result = await run2();
12020
+ result = await run();
12414
12021
  } catch (error) {
12415
12022
  await holder.rollback().catch(() => {
12416
12023
  });
@@ -12741,7 +12348,7 @@ var SqlServerContextStore = class _SqlServerContextStore extends ContextStore {
12741
12348
  write.input(name, mssql.NVarChar, updates.title);
12742
12349
  }
12743
12350
  if (updates.metadata !== void 0) {
12744
- const name = `p${paramIndex++}`;
12351
+ const name = `p${paramIndex}`;
12745
12352
  setClauses.push(`metadata = @${name}`);
12746
12353
  write.input(name, mssql.NVarChar, JSON.stringify(updates.metadata));
12747
12354
  }
@@ -13456,11 +13063,11 @@ function asStaticWordText(word, options = {}) {
13456
13063
  function asStaticWordPartText(parts, options = {}) {
13457
13064
  const texts = [];
13458
13065
  for (const part of parts) {
13459
- const text = staticPartText(part, options);
13460
- if (text == null) {
13066
+ const text3 = staticPartText(part, options);
13067
+ if (text3 == null) {
13461
13068
  return null;
13462
13069
  }
13463
- texts.push(text);
13070
+ texts.push(text3);
13464
13071
  }
13465
13072
  return texts.join("");
13466
13073
  }
@@ -13671,7 +13278,7 @@ var PostgresNotifyChangeSource = class _PostgresNotifyChangeSource {
13671
13278
  if (delivery instanceof ChangeDelivery) yield delivery.change;
13672
13279
  }
13673
13280
  } catch (error) {
13674
- if (error instanceof Error && error.name === "AbortError") return;
13281
+ if (Error.isError(error) && error.name === "AbortError") return;
13675
13282
  throw error;
13676
13283
  } finally {
13677
13284
  this.#subscriptions -= 1;
@@ -14534,7 +14141,7 @@ var StreamManager = class {
14534
14141
  throw err;
14535
14142
  }
14536
14143
  } else {
14537
- const message2 = err instanceof Error ? err.message : String(err);
14144
+ const message2 = Error.isError(err) ? err.message : String(err);
14538
14145
  if (pw) {
14539
14146
  await pw.fail(message2);
14540
14147
  } else {
@@ -14770,7 +14377,7 @@ async function drainAvailable(controller, store, streamId, lastSeqRef, pageSize,
14770
14377
  return total;
14771
14378
  }
14772
14379
  function isAbortError(error) {
14773
- return error instanceof Error && (error.name === "AbortError" || /aborted/i.test(error.message));
14380
+ return Error.isError(error) && (error.name === "AbortError" || /aborted/i.test(error.message));
14774
14381
  }
14775
14382
  async function drain(stream, signal) {
14776
14383
  await stream.pipeTo(new WritableStream(), { signal });
@@ -14853,12 +14460,9 @@ export {
14853
14460
  ContextEngine,
14854
14461
  ContextRenderer,
14855
14462
  ContextStore,
14856
- DAYTONA_DEFAULT_DESTINATION,
14857
14463
  DEFAULT_CANCEL_POLLING,
14858
- DEFAULT_MAX_OUTPUT_LENGTH,
14859
14464
  DEFAULT_STOP_WHEN,
14860
14465
  DEFAULT_WATCH_POLLING,
14861
- DaytonaCommandError,
14862
14466
  DaytonaCreationError,
14863
14467
  DaytonaSandboxError,
14864
14468
  DockerEngine,
@@ -14877,7 +14481,6 @@ export {
14877
14481
  LOCALE_METADATA_KEY,
14878
14482
  MICROSANDBOX_DEFAULT_DESTINATION,
14879
14483
  MarkdownRenderer,
14880
- MicrosandboxCommandError,
14881
14484
  MicrosandboxCreationError,
14882
14485
  MicrosandboxNotAvailableError,
14883
14486
  MicrosandboxSandboxError,
@@ -15024,7 +14627,6 @@ export {
15024
14627
  preference,
15025
14628
  principle,
15026
14629
  quirk,
15027
- readFileContent,
15028
14630
  reasoningFramework,
15029
14631
  reminder,
15030
14632
  render,