@deepagents/context 7.6.0 → 7.7.1

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 (35) hide show
  1. package/README.md +5 -5
  2. package/dist/index.js +497 -1000
  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/sandbox/apple-container-sandbox.d.ts.map +1 -1
  7. package/dist/lib/sandbox/bash-tool.d.ts +2 -2
  8. package/dist/lib/sandbox/bash-tool.d.ts.map +1 -1
  9. package/dist/lib/sandbox/container-engine.d.ts +7 -13
  10. package/dist/lib/sandbox/container-engine.d.ts.map +1 -1
  11. package/dist/lib/sandbox/container-sandbox.d.ts +6 -3
  12. package/dist/lib/sandbox/container-sandbox.d.ts.map +1 -1
  13. package/dist/lib/sandbox/container-session.d.ts +0 -2
  14. package/dist/lib/sandbox/container-session.d.ts.map +1 -1
  15. package/dist/lib/sandbox/daytona-sandbox.d.ts +40 -49
  16. package/dist/lib/sandbox/daytona-sandbox.d.ts.map +1 -1
  17. package/dist/lib/sandbox/docker-sandbox.d.ts +21 -120
  18. package/dist/lib/sandbox/docker-sandbox.d.ts.map +1 -1
  19. package/dist/lib/sandbox/index.d.ts +0 -1
  20. package/dist/lib/sandbox/index.d.ts.map +1 -1
  21. package/dist/lib/sandbox/microsandbox-sandbox.d.ts.map +1 -1
  22. package/dist/lib/sandbox/session.d.ts +40 -0
  23. package/dist/lib/sandbox/session.d.ts.map +1 -0
  24. package/dist/lib/sandbox/strace/file-changes.d.ts +2 -2
  25. package/dist/lib/sandbox/strace/file-changes.d.ts.map +1 -1
  26. package/dist/lib/sandbox/types.d.ts +28 -71
  27. package/dist/lib/sandbox/types.d.ts.map +1 -1
  28. package/dist/lib/telemetry/file/file-telemetry.d.ts.map +1 -1
  29. package/dist/lib/telemetry/file/index.js +9 -7
  30. package/dist/lib/telemetry/file/index.js.map +2 -2
  31. package/package.json +12 -12
  32. package/dist/lib/sandbox/legacy-sandbox.d.ts +0 -8
  33. package/dist/lib/sandbox/legacy-sandbox.d.ts.map +0 -1
  34. package/dist/lib/sandbox/read-file.d.ts +0 -9
  35. package/dist/lib/sandbox/read-file.d.ts.map +0 -1
package/dist/index.js CHANGED
@@ -7177,7 +7177,7 @@ import {
7177
7177
  import { once as once2 } from "node:events";
7178
7178
  import { writeFile } from "node:fs/promises";
7179
7179
  import { join } from "node:path";
7180
- import { Readable, Writable } from "node:stream";
7180
+ import { Writable } from "node:stream";
7181
7181
  import z10 from "zod";
7182
7182
 
7183
7183
  // packages/context/src/lib/sandbox/container-sandbox-errors.ts
@@ -7274,13 +7274,113 @@ import { existsSync, readFileSync } from "node:fs";
7274
7274
  import { setTimeout as setTimeout2 } from "node:timers/promises";
7275
7275
 
7276
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";
7281
+
7282
+ // packages/context/src/lib/sandbox/session.ts
7277
7283
  import {
7278
7284
  extractLines
7279
7285
  } from "@ai-sdk/provider-utils";
7280
- import { randomUUID } from "node:crypto";
7281
7286
  import { posix } from "node:path";
7282
7287
  import { text } from "node:stream/consumers";
7283
- import { setTimeout as delay } from "node:timers/promises";
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
+ }) {
7301
+ return {
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
+ })
7315
+ };
7316
+ }
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));
7332
+ return {
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
+ }
7371
+ };
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)
7382
+ };
7383
+ }
7284
7384
 
7285
7385
  // packages/context/src/lib/sandbox/shell-quote.ts
7286
7386
  function shellQuote(s) {
@@ -7301,12 +7401,6 @@ var DIRECTORY_ENTRY_TYPES = [
7301
7401
  "symlink",
7302
7402
  "other"
7303
7403
  ];
7304
- function bufferEncoding(encoding = "utf-8") {
7305
- if (!Buffer.isEncoding(encoding)) {
7306
- throw new TypeError(`Unknown encoding: ${encoding}`);
7307
- }
7308
- return encoding;
7309
- }
7310
7404
  var EXIT_MISSING_FUNCTION = `
7311
7405
  exit_missing() {
7312
7406
  error=$(LC_ALL=C; : 2>&1 < "$1")
@@ -7448,8 +7542,8 @@ async function deleteFileOverExec(container, path6, signal) {
7448
7542
  }
7449
7543
  async function collectOutput(process2) {
7450
7544
  const [stdout, stderr, exitCode] = await Promise.all([
7451
- text(process2.stdout),
7452
- text(process2.stderr),
7545
+ text2(process2.stdout),
7546
+ text2(process2.stderr),
7453
7547
  process2.exitCode
7454
7548
  ]);
7455
7549
  return { stdout, stderr, exitCode };
@@ -7525,11 +7619,10 @@ function containerSession(container, errors) {
7525
7619
  validateEnv(env, errors);
7526
7620
  return {
7527
7621
  env,
7528
- // Joined, not normalized, so that `link/..` follows the link.
7529
- workingDirectory: workingDirectory === void 0 || posix.isAbsolute(workingDirectory) ? workingDirectory : `${container.workdir}/${workingDirectory}`
7622
+ workingDirectory: workingDirectory === void 0 ? void 0 : resolveIn(container.workdir, workingDirectory)
7530
7623
  };
7531
7624
  };
7532
- const start = async (options) => {
7625
+ async function spawn5(options) {
7533
7626
  const { command, abortSignal, stdin } = options;
7534
7627
  abortSignal?.throwIfAborted();
7535
7628
  const controlPath = `/dev/shm/deepagents-exec-${randomUUID()}.pid`;
@@ -7541,30 +7634,16 @@ function containerSession(container, errors) {
7541
7634
  ],
7542
7635
  { ...scope(options), stdin }
7543
7636
  );
7544
- let termination;
7545
- const kill = () => termination ??= terminate(container, controlPath, process2.exitCode);
7546
- const onAbort = () => {
7547
- void kill().catch(() => {
7548
- });
7549
- };
7550
- if (abortSignal?.aborted) onAbort();
7551
- else abortSignal?.addEventListener("abort", onAbort, { once: true });
7552
- void process2.exitCode.catch(() => {
7553
- }).finally(() => abortSignal?.removeEventListener("abort", onAbort));
7554
- return { process: process2, kill };
7555
- };
7556
- async function spawn5(options) {
7557
- const { process: process2, kill } = await start(options);
7637
+ const control = controlProcess({
7638
+ exitCode: process2.exitCode,
7639
+ kill: () => terminate(container, controlPath, process2.exitCode),
7640
+ abortSignal
7641
+ });
7558
7642
  return {
7559
7643
  stdout: process2.stdout,
7560
7644
  stderr: process2.stderr,
7561
7645
  ...process2.stdin ? { stdin: process2.stdin } : {},
7562
- wait: async () => ({
7563
- exitCode: await process2.exitCode.finally(
7564
- () => options.abortSignal?.throwIfAborted()
7565
- )
7566
- }),
7567
- kill
7646
+ ...control
7568
7647
  };
7569
7648
  }
7570
7649
  const readBinaryFile = async ({
@@ -7590,10 +7669,7 @@ function containerSession(container, errors) {
7590
7669
  if (!abortSignal && !container.commandTimeout) {
7591
7670
  return container.exec(["bash", "-lc", command], scope(options));
7592
7671
  }
7593
- const { process: process2 } = await start(options);
7594
- return collectOutput(process2).finally(
7595
- () => abortSignal?.throwIfAborted()
7596
- );
7672
+ return collect(await spawn5(options));
7597
7673
  },
7598
7674
  spawn: spawn5,
7599
7675
  readBinaryFile,
@@ -7601,24 +7677,12 @@ function containerSession(container, errors) {
7601
7677
  const bytes = await readBinaryFile(options);
7602
7678
  return bytes && ReadableStream.from([bytes]);
7603
7679
  },
7604
- readTextFile: async ({ startLine, endLine, encoding, ...options }) => {
7605
- const bytes = await readBinaryFile(options);
7606
- if (!bytes) return null;
7607
- return extractLines({
7608
- text: Buffer.from(bytes).toString(bufferEncoding(encoding)),
7609
- startLine,
7610
- endLine
7611
- });
7612
- },
7613
7680
  writeBinaryFile,
7614
7681
  writeFile: async ({ content, ...options }) => writeBinaryFile({
7615
7682
  ...options,
7616
7683
  content: await new Response(content).bytes()
7617
7684
  }),
7618
- writeTextFile: ({ content, encoding, ...options }) => writeBinaryFile({
7619
- ...options,
7620
- content: Buffer.from(content, bufferEncoding(encoding))
7621
- }),
7685
+ ...textCalls({ readBinaryFile, writeBinaryFile }),
7622
7686
  stat: async ({ path: path6, abortSignal }) => {
7623
7687
  abortSignal?.throwIfAborted();
7624
7688
  return container.stat(path6, abortSignal);
@@ -7894,7 +7958,7 @@ var ContainerSandboxStrategy = class {
7894
7958
  await this.engine.dispose();
7895
7959
  throw error;
7896
7960
  }
7897
- const sandbox = this.createSandboxMethods(acquired.container);
7961
+ const sandbox = this.createSandboxMethods(acquired);
7898
7962
  if (this.opts.readiness) {
7899
7963
  try {
7900
7964
  await this.opts.readiness(sandbox);
@@ -8037,7 +8101,7 @@ var ContainerSandboxStrategy = class {
8037
8101
  this.createdVolumes.delete(volume);
8038
8102
  }
8039
8103
  }
8040
- /** Ends the sandbox's hold on its container: stops it, by default. */
8104
+ /** Ends a container that this sandbox created: stops it, by default. */
8041
8105
  release(container) {
8042
8106
  return container.stop();
8043
8107
  }
@@ -8050,11 +8114,14 @@ var ContainerSandboxStrategy = class {
8050
8114
  container.name
8051
8115
  );
8052
8116
  }
8053
- createSandboxMethods(container) {
8117
+ createSandboxMethods({
8118
+ container,
8119
+ attached
8120
+ }) {
8054
8121
  let disposal;
8055
8122
  const dispose = async () => {
8056
8123
  try {
8057
- await this.release(container);
8124
+ if (!attached) await this.release(container);
8058
8125
  await this.cleanupCreatedVolumes();
8059
8126
  } finally {
8060
8127
  await this.engine.dispose();
@@ -8177,10 +8244,17 @@ function isMissing(message2) {
8177
8244
  function isNameConflict(message2) {
8178
8245
  return /already exists/i.test(message2);
8179
8246
  }
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;
8253
+ }
8180
8254
  function engineProcess(child) {
8181
8255
  return {
8182
- stdout: Readable.toWeb(child.stdout),
8183
- stderr: Readable.toWeb(child.stderr),
8256
+ stdout: drained(child.stdout),
8257
+ stderr: drained(child.stderr),
8184
8258
  exitCode: once2(child, "close").then(([code]) => code ?? 1)
8185
8259
  };
8186
8260
  }
@@ -8266,18 +8340,14 @@ var appleEngine = {
8266
8340
  bindMountsOnClient: true,
8267
8341
  defaultImage: "docker.io/library/bash:5.3-alpine3.24",
8268
8342
  runArgs(image, containerId, opts) {
8269
- const { memory = "1024M", cpus = 2 } = opts.resources ?? {};
8270
- const args = [
8271
- "run",
8272
- "--detach",
8273
- "--rm",
8274
- "--name",
8275
- containerId,
8276
- "--memory",
8277
- memory,
8278
- "--cpus",
8279
- String(cpus)
8280
- ];
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
+ }
8281
8351
  if (opts.arch) {
8282
8352
  args.push("--arch", opts.arch);
8283
8353
  }
@@ -8442,28 +8512,14 @@ var appleEngine = {
8442
8512
  };
8443
8513
  async function runAppleBuild(args, showBuildLogs) {
8444
8514
  try {
8445
- if (showBuildLogs) {
8446
- await runStreamed(CLI, args);
8447
- } else {
8448
- await spawn(CLI, args);
8449
- }
8515
+ await spawn(CLI, args, showBuildLogs ? { stdio: "inherit" } : {});
8450
8516
  } catch (error) {
8451
- throw new AppleContainerImageBuildError(getCliErrorMessage(error));
8452
- }
8453
- }
8454
- function runStreamed(command, args) {
8455
- return new Promise((resolve3, reject) => {
8456
- const child = childSpawn(command, args, { stdio: "inherit" });
8457
- child.once("error", reject);
8458
- child.once(
8459
- "exit",
8460
- (code) => code === 0 ? resolve3() : reject(
8461
- new Error(
8462
- `${command} build exited with code ${code} (see build output above)`
8463
- )
8517
+ throw new AppleContainerImageBuildError(
8518
+ getCliErrorMessage(
8519
+ error instanceof SubprocessError ? error.cause ?? error : error
8464
8520
  )
8465
8521
  );
8466
- });
8522
+ }
8467
8523
  }
8468
8524
  async function createAppleContainerSandbox(options = {}) {
8469
8525
  if (isAppleContainerfileOptions(options)) {
@@ -8497,108 +8553,6 @@ import * as path4 from "node:path";
8497
8553
  import z12 from "zod";
8498
8554
  import { withHostOnlyToolMetadata as withHostOnlyToolMetadata2 } from "@deepagents/agent";
8499
8555
 
8500
- // packages/context/src/lib/sandbox/legacy-sandbox.ts
8501
- import {
8502
- extractLines as extractLines2
8503
- } from "@ai-sdk/provider-utils";
8504
- function commandInScope({
8505
- command,
8506
- workingDirectory,
8507
- env
8508
- }) {
8509
- const exports = Object.entries(env ?? {}).map(
8510
- ([name, value]) => `export ${name}=${shellQuote(value)}; `
8511
- );
8512
- const directory = workingDirectory === void 0 ? "" : `cd -- ${shellQuote(workingDirectory)} && `;
8513
- return `${exports.join("")}${directory}${command}`;
8514
- }
8515
- function unported(method) {
8516
- throw new Error(`${method} is not available until this backend is ported.`);
8517
- }
8518
- function fromLegacySandbox(legacy) {
8519
- const readBinaryFile = async ({
8520
- path: path6
8521
- }) => {
8522
- try {
8523
- return await legacy.readFile(path6, { encoding: "binary" });
8524
- } catch (error) {
8525
- if (await legacy.exists(path6)) throw error;
8526
- return null;
8527
- }
8528
- };
8529
- const writeBinaryFile = ({
8530
- path: path6,
8531
- content
8532
- }) => legacy.writeFiles([{ path: path6, content: Buffer.from(content) }]);
8533
- async function spawn5(options) {
8534
- if (options.stdin) throw new Error("This sandbox has no writable stdin.");
8535
- if (!legacy.spawn) throw new Error("This sandbox cannot spawn processes.");
8536
- const killer = new AbortController();
8537
- const { abortSignal } = options;
8538
- const child = await legacy.spawn(commandInScope(options), {
8539
- signal: abortSignal ? AbortSignal.any([abortSignal, killer.signal]) : killer.signal
8540
- });
8541
- return {
8542
- stdout: child.stdout,
8543
- stderr: child.stderr,
8544
- wait: async () => {
8545
- const { code } = await child.exit;
8546
- abortSignal?.throwIfAborted();
8547
- return { exitCode: code ?? 1 };
8548
- },
8549
- kill: async () => killer.abort()
8550
- };
8551
- }
8552
- return {
8553
- description: "Commands run through bash -lc.",
8554
- run: (options) => legacy.executeCommand(
8555
- commandInScope(options),
8556
- options.abortSignal ? { signal: options.abortSignal } : void 0
8557
- ),
8558
- spawn: spawn5,
8559
- readBinaryFile,
8560
- readFile: async (options) => {
8561
- const bytes = await readBinaryFile(options);
8562
- return bytes && new Blob([Buffer.from(bytes)]).stream();
8563
- },
8564
- readTextFile: async ({ startLine, endLine, encoding, ...options }) => {
8565
- const bytes = await readBinaryFile(options);
8566
- if (!bytes) return null;
8567
- return extractLines2({
8568
- text: Buffer.from(bytes).toString(bufferEncoding(encoding)),
8569
- startLine,
8570
- endLine
8571
- });
8572
- },
8573
- writeBinaryFile,
8574
- writeFile: async ({ path: path6, content }) => writeBinaryFile({
8575
- path: path6,
8576
- content: new Uint8Array(await new Response(content).arrayBuffer())
8577
- }),
8578
- writeTextFile: ({ path: path6, content, encoding }) => writeBinaryFile({
8579
- path: path6,
8580
- content: Buffer.from(content, bufferEncoding(encoding))
8581
- }),
8582
- stat: async ({ path: path6 }) => {
8583
- const quoted = shellQuote(path6);
8584
- const { stdout } = await legacy.executeCommand(
8585
- `if [ -d ${quoted} ]; then echo directory 0; elif [ -f ${quoted} ]; then echo file $(wc -c < ${quoted}); elif [ -e ${quoted} ]; then echo other 0; fi`
8586
- );
8587
- const [printed, size] = stdout.trim().split(" ");
8588
- if (!printed) return null;
8589
- const type = FILE_STAT_TYPES.find((known) => known === printed);
8590
- if (!type) {
8591
- throw new Error(`Failed to stat "${path6}": unknown type "${printed}"`);
8592
- }
8593
- return { type, size: Number(size) };
8594
- },
8595
- listDirectory: () => unported("listDirectory"),
8596
- deleteFile: () => unported("deleteFile"),
8597
- dispose: () => legacy.dispose(),
8598
- [Symbol.asyncDispose]: () => legacy.dispose()
8599
- };
8600
- }
8601
-
8602
8556
  // packages/context/src/lib/sandbox/read-file-tool/index.ts
8603
8557
  import { tool as tool2 } from "ai";
8604
8558
  import path3 from "node:path";
@@ -8861,8 +8815,7 @@ function createBashDescription(options) {
8861
8815
  ].filter(Boolean).join("\n\n");
8862
8816
  }
8863
8817
  async function createBashTool(options) {
8864
- const { workingDirectory } = options;
8865
- const sandbox = "run" in options.sandbox ? options.sandbox : fromLegacySandbox(options.sandbox);
8818
+ const { workingDirectory, sandbox } = options;
8866
8819
  const initialFiles = await listInitialFiles(options);
8867
8820
  if (workingDirectory !== void 0) {
8868
8821
  const created = await sandbox.run({
@@ -9068,19 +9021,17 @@ function mapToRealPath(fs, cwd) {
9068
9021
  }
9069
9022
 
9070
9023
  // packages/context/src/lib/sandbox/daytona-sandbox.ts
9071
- import { randomUUID as randomUUID3 } from "node:crypto";
9024
+ import "@ai-sdk/provider-utils";
9025
+ import { constants } from "node:os";
9072
9026
  import { setTimeout as setTimeout3 } from "node:timers/promises";
9073
-
9074
- // packages/context/src/lib/sandbox/read-file.ts
9075
- var decoder = new TextDecoder();
9076
- function readFileContent(bytes, options) {
9077
- return options?.encoding === "binary" ? bytes : decoder.decode(bytes);
9078
- }
9079
-
9080
- // packages/context/src/lib/sandbox/daytona-sandbox.ts
9081
- var DAYTONA_DEFAULT_DESTINATION = "/home/daytona";
9082
- var DAYTONA_EXIT_POLL_INTERVAL_MS = 250;
9083
- 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;
9084
9035
  var DaytonaSandboxError = class extends Error {
9085
9036
  constructor(message2, cause) {
9086
9037
  super(message2);
@@ -9094,53 +9045,51 @@ var DaytonaCreationError = class extends DaytonaSandboxError {
9094
9045
  this.name = "DaytonaCreationError";
9095
9046
  }
9096
9047
  };
9097
- var DaytonaCommandError = class extends DaytonaSandboxError {
9098
- constructor(message2, cause) {
9099
- super(message2, cause);
9100
- this.name = "DaytonaCommandError";
9101
- }
9102
- };
9103
9048
  async function createDaytonaSandbox(client, options = {}) {
9104
- const target = validateDaytonaOptions(options);
9105
- const sdk = await import("@daytona/sdk");
9106
- 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;
9107
9053
  try {
9108
- if ("sandboxId" in target) {
9109
- sandbox = await client.get(target.sandboxId);
9110
- await startIfStopped(sandbox, options);
9111
- } else {
9112
- sandbox = await acquireReusedSandbox(client, target.name, options, sdk);
9113
- }
9054
+ session = daytonaSession({
9055
+ sdk,
9056
+ sandbox,
9057
+ created,
9058
+ workdir: await startingDirectory(sdk, sandbox),
9059
+ commandTimeout
9060
+ });
9114
9061
  } catch (error) {
9115
- throw normalizeDaytonaError(error, sdk);
9062
+ if (created) await sandbox.delete();
9063
+ throw error;
9116
9064
  }
9117
- await assertDaytonaBash(sandbox, options.commandTimeout);
9118
- const backend = createDaytonaSandboxMethods({
9119
- sdk,
9120
- sandbox,
9121
- commandTimeout: options.commandTimeout
9122
- });
9123
- if (options.readiness) {
9065
+ if (readiness) {
9124
9066
  try {
9125
- await options.readiness(backend);
9067
+ await readiness(session);
9126
9068
  } catch (error) {
9127
- await backend.dispose().catch(() => {
9128
- });
9069
+ await session.dispose();
9129
9070
  throw error;
9130
9071
  }
9131
9072
  }
9132
- return backend;
9073
+ return session;
9133
9074
  }
9134
- async function assertDaytonaBash(sandbox, commandTimeout) {
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 };
9082
+ }
9083
+ async function startingDirectory(sdk, sandbox) {
9135
9084
  try {
9136
- const result = await sandbox.process.executeCommand(
9137
- "bash -lc ':'",
9138
- void 0,
9139
- void 0,
9140
- commandTimeout
9085
+ const result = await whenGatewayReady(
9086
+ sdk,
9087
+ () => sandbox.process.run('printf %s "$PWD"', { shell: "bash", login: true })
9141
9088
  );
9142
- if (result.exitCode === void 0 || result.exitCode === 0) return;
9143
- 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);
9144
9093
  } catch (error) {
9145
9094
  const err = toError(error);
9146
9095
  throw new DaytonaCreationError(
@@ -9149,408 +9098,233 @@ async function assertDaytonaBash(sandbox, commandTimeout) {
9149
9098
  );
9150
9099
  }
9151
9100
  }
9152
- var UNRECOVERABLE_SANDBOX_STATES = /* @__PURE__ */ new Set([
9153
- "error",
9154
- "build_failed",
9155
- "destroyed"
9156
- ]);
9157
- async function acquireReusedSandbox(client, name, options, sdk) {
9158
- let existing;
9159
- try {
9160
- existing = await client.get(name);
9161
- } catch (error) {
9162
- if (error instanceof sdk.DaytonaNotFoundError) {
9163
- return createSandbox(client, options);
9164
- }
9165
- throw error;
9166
- }
9167
- if (existing.state && UNRECOVERABLE_SANDBOX_STATES.has(existing.state)) {
9168
- await deleteSandboxQuietly(existing, options);
9169
- return createSandbox(client, options);
9170
- }
9171
- await startIfStopped(existing, options);
9172
- return existing;
9173
- }
9174
- async function deleteSandboxQuietly(sandbox, options) {
9175
- try {
9176
- await sandbox.delete(options.deleteTimeout);
9177
- } catch {
9178
- }
9179
- }
9180
- async function startIfStopped(sandbox, options) {
9181
- if (sandbox.state && sandbox.state !== "started") {
9182
- await sandbox.start(options.startTimeout ?? options.createTimeout);
9183
- }
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
+ );
9184
9132
  }
9185
- function normalizeDaytonaError(error, sdk) {
9186
- const err = toError(error);
9187
- if (err instanceof sdk.DaytonaError) {
9188
- return err;
9189
- }
9190
- return new DaytonaCreationError(err.message, err);
9191
- }
9192
- function createSandbox(client, options) {
9193
- const base = compactObject({
9194
- name: options.name,
9195
- user: options.user,
9196
- language: options.language,
9197
- envVars: options.envVars,
9198
- labels: options.labels,
9199
- public: options.public,
9200
- autoStopInterval: options.autoStopInterval,
9201
- autoArchiveInterval: options.autoArchiveInterval,
9202
- autoDeleteInterval: options.autoDeleteInterval,
9203
- volumes: options.volumes,
9204
- networkBlockAll: options.networkBlockAll,
9205
- networkAllowList: options.networkAllowList,
9206
- ephemeral: options.ephemeral
9207
- });
9208
- if (options.image !== void 0) {
9209
- const params2 = compactObject({
9210
- ...base,
9211
- image: options.image,
9212
- resources: options.resources
9213
- });
9214
- return client.create(params2, {
9215
- timeout: options.createTimeout,
9216
- onSnapshotCreateLogs: options.onSnapshotCreateLogs
9217
- });
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";
9218
9143
  }
9219
- const params = compactObject({
9220
- ...base,
9221
- snapshot: options.snapshot
9222
- });
9223
- return client.create(params, { timeout: options.createTimeout });
9224
9144
  }
9225
- function validateDaytonaOptions(options) {
9226
- if (options.image && options.snapshot) {
9227
- throw new DaytonaSandboxError(
9228
- 'Daytona sandbox options cannot include both "image" and "snapshot". Choose one environment source.'
9229
- );
9230
- }
9231
- if (options.resources && !options.image) {
9232
- throw new DaytonaSandboxError(
9233
- 'Daytona sandbox options can only include "resources" when creating from "image". The Daytona SDK does not apply resources during default or snapshot creation.'
9234
- );
9235
- }
9236
- if (options.sandboxId === void 0) {
9237
- if (options.name === void 0) {
9238
- throw new DaytonaSandboxError(
9239
- 'Daytona sandbox options require "name" (get-or-create) or "sandboxId" (attach). An unnamed sandbox cannot be reclaimed, since dispose() does not delete it.'
9240
- );
9241
- }
9242
- return { name: options.name };
9243
- }
9244
- if (!options.sandboxId) {
9245
- return { sandboxId: options.sandboxId };
9246
- }
9247
- const creationOnlyFields = [
9248
- "name",
9249
- "user",
9250
- "snapshot",
9251
- "image",
9252
- "language",
9253
- "envVars",
9254
- "labels",
9255
- "public",
9256
- "resources",
9257
- "volumes",
9258
- "networkAllowList",
9259
- "networkBlockAll",
9260
- "autoStopInterval",
9261
- "autoArchiveInterval",
9262
- "autoDeleteInterval",
9263
- "ephemeral",
9264
- "onSnapshotCreateLogs"
9265
- ];
9266
- const present = creationOnlyFields.filter((field) => {
9267
- return options[field] !== void 0;
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) } : {}
9268
9157
  });
9269
- if (present.length > 0) {
9270
- throw new DaytonaSandboxError(
9271
- `Daytona sandbox options cannot combine "sandboxId" with creation options: ${present.join(", ")}`
9272
- );
9273
- }
9274
- return { sandboxId: options.sandboxId };
9275
- }
9276
- function createDaytonaSandboxMethods(args) {
9277
- const { sdk, sandbox, commandTimeout } = args;
9278
- const executeCommand = async (command, options) => {
9279
- if (options?.signal?.aborted) {
9280
- return abortedCommandResult();
9281
- }
9282
- let aborted = false;
9283
- const abort = () => {
9284
- aborted = true;
9285
- };
9286
- options?.signal?.addEventListener("abort", abort, { once: true });
9158
+ const isMissing2 = (error) => error instanceof sdk.FileNotFoundError || error instanceof sdk.BadRequestError && NOT_A_DIRECTORY.test(error.message);
9159
+ const orNull = async (operation) => {
9287
9160
  try {
9288
- if (aborted || options?.signal?.aborted) {
9289
- return abortedCommandResult();
9290
- }
9291
- const response = await sandbox.process.executeCommand(
9292
- `bash -lc ${shellQuote(command)}`,
9293
- void 0,
9294
- void 0,
9295
- commandTimeout
9296
- );
9297
- if (aborted) return abortedCommandResult();
9161
+ return await operation();
9162
+ } catch (error) {
9163
+ if (isMissing2(error)) return null;
9164
+ throw error;
9165
+ }
9166
+ };
9167
+ const execRunner = {
9168
+ exec: async (argv) => {
9169
+ const result = await sandbox.process.run({ argv });
9298
9170
  return {
9299
- stdout: response.result ?? response.artifacts?.stdout ?? "",
9300
- stderr: "",
9301
- exitCode: response.exitCode ?? 0
9171
+ stdout: result.stdout,
9172
+ stderr: result.stderr,
9173
+ exitCode: exitCodeOf(result)
9302
9174
  };
9303
- } catch (error) {
9304
- if (aborted) return abortedCommandResult();
9305
- return { stdout: "", stderr: toError(error).message, exitCode: 1 };
9306
- } finally {
9307
- options?.signal?.removeEventListener("abort", abort);
9308
9175
  }
9309
9176
  };
9310
- return {
9311
- executeCommand,
9312
- async spawn(command, options) {
9313
- const sessionId = `deepagents-spawn-${randomUUID3()}`;
9314
- const stdout = createTextReadable();
9315
- const stderr = createTextReadable();
9316
- const signal = options?.signal;
9317
- const sessionCommand = buildSessionCommand(command, { ...options });
9318
- const exit = (async () => {
9319
- let sessionCreated = false;
9320
- let aborted = signal?.aborted === true;
9321
- const { promise: abortPromise, resolve: resolveAbort } = Promise.withResolvers();
9322
- const abort = () => {
9323
- aborted = true;
9324
- resolveAbort("aborted");
9325
- if (sessionCreated) {
9326
- sandbox.process.deleteSession(sessionId).catch(() => {
9327
- });
9328
- }
9329
- };
9330
- if (signal) {
9331
- if (signal.aborted) abort();
9332
- else signal.addEventListener("abort", abort, { once: true });
9333
- }
9334
- try {
9335
- await sandbox.process.createSession(sessionId);
9336
- sessionCreated = true;
9337
- if (aborted) return abortedExitInfo();
9338
- const response = await sandbox.process.executeSessionCommand(
9339
- sessionId,
9340
- {
9341
- command: sessionCommand,
9342
- runAsync: true,
9343
- suppressInputEcho: true
9344
- },
9345
- commandTimeout
9346
- );
9347
- const commandId = response.cmdId;
9348
- if (!commandId) {
9349
- throw new DaytonaCommandError(
9350
- "Daytona did not return a command id for the spawned session command."
9351
- );
9352
- }
9353
- if (aborted) return abortedExitInfo();
9354
- const logsTask = sandbox.process.getSessionCommandLogs(
9355
- sessionId,
9356
- commandId,
9357
- stdout.enqueue,
9358
- stderr.enqueue
9359
- );
9360
- logsTask.catch(() => {
9361
- });
9362
- const winner = await Promise.race([logsTask, abortPromise]);
9363
- if (winner === "aborted") {
9364
- await sandbox.process.deleteSession(sessionId).catch(() => {
9365
- });
9366
- return abortedExitInfo();
9367
- }
9368
- const timeoutMs = commandTimeout === void 0 ? DAYTONA_EXIT_POLL_TIMEOUT_MS : Math.max(commandTimeout * 1e3, DAYTONA_EXIT_POLL_TIMEOUT_MS);
9369
- const deadline = Date.now() + timeoutMs;
9370
- while (true) {
9371
- if (aborted)
9372
- throw new DaytonaCommandError("Daytona command aborted.");
9373
- const info = await sandbox.process.getSessionCommand(
9374
- sessionId,
9375
- commandId
9376
- );
9377
- if (typeof info.exitCode === "number") {
9378
- return {
9379
- code: info.exitCode,
9380
- signal: null,
9381
- success: info.exitCode === 0
9382
- };
9383
- }
9384
- if (Date.now() >= deadline) {
9385
- throw new DaytonaCommandError(
9386
- `Daytona session command "${commandId}" logs closed before an exit code became available.`
9387
- );
9388
- }
9389
- await setTimeout3(DAYTONA_EXIT_POLL_INTERVAL_MS);
9390
- }
9391
- } catch (error) {
9392
- if (aborted) return abortedExitInfo();
9393
- const err = toError(error);
9394
- stdout.error(err);
9395
- stderr.error(err);
9396
- throw err;
9397
- } finally {
9398
- if (signal) {
9399
- signal.removeEventListener("abort", abort);
9400
- }
9401
- stdout.close();
9402
- stderr.close();
9403
- if (sessionCreated) {
9404
- await sandbox.process.deleteSession(sessionId).catch(() => {
9405
- });
9406
- }
9407
- }
9408
- })();
9409
- return { stdout: stdout.stream, stderr: stderr.stream, exit };
9410
- },
9411
- async readFile(path6, options) {
9412
- try {
9413
- const bytes = await sandbox.fs.downloadFile(path6);
9414
- return readFileContent(bytes, options);
9415
- } catch (error) {
9416
- throw new DaytonaCommandError(
9417
- `Failed to read file "${path6}": ${toError(error).message}`,
9418
- toError(error)
9419
- );
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
+ }
9203
+ };
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));
9420
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);
9258
+ try {
9259
+ await sandbox.fs.writeBytes(target, content);
9260
+ } catch (error) {
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;
9267
+ }
9268
+ };
9269
+ let disposing;
9270
+ const dispose = () => disposing ??= created ? sandbox.delete() : Promise.resolve();
9271
+ return {
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
+ };
9421
9286
  },
9422
- async exists(path6) {
9287
+ spawn: spawn5,
9288
+ readBinaryFile,
9289
+ readFile: async (options) => {
9290
+ const bytes = await readBinaryFile(options);
9291
+ return bytes && ReadableStream.from([bytes]);
9292
+ },
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);
9423
9303
  try {
9424
- await sandbox.fs.getFileDetails(path6);
9425
- 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
+ }));
9426
9309
  } catch (error) {
9427
- if (error instanceof sdk.DaytonaNotFoundError) return false;
9428
- throw new DaytonaCommandError(
9429
- `Failed to check "${path6}": ${toError(error).message}`,
9430
- toError(error)
9431
- );
9310
+ if (!isMissing2(error) || await stat({ path: target })) throw error;
9311
+ return null;
9432
9312
  }
9433
9313
  },
9434
- async writeFiles(files) {
9314
+ deleteFile: async ({ path: path6, abortSignal }) => {
9315
+ abortSignal?.throwIfAborted();
9435
9316
  try {
9436
- for (const dir of uniqueParentDirectories(files.map((f) => f.path))) {
9437
- const result = await executeCommand(`mkdir -p ${shellQuote(dir)}`);
9438
- if (result.exitCode !== 0) {
9439
- throw new DaytonaCommandError(
9440
- `Failed to create directory "${dir}": ${result.stderr}`
9441
- );
9442
- }
9443
- }
9444
- await sandbox.fs.uploadFiles(
9445
- files.map((file) => ({
9446
- source: Buffer.from(file.content),
9447
- destination: file.path
9448
- }))
9449
- );
9317
+ await sandbox.fs.remove(resolve3(path6));
9318
+ return true;
9450
9319
  } catch (error) {
9451
- if (error instanceof DaytonaSandboxError) throw error;
9452
- const err = toError(error);
9453
- throw new DaytonaCommandError(
9454
- `Failed to write files: ${err.message}`,
9455
- err
9456
- );
9320
+ if (isMissing2(error)) return false;
9321
+ throw error;
9457
9322
  }
9458
9323
  },
9459
- async dispose() {
9460
- },
9461
- [Symbol.asyncDispose]() {
9462
- return this.dispose();
9463
- }
9464
- };
9465
- }
9466
- function createTextReadable() {
9467
- const encoder = new TextEncoder();
9468
- const ended = {
9469
- enqueue() {
9470
- },
9471
- close() {
9472
- },
9473
- error() {
9474
- }
9475
- };
9476
- let sink = ended;
9477
- const stream = new ReadableStream({
9478
- start(controller) {
9479
- sink = {
9480
- enqueue(chunk) {
9481
- if (chunk) controller.enqueue(encoder.encode(chunk));
9482
- },
9483
- close() {
9484
- sink = ended;
9485
- controller.close();
9486
- },
9487
- error(error) {
9488
- sink = ended;
9489
- controller.error(error);
9490
- }
9491
- };
9492
- }
9493
- });
9494
- return {
9495
- stream,
9496
- enqueue: (chunk) => sink.enqueue(chunk),
9497
- close: () => sink.close(),
9498
- error: (error) => sink.error(error)
9499
- };
9500
- }
9501
- function buildSessionCommand(command, options) {
9502
- const cwdPrefix = options.cwd ? `cd ${shellQuote(options.cwd)} && ` : "";
9503
- const env = options.env ?? {};
9504
- const entries = Object.entries(env);
9505
- if (entries.length === 0) {
9506
- return `bash -lc ${shellQuote(`${cwdPrefix}${command}`)}`;
9507
- }
9508
- for (const [key] of entries) {
9509
- validateEnvKey(key);
9510
- }
9511
- const exports = entries.map(([key, value]) => `export ${key}=${shellQuote(value)}`).join("; ");
9512
- return `bash -lc ${shellQuote(`${exports}; ${cwdPrefix}${command}`)}`;
9513
- }
9514
- function validateEnvKey(key) {
9515
- if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) {
9516
- throw new DaytonaSandboxError(
9517
- `Invalid environment variable key: "${key}". Use shell-compatible environment variable names.`
9518
- );
9519
- }
9520
- }
9521
- function abortedCommandResult() {
9522
- return {
9523
- stdout: "",
9524
- stderr: "Command aborted",
9525
- exitCode: 1
9526
- };
9527
- }
9528
- function abortedExitInfo() {
9529
- return {
9530
- code: null,
9531
- signal: "SIGKILL",
9532
- success: false
9324
+ dispose,
9325
+ [Symbol.asyncDispose]: dispose
9533
9326
  };
9534
9327
  }
9535
- function uniqueParentDirectories(paths) {
9536
- const dirs = /* @__PURE__ */ new Set();
9537
- for (const path6 of paths) {
9538
- const index = path6.lastIndexOf("/");
9539
- if (index > 0) {
9540
- dirs.add(path6.slice(0, index));
9541
- }
9542
- }
9543
- return [...dirs];
9544
- }
9545
- function compactObject(input) {
9546
- const output = { ...input };
9547
- for (const [key, value] of Object.entries(output)) {
9548
- if (value === void 0) {
9549
- Reflect.deleteProperty(output, key);
9550
- }
9551
- }
9552
- return output;
9553
- }
9554
9328
  function toError(error) {
9555
9329
  return Error.isError(error) ? error : new Error(String(error));
9556
9330
  }
@@ -9569,7 +9343,6 @@ import {
9569
9343
  PathNotFoundError
9570
9344
  } from "@zukhruf/docker";
9571
9345
  import spawn3, { SubprocessError as SubprocessError3 } from "nano-spawn";
9572
- import { spawn as childSpawn2 } from "node:child_process";
9573
9346
  import { hash } from "node:crypto";
9574
9347
  import { readFileSync as readFileSync2 } from "node:fs";
9575
9348
  import { posix as posix3 } from "node:path";
@@ -9579,71 +9352,6 @@ function isDockerfileOptions(opts) {
9579
9352
  function isComposeOptions(opts) {
9580
9353
  return "compose" in opts;
9581
9354
  }
9582
- var SIZE_UNITS = {
9583
- "": 1,
9584
- k: 1024,
9585
- m: 1024 ** 2,
9586
- g: 1024 ** 3,
9587
- t: 1024 ** 4,
9588
- p: 1024 ** 5
9589
- };
9590
- function sizeInBytes(flag, value) {
9591
- const match = /^(\d+(?:\.\d+)?)\s*([kmgtp]?)(?:i?b)?$/i.exec(value);
9592
- if (!match) {
9593
- throw new DockerSandboxError(`Invalid ${flag} size: "${value}"`);
9594
- }
9595
- return Math.floor(Number(match[1]) * SIZE_UNITS[match[2].toLowerCase()]);
9596
- }
9597
- function ulimit(value) {
9598
- const match = /^([a-z]+)=(-?\d+)(?::(-?\d+))?$/.exec(value);
9599
- if (!match) {
9600
- throw new DockerSandboxError(`Invalid ulimit: "${value}"`);
9601
- }
9602
- const soft = Number(match[2]);
9603
- return {
9604
- Name: match[1],
9605
- Soft: soft,
9606
- Hard: match[3] === void 0 ? soft : Number(match[3])
9607
- };
9608
- }
9609
- function device(value) {
9610
- const [host, container = host, permissions = "rwm"] = value.split(":");
9611
- return {
9612
- PathOnHost: host,
9613
- PathInContainer: container,
9614
- CgroupPermissions: permissions
9615
- };
9616
- }
9617
- function gpuRequest(value) {
9618
- if (value === "all") return { Count: -1, Capabilities: [["gpu"]] };
9619
- if (/^\d+$/.test(value)) {
9620
- return { Count: Number(value), Capabilities: [["gpu"]] };
9621
- }
9622
- const devices = /^device=(.+)$/.exec(value);
9623
- if (devices) {
9624
- return { DeviceIDs: devices[1].split(","), Capabilities: [["gpu"]] };
9625
- }
9626
- throw new DockerSandboxError(`Invalid gpus value: "${value}"`);
9627
- }
9628
- function publishedPort(value) {
9629
- const [address, protocol = "tcp"] = value.split("/");
9630
- const parts = address.split(":");
9631
- const containerPort = parts.pop();
9632
- const hostPort = parts.pop() ?? "";
9633
- const hostIp = parts.join(":");
9634
- if (!containerPort || !/^\d+$/.test(containerPort)) {
9635
- throw new DockerSandboxError(`Invalid publish value: "${value}"`);
9636
- }
9637
- return {
9638
- port: `${containerPort}/${protocol}`,
9639
- binding: { HostIp: hostIp, HostPort: hostPort }
9640
- };
9641
- }
9642
- function securityOption(entry) {
9643
- const match = /^seccomp[=:](.+)$/.exec(entry);
9644
- if (!match || match[1] === "unconfined") return entry;
9645
- return `seccomp=${JSON.stringify(JSON.parse(readFileSync2(match[1], "utf-8")))}`;
9646
- }
9647
9355
  function mount(volume) {
9648
9356
  const ReadOnly = volume.readOnly !== false;
9649
9357
  if (volume.type === "bind") {
@@ -9668,107 +9376,22 @@ function mount(volume) {
9668
9376
  };
9669
9377
  }
9670
9378
  function containerCreateRequest(image, opts, workdir) {
9671
- const {
9672
- memory = "1g",
9673
- cpus = 2,
9674
- memorySwap,
9675
- shmSize,
9676
- pidsLimit,
9677
- ulimits = [],
9678
- cpusetCpus,
9679
- cpuShares
9680
- } = opts.resources ?? {};
9681
- const security = opts.security ?? {};
9682
- const network = opts.network ?? {};
9683
- const published = (network.publish ?? []).map(publishedPort);
9379
+ const { HostConfig, ...config } = opts.container ?? {};
9684
9380
  return {
9381
+ ...config,
9685
9382
  Image: image,
9686
9383
  WorkingDir: workdir,
9687
9384
  Env: Object.entries(opts.env ?? {}).map(
9688
9385
  ([key, value]) => `${key}=${value}`
9689
9386
  ),
9690
- Labels: opts.labels ?? {},
9691
9387
  ...opts.command === void 0 ? { Cmd: ["tail", "-f", "/dev/null"] } : opts.command === null || opts.command.length === 0 ? {} : { Cmd: [...opts.command] },
9692
- ...opts.entrypoint === void 0 ? {} : { Entrypoint: [opts.entrypoint] },
9693
- ...security.user ? { User: security.user } : {},
9694
- ...network.hostname ? { Hostname: network.hostname } : {},
9695
- ExposedPorts: Object.fromEntries(published.map(({ port }) => [port, {}])),
9696
9388
  HostConfig: {
9389
+ ...HostConfig,
9697
9390
  AutoRemove: true,
9698
- Memory: sizeInBytes("memory", memory),
9699
- NanoCpus: Math.round(cpus * 1e9),
9700
- ...memorySwap ? {
9701
- MemorySwap: memorySwap === "-1" ? -1 : sizeInBytes("memorySwap", memorySwap)
9702
- } : {},
9703
- ...shmSize ? { ShmSize: sizeInBytes("shmSize", shmSize) } : {},
9704
- ...pidsLimit === void 0 ? {} : { PidsLimit: pidsLimit },
9705
- Ulimits: ulimits.map(ulimit),
9706
- ...cpusetCpus ? { CpusetCpus: cpusetCpus } : {},
9707
- ...cpuShares === void 0 ? {} : { CpuShares: cpuShares },
9708
- ...opts.runtime ? { Runtime: opts.runtime } : {},
9709
- CapDrop: security.capDrop ?? [],
9710
- CapAdd: security.capAdd ?? [],
9711
- ReadonlyRootfs: security.readOnly === true,
9712
- Tmpfs: Object.fromEntries(
9713
- (security.tmpfs ?? []).map((entry) => {
9714
- const separator = entry.indexOf(":");
9715
- return separator < 0 ? [entry, ""] : [entry.slice(0, separator), entry.slice(separator + 1)];
9716
- })
9717
- ),
9718
- SecurityOpt: (security.securityOpt ?? []).map(securityOption),
9719
- ...network.mode ? { NetworkMode: network.mode } : {},
9720
- PortBindings: published.reduce(
9721
- (bindings, { port, binding }) => ({
9722
- ...bindings,
9723
- [port]: [...bindings[port] ?? [], binding]
9724
- }),
9725
- {}
9726
- ),
9727
- Dns: network.dns ?? [],
9728
- ExtraHosts: network.addHost ?? [],
9729
- ...opts.gpus ? { DeviceRequests: [gpuRequest(opts.gpus)] } : {},
9730
- Devices: (opts.devices ?? []).map(device),
9731
- ...opts.init ? { Init: true } : {},
9732
- Sysctls: opts.sysctls ?? {},
9733
9391
  Mounts: (opts.volumes ?? []).map(mount)
9734
9392
  }
9735
9393
  };
9736
9394
  }
9737
- function runDockerBuild(args, stdin, showBuildLogs, env) {
9738
- const stdio = [
9739
- stdin === void 0 ? "inherit" : "pipe",
9740
- showBuildLogs ? "inherit" : "ignore",
9741
- showBuildLogs ? "inherit" : "pipe"
9742
- ];
9743
- return new Promise((resolve3, reject) => {
9744
- const child = childSpawn2("docker", args, { stdio, env });
9745
- let stderr = "";
9746
- child.stderr?.setEncoding("utf8");
9747
- child.stderr?.on("data", (chunk) => {
9748
- stderr += chunk;
9749
- });
9750
- child.once(
9751
- "error",
9752
- (error) => reject(new DockerfileBuildError(error.message))
9753
- );
9754
- child.once("exit", (code) => {
9755
- if (code === 0) {
9756
- resolve3();
9757
- return;
9758
- }
9759
- reject(
9760
- new DockerfileBuildError(
9761
- showBuildLogs ? `docker build exited with code ${code} (see build output above)` : stderr || `docker build exited with code ${code}`
9762
- )
9763
- );
9764
- });
9765
- if (stdin !== void 0 && child.stdin) {
9766
- child.stdin.on("error", () => {
9767
- });
9768
- child.stdin.end(stdin);
9769
- }
9770
- });
9771
- }
9772
9395
  async function startContainer(container, image) {
9773
9396
  try {
9774
9397
  await container.start();
@@ -9802,76 +9425,38 @@ var dockerErrors = {
9802
9425
  volumeCreate: (name, reason) => new VolumeCreateError(name, reason)
9803
9426
  };
9804
9427
  function engineProcess2(process2) {
9805
- const queue = { highWaterMark: Number.POSITIVE_INFINITY };
9806
- const stdout = new TransformStream(
9807
- void 0,
9808
- void 0,
9809
- queue
9810
- );
9811
- const stderr = new TransformStream(
9812
- void 0,
9813
- void 0,
9814
- queue
9815
- );
9816
- const writers = {
9817
- stdout: stdout.writable.getWriter(),
9818
- stderr: stderr.writable.getWriter()
9428
+ const streams = {
9429
+ stdout: createByteReadable(),
9430
+ stderr: createByteReadable()
9819
9431
  };
9820
9432
  const exitCode = (async () => {
9821
9433
  try {
9822
9434
  for await (const { stream, data } of process2) {
9823
- await writers[stream].write(data);
9435
+ streams[stream].enqueue(data);
9824
9436
  }
9825
9437
  } catch (error) {
9826
- await Promise.all([
9827
- writers.stdout.abort(error),
9828
- writers.stderr.abort(error)
9829
- ]);
9438
+ streams.stdout.error(error);
9439
+ streams.stderr.error(error);
9830
9440
  throw error;
9831
9441
  }
9832
- await Promise.all([writers.stdout.close(), writers.stderr.close()]);
9442
+ streams.stdout.close();
9443
+ streams.stderr.close();
9833
9444
  return process2.exitCode;
9834
9445
  })();
9835
9446
  return {
9836
- stdout: stdout.readable,
9837
- stderr: stderr.readable,
9447
+ stdout: streams.stdout.stream,
9448
+ stderr: streams.stderr.stream,
9838
9449
  ...process2.stdin ? { stdin: process2.stdin } : {},
9839
9450
  exitCode
9840
9451
  };
9841
9452
  }
9842
9453
  var KERNEL_FILESYSTEMS = ["/proc", "/sys", "/dev"];
9843
- var RESOLVE_OWNER = [
9844
- "user=$1 group=$2",
9845
- 'case $user in *[!0-9]*) uid=$(id -u "$user") || exit 1 ;; *) uid=$user ;; esac',
9846
- "case $group in",
9847
- ' "") gid=$(id -g "$user" 2>/dev/null) || gid=0 ;;',
9848
- ` *[!0-9]*) gid=$(awk -F: -v name="$group" '$1 == name { print $3 }' /etc/group); [ -n "$gid" ] || { echo "unknown group $group" >&2; exit 1; } ;;`,
9849
- " *) gid=$group ;;",
9850
- "esac",
9851
- `printf '%s %s' "$uid" "$gid"`
9852
- ].join("\n");
9853
9454
  function fileLayout(config, hostConfig) {
9854
9455
  return {
9855
9456
  workdir: config?.WorkingDir || "/",
9856
- execOnly: [...KERNEL_FILESYSTEMS, ...Object.keys(hostConfig?.Tmpfs ?? {})],
9857
- user: config?.User ?? ""
9457
+ execOnly: [...KERNEL_FILESYSTEMS, ...Object.keys(hostConfig?.Tmpfs ?? {})]
9858
9458
  };
9859
9459
  }
9860
- async function resolveOwner(container, user2) {
9861
- if (user2 === "") return void 0;
9862
- const separator = user2.indexOf(":");
9863
- const [name, group] = separator < 0 ? [user2, ""] : [user2.slice(0, separator), user2.slice(separator + 1)];
9864
- const result = await container.exec({
9865
- Cmd: ["sh", "-c", RESOLVE_OWNER, "sh", name, group]
9866
- });
9867
- if (result.exitCode !== 0) {
9868
- throw new DockerSandboxError(
9869
- `Failed to resolve the container user "${user2}": ${result.stderr.trim()}`
9870
- );
9871
- }
9872
- const [uid, gid] = result.stdout.split(" ").map(Number);
9873
- return { uid, gid };
9874
- }
9875
9460
  function messageOf(error) {
9876
9461
  return Error.isError(error) ? error.message : String(error);
9877
9462
  }
@@ -9890,16 +9475,13 @@ var DockerContainer = class {
9890
9475
  commandTimeout;
9891
9476
  #container;
9892
9477
  #execOnly;
9893
- /** Who owns the files the sandbox writes: the container user, or root. */
9894
- #owner;
9895
9478
  #autoRemove;
9896
- constructor(name, container, layout, owner, commandTimeout, autoRemove) {
9479
+ constructor(name, container, layout, commandTimeout, autoRemove) {
9897
9480
  this.name = name;
9898
9481
  this.workdir = layout.workdir;
9899
9482
  this.commandTimeout = commandTimeout;
9900
9483
  this.#container = container;
9901
9484
  this.#execOnly = layout.execOnly;
9902
- this.#owner = owner;
9903
9485
  this.#autoRemove = autoRemove;
9904
9486
  }
9905
9487
  #config(argv, { workingDirectory, env = {} }) {
@@ -9985,34 +9567,16 @@ var DockerContainer = class {
9985
9567
  return writeFileOverExec(this, target, content, signal);
9986
9568
  }
9987
9569
  try {
9988
- const owner = this.#owner;
9989
- const directories = owner ? await this.#missingDirectories(posix3.dirname(target), signal) : [];
9990
- await this.#container.writeFiles(
9991
- [
9992
- ...directories.map((directory) => ({
9993
- path: directory,
9994
- directory: true,
9995
- ...owner
9996
- })),
9997
- { path: target, data: content, ...owner }
9998
- ],
9999
- { signal }
10000
- );
9570
+ await this.#container.writeFiles([{ path: target, data: content }], {
9571
+ signal,
9572
+ copyUIDGID: true
9573
+ });
10001
9574
  } catch (error) {
10002
9575
  throw new Error(`Failed to write file "${path6}": ${messageOf(error)}`, {
10003
9576
  cause: error
10004
9577
  });
10005
9578
  }
10006
9579
  }
10007
- /** The directories, parents first, that a write into `start` creates. */
10008
- async #missingDirectories(start, signal) {
10009
- const missing = [];
10010
- for (let directory = start; directory !== "/"; directory = posix3.dirname(directory)) {
10011
- if (await this.#container.stat(directory, { signal })) break;
10012
- missing.unshift(directory);
10013
- }
10014
- return missing;
10015
- }
10016
9580
  installerContext(image) {
10017
9581
  return createInstallerContext(
10018
9582
  {
@@ -10061,13 +9625,11 @@ var DockerEngine = class _DockerEngine {
10061
9625
  return new _DockerEngine(docker, commandTimeout);
10062
9626
  }
10063
9627
  /** A sandbox container handle for a container of this engine. */
10064
- async container(name, container, info) {
10065
- const layout = fileLayout(info.Config, info.HostConfig);
9628
+ container(name, container, info) {
10066
9629
  return new DockerContainer(
10067
9630
  name,
10068
9631
  container,
10069
- layout,
10070
- await resolveOwner(container, layout.user),
9632
+ fileLayout(info.Config, info.HostConfig),
10071
9633
  this.#commandTimeout,
10072
9634
  info.HostConfig?.AutoRemove === true
10073
9635
  );
@@ -10088,7 +9650,7 @@ var DockerEngine = class _DockerEngine {
10088
9650
  return {
10089
9651
  created: true,
10090
9652
  // The image's own USER and WORKDIR are in the inspect, not the body.
10091
- container: await this.container(name, started, await started.inspect())
9653
+ container: this.container(name, started, await started.inspect())
10092
9654
  };
10093
9655
  } catch (error) {
10094
9656
  await started[Symbol.asyncDispose]();
@@ -10159,7 +9721,7 @@ var DockerEngine = class _DockerEngine {
10159
9721
  try {
10160
9722
  await this.docker.volumes.create({
10161
9723
  Name: volume.name,
10162
- Labels: opts.labels ?? {},
9724
+ Labels: opts.container?.Labels,
10163
9725
  ...volume.driver ? { Driver: volume.driver } : {},
10164
9726
  DriverOpts: volume.driverOptions ?? {}
10165
9727
  });
@@ -10188,23 +9750,33 @@ var DockerEngine = class _DockerEngine {
10188
9750
  async imageExists(tag) {
10189
9751
  return await this.docker.images.inspect(tag) !== void 0;
10190
9752
  }
9753
+ /** An inline Dockerfile goes to `docker build -f -` on stdin. */
10191
9754
  async buildImage(spec) {
10192
9755
  const inline = spec.dockerfile.includes("\n");
10193
- const args = [
10194
- "build",
10195
- ...spec.identity ? ["--platform", spec.identity] : [],
10196
- "-t",
10197
- spec.tag,
10198
- "-f",
10199
- inline ? "-" : spec.dockerfile,
10200
- spec.context
10201
- ];
10202
- await runDockerBuild(
10203
- args,
10204
- inline ? spec.dockerfile : void 0,
10205
- spec.showBuildLogs,
10206
- this.cliEnv
10207
- );
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
+ }
10208
9780
  }
10209
9781
  dispose() {
10210
9782
  return this.docker[Symbol.asyncDispose]();
@@ -10216,7 +9788,7 @@ var ComposeStrategy = class extends ContainerSandboxStrategy {
10216
9788
  service;
10217
9789
  dockerEngine;
10218
9790
  constructor(args, engine) {
10219
- super({ resources: args.resources }, engine);
9791
+ super({}, engine);
10220
9792
  this.dockerEngine = engine;
10221
9793
  this.composeFile = args.compose;
10222
9794
  this.service = args.service;
@@ -10260,7 +9832,7 @@ var ComposeStrategy = class extends ContainerSandboxStrategy {
10260
9832
  );
10261
9833
  }
10262
9834
  return {
10263
- container: await this.dockerEngine.container(
9835
+ container: this.dockerEngine.container(
10264
9836
  this.projectName,
10265
9837
  container,
10266
9838
  await container.inspect()
@@ -10287,11 +9859,7 @@ async function createDockerSandbox(options = {}) {
10287
9859
  try {
10288
9860
  if (isComposeOptions(options)) {
10289
9861
  strategy = new ComposeStrategy(
10290
- {
10291
- compose: options.compose,
10292
- service: options.service,
10293
- resources: options.resources
10294
- },
9862
+ { compose: options.compose, service: options.service },
10295
9863
  engine
10296
9864
  );
10297
9865
  } else if (isDockerfileOptions(options)) {
@@ -10319,7 +9887,7 @@ async function useSandbox(options, fn) {
10319
9887
  }
10320
9888
 
10321
9889
  // packages/context/src/lib/sandbox/strace/file-changes.ts
10322
- import { randomUUID as randomUUID4 } from "node:crypto";
9890
+ import { randomUUID as randomUUID3 } from "node:crypto";
10323
9891
  import { posix as posix5 } from "node:path";
10324
9892
 
10325
9893
  // packages/context/src/lib/sandbox/strace/index.ts
@@ -10549,14 +10117,13 @@ async function withStraceFileChanges(sandbox, options) {
10549
10117
  const { include, exclude, onFileChanges } = options;
10550
10118
  const onError = options.onError ?? warnOnFileChangesError;
10551
10119
  const traceDir = options.traceDir ?? DEFAULT_TRACE_DIR;
10552
- const inner = "run" in sandbox ? sandbox : fromLegacySandbox(sandbox);
10553
10120
  const removeTrace = (traceFile) => void Promise.resolve(
10554
- inner.run({ command: `rm -f ${shellQuote(traceFile)}` })
10121
+ sandbox.run({ command: `rm -f ${shellQuote(traceFile)}` })
10555
10122
  ).catch(() => {
10556
10123
  });
10557
10124
  const readChanges = async (traceFile) => {
10558
10125
  try {
10559
- const trace = await inner.readTextFile({ path: traceFile });
10126
+ const trace = await sandbox.readTextFile({ path: traceFile });
10560
10127
  return trace === null ? [] : parseStraceTrace(trace, { include, exclude, traceFile, traceDir });
10561
10128
  } catch {
10562
10129
  return [];
@@ -10576,7 +10143,7 @@ async function withStraceFileChanges(sandbox, options) {
10576
10143
  let baseDirectory;
10577
10144
  const absolutePath = async (path6) => {
10578
10145
  if (posix5.isAbsolute(path6)) return posix5.normalize(path6);
10579
- baseDirectory ??= Promise.resolve(inner.run({ command: "pwd" })).then(
10146
+ baseDirectory ??= Promise.resolve(sandbox.run({ command: "pwd" })).then(
10580
10147
  ({ stdout }) => stdout.trimEnd()
10581
10148
  );
10582
10149
  return posix5.resolve(await baseDirectory, path6);
@@ -10587,8 +10154,8 @@ async function withStraceFileChanges(sandbox, options) {
10587
10154
  await onFileChanges?.([{ op, path: path6, timestamp: Date.now() }]);
10588
10155
  };
10589
10156
  async function spawn5(spawnOptions) {
10590
- const traceFile = `${traceDir}/${randomUUID4()}.strace`;
10591
- const child = await inner.spawn({
10157
+ const traceFile = `${traceDir}/${randomUUID3()}.strace`;
10158
+ const child = await sandbox.spawn({
10592
10159
  ...spawnOptions,
10593
10160
  command: buildStraceCommand(spawnOptions.command, traceFile, traceDir)
10594
10161
  });
@@ -10608,16 +10175,16 @@ async function withStraceFileChanges(sandbox, options) {
10608
10175
  }
10609
10176
  const dispose = async () => {
10610
10177
  await Promise.resolve(
10611
- inner.run({ command: `rm -rf ${shellQuote(traceDir)}` })
10178
+ sandbox.run({ command: `rm -rf ${shellQuote(traceDir)}` })
10612
10179
  ).catch(() => {
10613
10180
  });
10614
- await inner.dispose();
10181
+ await sandbox.dispose();
10615
10182
  };
10616
10183
  return {
10617
- description: inner.description,
10184
+ description: sandbox.description,
10618
10185
  async run(runOptions) {
10619
- const traceFile = `${traceDir}/${randomUUID4()}.strace`;
10620
- const sentinel = `__dat_trace_${randomUUID4()}__`;
10186
+ const traceFile = `${traceDir}/${randomUUID3()}.strace`;
10187
+ const sentinel = `__dat_trace_${randomUUID3()}__`;
10621
10188
  const wrapped = buildTracedCommand(
10622
10189
  runOptions.command,
10623
10190
  traceFile,
@@ -10626,7 +10193,7 @@ async function withStraceFileChanges(sandbox, options) {
10626
10193
  );
10627
10194
  let raw;
10628
10195
  try {
10629
- raw = await inner.run({ ...runOptions, command: wrapped });
10196
+ raw = await sandbox.run({ ...runOptions, command: wrapped });
10630
10197
  } catch (error) {
10631
10198
  removeTrace(traceFile);
10632
10199
  throw error;
@@ -10658,26 +10225,26 @@ async function withStraceFileChanges(sandbox, options) {
10658
10225
  return result;
10659
10226
  },
10660
10227
  spawn: spawn5,
10661
- readFile: (readOptions) => inner.readFile(readOptions),
10662
- readBinaryFile: (readOptions) => inner.readBinaryFile(readOptions),
10663
- readTextFile: (readOptions) => inner.readTextFile(readOptions),
10664
- stat: (statOptions) => inner.stat(statOptions),
10665
- listDirectory: (listOptions) => inner.listDirectory(listOptions),
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),
10666
10233
  deleteFile: async (deleteOptions) => {
10667
- const deleted = await inner.deleteFile(deleteOptions);
10234
+ const deleted = await sandbox.deleteFile(deleteOptions);
10668
10235
  if (deleted) await observe("delete", deleteOptions.path);
10669
10236
  return deleted;
10670
10237
  },
10671
10238
  writeFile: async (writeOptions) => {
10672
- await inner.writeFile(writeOptions);
10239
+ await sandbox.writeFile(writeOptions);
10673
10240
  await observe("write", writeOptions.path);
10674
10241
  },
10675
10242
  writeBinaryFile: async (writeOptions) => {
10676
- await inner.writeBinaryFile(writeOptions);
10243
+ await sandbox.writeBinaryFile(writeOptions);
10677
10244
  await observe("write", writeOptions.path);
10678
10245
  },
10679
10246
  writeTextFile: async (writeOptions) => {
10680
- await inner.writeTextFile(writeOptions);
10247
+ await sandbox.writeTextFile(writeOptions);
10681
10248
  await observe("write", writeOptions.path);
10682
10249
  },
10683
10250
  dispose,
@@ -10981,16 +10548,12 @@ function formatVersion(version) {
10981
10548
  }
10982
10549
 
10983
10550
  // packages/context/src/lib/sandbox/microsandbox-sandbox.ts
10984
- import {
10985
- extractLines as extractLines3
10986
- } from "@ai-sdk/provider-utils";
10987
- import { randomUUID as randomUUID5 } from "node:crypto";
10551
+ import "@ai-sdk/provider-utils";
10552
+ import { randomUUID as randomUUID4 } from "node:crypto";
10988
10553
  import { posix as posix7 } from "node:path";
10989
- import { text as text2 } from "node:stream/consumers";
10990
10554
  var MICROSANDBOX_DEFAULT_DESTINATION = "/workspace";
10991
10555
  var MICROSANDBOX_DEFAULT_IMAGE = "bash:5.3-alpine3.24";
10992
- var MICROSANDBOX_MAX_NAME_BYTES = 128;
10993
- var COMMAND_TIMEOUT_EXIT_CODE2 = 124;
10556
+ var COMMAND_TIMEOUT_EXIT_CODE3 = 124;
10994
10557
  var NOT_FOUND_MESSAGE = /\(os error (?:2|20)\)$/;
10995
10558
  var MicrosandboxSandboxError = class extends Error {
10996
10559
  constructor(message2, cause) {
@@ -11018,7 +10581,7 @@ async function createMicrosandboxSandbox(options = {}) {
11018
10581
  validateMicrosandboxOptions(options);
11019
10582
  const sdk = await importMicrosandbox();
11020
10583
  const ephemeral = options.name === void 0;
11021
- const name = options.name ?? `deepagents-msb-${randomUUID5()}`;
10584
+ const name = options.name ?? `deepagents-msb-${randomUUID4()}`;
11022
10585
  const workdir = options.workdir ?? MICROSANDBOX_DEFAULT_DESTINATION;
11023
10586
  const sandboxBuilder = (replace) => {
11024
10587
  let builder = sdk.Sandbox.builder(name).image(MICROSANDBOX_DEFAULT_IMAGE).patch((patch) => patch.mkdir(workdir));
@@ -11089,11 +10652,6 @@ function normalizeMicrosandboxError(error, sdk) {
11089
10652
  return new MicrosandboxCreationError(err.message, err);
11090
10653
  }
11091
10654
  function validateMicrosandboxOptions(options) {
11092
- if (options.name !== void 0 && Buffer.byteLength(options.name, "utf-8") > MICROSANDBOX_MAX_NAME_BYTES) {
11093
- throw new MicrosandboxSandboxError(
11094
- `Microsandbox names are limited to ${MICROSANDBOX_MAX_NAME_BYTES} UTF-8 bytes.`
11095
- );
11096
- }
11097
10655
  if (options.replace && options.name === void 0) {
11098
10656
  throw new MicrosandboxSandboxError(
11099
10657
  'Microsandbox options can only include "replace" together with "name" \u2014 an unnamed sandbox is always created fresh.'
@@ -11128,7 +10686,7 @@ function microsandboxSession(args) {
11128
10686
  throw error;
11129
10687
  }
11130
10688
  };
11131
- const resolve3 = (path6) => posix7.isAbsolute(path6) ? path6 : `${workdir}/${path6}`;
10689
+ const resolve3 = (path6) => resolveIn(workdir, path6);
11132
10690
  const statAt = async (path6) => {
11133
10691
  const metadata = await orNull(() => withFs((fs) => fs.stat(path6)));
11134
10692
  if (!metadata) return null;
@@ -11140,7 +10698,7 @@ function microsandboxSession(args) {
11140
10698
  }
11141
10699
  return { type, size: metadata.size };
11142
10700
  };
11143
- const readable = async (path6) => {
10701
+ const streamable = async (path6) => {
11144
10702
  const stat = await statAt(path6);
11145
10703
  if (stat?.type === "directory") {
11146
10704
  throw new Error(`Cannot read "${path6}": it is a directory.`);
@@ -11173,20 +10731,7 @@ function microsandboxSession(args) {
11173
10731
  const stderr = createByteReadable();
11174
10732
  let exited = false;
11175
10733
  let timedOut = false;
11176
- const kill = async () => {
11177
- if (exited) return;
11178
- await handle.kill().catch((error) => {
11179
- if (!exited) throw error;
11180
- });
11181
- };
11182
- const onAbort = () => {
11183
- void kill().catch(() => {
11184
- });
11185
- };
11186
- const timer = commandTimeout ? setTimeout(() => {
11187
- timedOut = true;
11188
- onAbort();
11189
- }, commandTimeout).unref() : void 0;
10734
+ let timer;
11190
10735
  const pump = async () => {
11191
10736
  let code;
11192
10737
  for await (const event of handle) {
@@ -11196,7 +10741,7 @@ function microsandboxSession(args) {
11196
10741
  }
11197
10742
  if (timedOut) {
11198
10743
  stderr.enqueue(new TextEncoder().encode("Command timed out"));
11199
- return COMMAND_TIMEOUT_EXIT_CODE2;
10744
+ return COMMAND_TIMEOUT_EXIT_CODE3;
11200
10745
  }
11201
10746
  if (code === void 0) {
11202
10747
  throw new MicrosandboxSandboxError(
@@ -11221,12 +10766,28 @@ function microsandboxSession(args) {
11221
10766
  ).finally(() => {
11222
10767
  exited = true;
11223
10768
  clearTimeout(timer);
11224
- abortSignal?.removeEventListener("abort", onAbort);
11225
10769
  });
11226
10770
  exitCode.catch(() => {
11227
10771
  });
11228
- if (abortSignal?.aborted) onAbort();
11229
- else abortSignal?.addEventListener("abort", onAbort, { once: true });
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;
10780
+ });
10781
+ },
10782
+ abortSignal
10783
+ });
10784
+ if (commandTimeout) {
10785
+ timer = setTimeout(() => {
10786
+ timedOut = true;
10787
+ void control.kill().catch(() => {
10788
+ });
10789
+ }, commandTimeout).unref();
10790
+ }
11230
10791
  return {
11231
10792
  stdout: stdout.stream,
11232
10793
  stderr: stderr.stream,
@@ -11237,10 +10798,7 @@ function microsandboxSession(args) {
11237
10798
  abort: () => sink.close()
11238
10799
  })
11239
10800
  } : {},
11240
- wait: async () => ({
11241
- exitCode: await exitCode.finally(() => abortSignal?.throwIfAborted())
11242
- }),
11243
- kill
10801
+ ...control
11244
10802
  };
11245
10803
  }
11246
10804
  const readBinaryFile = async ({
@@ -11249,7 +10807,6 @@ function microsandboxSession(args) {
11249
10807
  }) => {
11250
10808
  abortSignal?.throwIfAborted();
11251
10809
  const target = resolve3(path6);
11252
- if (!await readable(target)) return null;
11253
10810
  return orNull(() => withFs((fs) => fs.read(target)));
11254
10811
  };
11255
10812
  const writeBinaryFile = async ({
@@ -11266,33 +10823,16 @@ function microsandboxSession(args) {
11266
10823
  };
11267
10824
  return {
11268
10825
  description: `Commands run through bash -lc in a Microsandbox microVM, starting in ${workdir}.`,
11269
- run: async (options) => {
11270
- const process2 = await spawn5(options);
11271
- const [stdout, stderr, { exitCode }] = await Promise.all([
11272
- text2(process2.stdout),
11273
- text2(process2.stderr),
11274
- process2.wait()
11275
- ]);
11276
- return { stdout, stderr, exitCode };
11277
- },
10826
+ run: async (options) => collect(await spawn5(options)),
11278
10827
  spawn: spawn5,
11279
10828
  readBinaryFile,
11280
10829
  readFile: async ({ path: path6, abortSignal }) => {
11281
10830
  abortSignal?.throwIfAborted();
11282
10831
  const target = resolve3(path6);
11283
- if (!await readable(target)) return null;
10832
+ if (!await streamable(target)) return null;
11284
10833
  const stream = await orNull(() => withFs((fs) => fs.readStream(target)));
11285
10834
  return stream && ReadableStream.from(stream);
11286
10835
  },
11287
- readTextFile: async ({ startLine, endLine, encoding, ...options }) => {
11288
- const bytes = await readBinaryFile(options);
11289
- if (!bytes) return null;
11290
- return extractLines3({
11291
- text: Buffer.from(bytes).toString(bufferEncoding(encoding)),
11292
- startLine,
11293
- endLine
11294
- });
11295
- },
11296
10836
  writeBinaryFile,
11297
10837
  writeFile: async ({ path: path6, content, abortSignal }) => {
11298
10838
  abortSignal?.throwIfAborted();
@@ -11304,10 +10844,7 @@ function microsandboxSession(args) {
11304
10844
  for await (const chunk of content) await sink.write(chunk);
11305
10845
  await sink.close();
11306
10846
  },
11307
- writeTextFile: ({ content, encoding, ...options }) => writeBinaryFile({
11308
- ...options,
11309
- content: Buffer.from(content, bufferEncoding(encoding))
11310
- }),
10847
+ ...textCalls({ readBinaryFile, writeBinaryFile }),
11311
10848
  stat: async ({ path: path6, abortSignal }) => {
11312
10849
  abortSignal?.throwIfAborted();
11313
10850
  return statAt(resolve3(path6));
@@ -11340,43 +10877,6 @@ function microsandboxSession(args) {
11340
10877
  [Symbol.asyncDispose]: dispose
11341
10878
  };
11342
10879
  }
11343
- function createByteReadable() {
11344
- const ended = {
11345
- enqueue() {
11346
- },
11347
- close() {
11348
- },
11349
- error() {
11350
- }
11351
- };
11352
- let sink = ended;
11353
- const stream = new ReadableStream({
11354
- start(controller) {
11355
- sink = {
11356
- enqueue(chunk) {
11357
- if (chunk.length > 0) controller.enqueue(chunk);
11358
- },
11359
- close() {
11360
- sink = ended;
11361
- controller.close();
11362
- },
11363
- error(error) {
11364
- sink = ended;
11365
- controller.error(error);
11366
- }
11367
- };
11368
- },
11369
- cancel() {
11370
- sink = ended;
11371
- }
11372
- });
11373
- return {
11374
- stream,
11375
- enqueue: (chunk) => sink.enqueue(chunk),
11376
- close: () => sink.close(),
11377
- error: (error) => sink.error(error)
11378
- };
11379
- }
11380
10880
  function toError2(error) {
11381
10881
  return Error.isError(error) ? error : new Error(String(error));
11382
10882
  }
@@ -14960,11 +14460,9 @@ export {
14960
14460
  ContextEngine,
14961
14461
  ContextRenderer,
14962
14462
  ContextStore,
14963
- DAYTONA_DEFAULT_DESTINATION,
14964
14463
  DEFAULT_CANCEL_POLLING,
14965
14464
  DEFAULT_STOP_WHEN,
14966
14465
  DEFAULT_WATCH_POLLING,
14967
- DaytonaCommandError,
14968
14466
  DaytonaCreationError,
14969
14467
  DaytonaSandboxError,
14970
14468
  DockerEngine,
@@ -15129,7 +14627,6 @@ export {
15129
14627
  preference,
15130
14628
  principle,
15131
14629
  quirk,
15132
- readFileContent,
15133
14630
  reasoningFramework,
15134
14631
  reminder,
15135
14632
  render,