@deepagents/context 7.10.2 → 7.12.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.
package/dist/index.js CHANGED
@@ -7337,8 +7337,18 @@ import { setTimeout as delay } from "node:timers/promises";
7337
7337
  import {
7338
7338
  extractLines
7339
7339
  } from "@ai-sdk/provider-utils";
7340
+ import { hash } from "node:crypto";
7340
7341
  import { posix } from "node:path";
7341
7342
  import { text } from "node:stream/consumers";
7343
+ function chatSandboxName(namespace, chat2) {
7344
+ return `sandbox-${hash("sha256", JSON.stringify([namespace, chat2.chatId])).slice(0, 32)}`;
7345
+ }
7346
+ function chatSandboxLabels(namespace, chat2) {
7347
+ return {
7348
+ "deepagents.sandbox.namespace": namespace,
7349
+ "deepagents.sandbox.chat": chat2.chatId
7350
+ };
7351
+ }
7342
7352
  function bufferEncoding(encoding = "utf-8") {
7343
7353
  if (!Buffer.isEncoding(encoding)) {
7344
7354
  throw new TypeError(`Unknown encoding: ${encoding}`);
@@ -7594,6 +7604,7 @@ async function deleteFileOverExec(container, path6, signal) {
7594
7604
  }
7595
7605
  return true;
7596
7606
  }
7607
+ var CONTROL_DIRECTORIES = ["/dev/shm", "/tmp"];
7597
7608
  async function collectOutput(process2) {
7598
7609
  const [stdout, stderr, exitCode] = await Promise.all([
7599
7610
  text2(process2.stdout),
@@ -7602,11 +7613,14 @@ async function collectOutput(process2) {
7602
7613
  ]);
7603
7614
  return { stdout, stderr, exitCode };
7604
7615
  }
7605
- function managedCommand(command, controlPath, commandTimeout) {
7616
+ function managedCommand(command, controlFile, commandTimeout) {
7606
7617
  return [
7607
7618
  "set -m",
7608
- `control=${shellQuote(controlPath)}`,
7609
- ': > "$control" || exit 1',
7619
+ "control=",
7620
+ `for dir in ${CONTROL_DIRECTORIES.join(" ")}; do`,
7621
+ ` if { : > "$dir/"${shellQuote(controlFile)}; } 2>/dev/null; then control="$dir/"${shellQuote(controlFile)}; break; fi`,
7622
+ "done",
7623
+ `[ -n "$control" ] || { echo ${shellQuote(`Cannot start the command: neither ${CONTROL_DIRECTORIES.join(" nor ")} is writable for the file that lets the sandbox stop it`)} >&2; exit 1; }`,
7610
7624
  "timer=",
7611
7625
  `trap 'if [ -n "$timer" ]; then kill -TERM "$timer" 2>/dev/null || :; wait "$timer" 2>/dev/null || :; fi; rm -f "$control" "$control.timeout"' EXIT`,
7612
7626
  `bash -lc ${shellQuote(command)} &`,
@@ -7630,13 +7644,16 @@ function managedCommand(command, controlPath, commandTimeout) {
7630
7644
  'exit "$status"'
7631
7645
  ].join("\n");
7632
7646
  }
7633
- async function terminate(container, controlPath, exitCode) {
7647
+ async function terminate(container, controlFile, exitCode) {
7634
7648
  const exited = exitCode.then(
7635
7649
  () => true,
7636
7650
  () => true
7637
7651
  );
7638
7652
  const killGroup = [
7639
- `IFS= read -r pid < ${shellQuote(controlPath)} || exit 0`,
7653
+ `for dir in ${CONTROL_DIRECTORIES.join(" ")}; do`,
7654
+ ` { IFS= read -r pid < "$dir/"${shellQuote(controlFile)}; } 2>/dev/null && break`,
7655
+ " pid=",
7656
+ "done",
7640
7657
  '[ -n "$pid" ] || exit 0',
7641
7658
  "printf found",
7642
7659
  'kill -KILL -- "-$pid" 2>/dev/null || exit 0',
@@ -7679,18 +7696,18 @@ function containerSession(container, errors) {
7679
7696
  async function spawn5(options) {
7680
7697
  const { command, abortSignal, stdin } = options;
7681
7698
  abortSignal?.throwIfAborted();
7682
- const controlPath = `/dev/shm/deepagents-exec-${randomUUID()}.pid`;
7699
+ const controlFile = `deepagents-exec-${randomUUID()}.pid`;
7683
7700
  const process2 = await container.spawn(
7684
7701
  [
7685
7702
  "bash",
7686
7703
  "-c",
7687
- managedCommand(command, controlPath, container.commandTimeout)
7704
+ managedCommand(command, controlFile, container.commandTimeout)
7688
7705
  ],
7689
7706
  { ...scope(options), stdin }
7690
7707
  );
7691
7708
  const control = controlProcess({
7692
7709
  exitCode: process2.exitCode,
7693
- kill: () => terminate(container, controlPath, process2.exitCode),
7710
+ kill: () => terminate(container, controlFile, process2.exitCode),
7694
7711
  abortSignal
7695
7712
  });
7696
7713
  return {
@@ -7745,6 +7762,33 @@ function containerSession(container, errors) {
7745
7762
  deleteFile: ({ path: path6, abortSignal }) => deleteFileOverExec(container, path6, abortSignal)
7746
7763
  };
7747
7764
  }
7765
+ function chatContainerSandbox(container, errors, chatId, release) {
7766
+ const session = containerSession(container, errors);
7767
+ let closing;
7768
+ const close = () => closing ??= release();
7769
+ const live = (operation) => async (...args) => {
7770
+ if (closing !== void 0) {
7771
+ throw new Error(`The sandbox handle of chat "${chatId}" is closed.`);
7772
+ }
7773
+ return operation(...args);
7774
+ };
7775
+ return Object.assign(session, {
7776
+ run: live(session.run),
7777
+ spawn: live(session.spawn),
7778
+ readFile: live(session.readFile),
7779
+ readBinaryFile: live(session.readBinaryFile),
7780
+ readTextFile: live(session.readTextFile),
7781
+ writeFile: live(session.writeFile),
7782
+ writeBinaryFile: live(session.writeBinaryFile),
7783
+ writeTextFile: live(session.writeTextFile),
7784
+ stat: live(session.stat),
7785
+ listDirectory: live(session.listDirectory),
7786
+ deleteFile: live(session.deleteFile),
7787
+ resume: live(() => container.resume()),
7788
+ close,
7789
+ [Symbol.asyncDispose]: close
7790
+ });
7791
+ }
7748
7792
 
7749
7793
  // packages/context/src/lib/sandbox/docker-sandbox-errors.ts
7750
7794
  var DockerSandboxError = class extends ContainerSandboxError {
@@ -7955,6 +7999,14 @@ function createInstallerContext(shell, containerId, image) {
7955
7999
  };
7956
8000
  }
7957
8001
 
8002
+ // packages/context/src/lib/sandbox/types.ts
8003
+ var SandboxNotFoundError = class extends Error {
8004
+ constructor(sandbox, options) {
8005
+ super(`The sandbox "${sandbox}" no longer exists.`, options);
8006
+ this.name = "SandboxNotFoundError";
8007
+ }
8008
+ };
8009
+
7958
8010
  // packages/context/src/lib/sandbox/container-sandbox.ts
7959
8011
  var CONTAINER_NAME_PATTERN = /^[A-Za-z0-9_.-]+$/;
7960
8012
  function validateSandboxOptions(opts, errors) {
@@ -8024,6 +8076,45 @@ var ContainerSandboxStrategy = class {
8024
8076
  }
8025
8077
  return sandbox;
8026
8078
  }
8079
+ /**
8080
+ * The running chat container `name`: unpaused or started when it exists,
8081
+ * created with `labels` and configured when it does not. A create that
8082
+ * another caller won takes the winner's container. A container this call
8083
+ * created and could not configure is removed. The engine stays open.
8084
+ */
8085
+ async openChat(name, labels) {
8086
+ const found = await this.engine.find(name);
8087
+ if (found) {
8088
+ try {
8089
+ await found.resume();
8090
+ return found;
8091
+ } catch (error) {
8092
+ if (!(error instanceof SandboxNotFoundError)) throw error;
8093
+ }
8094
+ }
8095
+ const image = await this.getImage();
8096
+ await this.prepareVolumes();
8097
+ const { created, container } = await this.engine.createChat(
8098
+ image,
8099
+ name,
8100
+ this.opts,
8101
+ this.workdir,
8102
+ labels
8103
+ );
8104
+ if (!created) {
8105
+ await container.resume();
8106
+ return container;
8107
+ }
8108
+ try {
8109
+ await this.engine.ensureWorkdir(container, this.workdir);
8110
+ await this.configure(container, image);
8111
+ await this.assertBashAvailable(container);
8112
+ } catch (error) {
8113
+ await container.remove().catch((removeError) => suppress(error, removeError));
8114
+ throw error;
8115
+ }
8116
+ return container;
8117
+ }
8027
8118
  containerName() {
8028
8119
  return this.name ? `sandbox-${this.name}` : `sandbox-${randomUUID2().slice(0, 8)}`;
8029
8120
  }
@@ -8794,14 +8885,6 @@ function createReadFileTool({
8794
8885
  });
8795
8886
  }
8796
8887
 
8797
- // packages/context/src/lib/sandbox/types.ts
8798
- var SandboxNotFoundError = class extends Error {
8799
- constructor(sandbox, options) {
8800
- super(`The sandbox "${sandbox}" no longer exists.`, options);
8801
- this.name = "SandboxNotFoundError";
8802
- }
8803
- };
8804
-
8805
8888
  // packages/context/src/lib/sandbox/bash-tool.ts
8806
8889
  var DEFAULT_MAX_FILES = 1e3;
8807
8890
  var DEFAULT_MAX_OUTPUT_LENGTH = 3e4;
@@ -9389,9 +9472,10 @@ import {
9389
9472
  PathNotFoundError
9390
9473
  } from "@zukhruf/docker";
9391
9474
  import spawn3, { SubprocessError as SubprocessError3 } from "nano-spawn";
9392
- import { hash } from "node:crypto";
9475
+ import { hash as hash2 } from "node:crypto";
9393
9476
  import { readFileSync as readFileSync2 } from "node:fs";
9394
9477
  import { posix as posix3 } from "node:path";
9478
+ import pMemoize3 from "p-memoize";
9395
9479
  function isDockerfileOptions(opts) {
9396
9480
  return "dockerfile" in opts;
9397
9481
  }
@@ -9421,10 +9505,11 @@ function mount(volume) {
9421
9505
  } : {}
9422
9506
  };
9423
9507
  }
9424
- function containerCreateRequest(image, opts, workdir) {
9508
+ function containerCreateRequest(image, opts, workdir, lifetime) {
9425
9509
  const { HostConfig, ...config } = opts.container ?? {};
9426
9510
  return {
9427
9511
  ...config,
9512
+ ...lifetime.kind === "chat" ? { Labels: { ...config.Labels, ...lifetime.labels } } : {},
9428
9513
  Image: image,
9429
9514
  WorkingDir: workdir,
9430
9515
  Env: Object.entries(opts.env ?? {}).map(
@@ -9433,7 +9518,9 @@ function containerCreateRequest(image, opts, workdir) {
9433
9518
  ...opts.command === void 0 ? { Cmd: ["tail", "-f", "/dev/null"] } : opts.command === null || opts.command.length === 0 ? {} : { Cmd: [...opts.command] },
9434
9519
  HostConfig: {
9435
9520
  ...HostConfig,
9436
- AutoRemove: true,
9521
+ // A chat container lives for days: tini as PID 1 reaps the processes
9522
+ // that killed commands leave behind, and passes `docker stop` on.
9523
+ ...lifetime.kind === "chat" ? { AutoRemove: false, Init: true } : { AutoRemove: true },
9437
9524
  Mounts: (opts.volumes ?? []).map(mount)
9438
9525
  }
9439
9526
  };
@@ -9626,12 +9713,16 @@ var DockerContainer = class {
9626
9713
  if (this.#isExecOnly(target)) return statOverExec(this, target, signal);
9627
9714
  try {
9628
9715
  const followed = await this.#followLinks(target, signal);
9629
- return followed ? { type: fileType(followed.stat.mode), size: followed.stat.size } : null;
9716
+ if (followed) {
9717
+ return { type: fileType(followed.stat.mode), size: followed.stat.size };
9718
+ }
9719
+ await this.#container.inspect({ signal });
9720
+ return null;
9630
9721
  } catch (error) {
9631
9722
  if (isUnexplainedFailure(error)) {
9632
9723
  return statOverExec(this, target, signal);
9633
9724
  }
9634
- throw error;
9725
+ throw this.#notFound(error);
9635
9726
  }
9636
9727
  }
9637
9728
  async writeFile(path6, content, signal) {
@@ -9666,7 +9757,15 @@ var DockerContainer = class {
9666
9757
  try {
9667
9758
  await this.#container.stop();
9668
9759
  if (this.#autoRemove) {
9669
- await this.#container.wait({ condition: "removed" });
9760
+ const { Error: failure } = await this.#container.wait({
9761
+ condition: "removed"
9762
+ });
9763
+ if (failure?.Message) {
9764
+ throw new DockerSandboxError(
9765
+ `Failed to remove container "${this.name}": ${failure.Message}`,
9766
+ this.name
9767
+ );
9768
+ }
9670
9769
  }
9671
9770
  } catch (error) {
9672
9771
  if (error instanceof ContainerNotFoundError) return;
@@ -9674,6 +9773,37 @@ var DockerContainer = class {
9674
9773
  }
9675
9774
  }
9676
9775
  };
9776
+ var DockerChatContainer = class extends DockerContainer {
9777
+ #container;
9778
+ #containers;
9779
+ constructor(name, container, layout, commandTimeout, containers) {
9780
+ super(name, container, layout, commandTimeout, false);
9781
+ this.#container = container;
9782
+ this.#containers = containers;
9783
+ }
9784
+ /** Inspects by name, so a container that now has the name is not this one. */
9785
+ async resume() {
9786
+ const info = await this.#containers.inspect(this.name).catch(unavailable);
9787
+ const state = info?.State?.Status;
9788
+ if (info?.Id !== this.#container.id || state === "removing" || state === "dead") {
9789
+ throw new SandboxNotFoundError(this.name);
9790
+ }
9791
+ try {
9792
+ if (state === "paused") await this.#container.unpause();
9793
+ else if (state === "created" || state === "exited") {
9794
+ await this.#container.start();
9795
+ }
9796
+ } catch (error) {
9797
+ if (error instanceof ContainerNotFoundError) {
9798
+ throw new SandboxNotFoundError(this.name, { cause: error });
9799
+ }
9800
+ unavailable(error);
9801
+ }
9802
+ }
9803
+ async remove() {
9804
+ await this.#container.remove({ force: true, v: true }).catch(unavailable);
9805
+ }
9806
+ };
9677
9807
  var DockerEngine = class _DockerEngine {
9678
9808
  bindMountsOnClient = false;
9679
9809
  defaultImage = "bash:5.3-alpine3.24";
@@ -9708,6 +9838,43 @@ var DockerEngine = class _DockerEngine {
9708
9838
  info.HostConfig?.AutoRemove === true
9709
9839
  );
9710
9840
  }
9841
+ #chatContainer(name, container, info) {
9842
+ return new DockerChatContainer(
9843
+ name,
9844
+ container,
9845
+ fileLayout(info.Config, info.HostConfig),
9846
+ this.#commandTimeout,
9847
+ this.docker.containers
9848
+ );
9849
+ }
9850
+ async find(name) {
9851
+ const found = await this.docker.containers.find(name).catch(unavailable);
9852
+ if (!found) return void 0;
9853
+ const info = await found.inspect().catch((error) => {
9854
+ if (error instanceof ContainerNotFoundError) return void 0;
9855
+ unavailable(error);
9856
+ });
9857
+ return info && this.#chatContainer(name, found, info);
9858
+ }
9859
+ async createChat(image, name, opts, workdir, labels) {
9860
+ const result = await this.#createOrGet(image, name, opts, workdir, {
9861
+ kind: "chat",
9862
+ labels
9863
+ });
9864
+ try {
9865
+ return {
9866
+ created: result.created,
9867
+ container: this.#chatContainer(
9868
+ name,
9869
+ result.container,
9870
+ await result.container.inspect()
9871
+ )
9872
+ };
9873
+ } catch (error) {
9874
+ if (result.created) await result.container[Symbol.asyncDispose]();
9875
+ unavailable(error);
9876
+ }
9877
+ }
9711
9878
  async attach(name, image) {
9712
9879
  const found = await this.docker.containers.find(name).catch(unavailable);
9713
9880
  if (!found) return void 0;
@@ -9718,8 +9885,11 @@ var DockerEngine = class _DockerEngine {
9718
9885
  return this.container(name, found, info);
9719
9886
  }
9720
9887
  async run(image, name, opts, workdir) {
9721
- const started = await this.#createAndStart(image, name, opts, workdir);
9722
- if (!started) return { created: false };
9888
+ const result = await this.#createOrGet(image, name, opts, workdir, {
9889
+ kind: "one-off"
9890
+ });
9891
+ if (!result.created) return { created: false };
9892
+ const started = result.container;
9723
9893
  try {
9724
9894
  return {
9725
9895
  created: true,
@@ -9731,10 +9901,13 @@ var DockerEngine = class _DockerEngine {
9731
9901
  throw error;
9732
9902
  }
9733
9903
  }
9734
- /** Creates and starts the container; `undefined` when another caller has the name. */
9735
- async #createAndStart(image, name, opts, workdir) {
9904
+ /**
9905
+ * Creates and starts the container, or gives the one that another caller
9906
+ * has under the name, as it is.
9907
+ */
9908
+ async #createOrGet(image, name, opts, workdir, lifetime) {
9736
9909
  try {
9737
- const body = containerCreateRequest(image, opts, workdir);
9910
+ const body = containerCreateRequest(image, opts, workdir, lifetime);
9738
9911
  const create = () => this.docker.containers.createOrGet(body, {
9739
9912
  name,
9740
9913
  platform: opts.platform
@@ -9744,14 +9917,14 @@ var DockerEngine = class _DockerEngine {
9744
9917
  await this.docker.images.pull(image, { platform: opts.platform });
9745
9918
  return create();
9746
9919
  });
9747
- if (!result.created) return void 0;
9920
+ if (!result.created) return result;
9748
9921
  try {
9749
9922
  await result.container.start();
9750
9923
  } catch (error) {
9751
9924
  await result.container[Symbol.asyncDispose]();
9752
9925
  throw error;
9753
9926
  }
9754
- return result.container;
9927
+ return result;
9755
9928
  } catch (error) {
9756
9929
  throw this.#runError(error, image, opts.volumes ?? []);
9757
9930
  }
@@ -9866,7 +10039,7 @@ var ComposeStrategy = class extends ContainerSandboxStrategy {
9866
10039
  this.dockerEngine = engine;
9867
10040
  this.composeFile = args.compose;
9868
10041
  this.service = args.service;
9869
- this.projectName = `sandbox-${hash("sha256", readFileSync2(this.composeFile, "utf-8")).slice(0, 8)}`;
10042
+ this.projectName = `sandbox-${hash2("sha256", readFileSync2(this.composeFile, "utf-8")).slice(0, 8)}`;
9870
10043
  }
9871
10044
  compose(command) {
9872
10045
  return spawn3(
@@ -9921,6 +10094,111 @@ var ComposeStrategy = class extends ContainerSandboxStrategy {
9921
10094
  });
9922
10095
  }
9923
10096
  };
10097
+ var DockerSandboxEnvironment = class {
10098
+ #options;
10099
+ /** The connected engine, while something holds it; concurrent connects share one. */
10100
+ #connected = /* @__PURE__ */ new Map();
10101
+ #connect = pMemoize3(
10102
+ () => DockerEngine.connect(
10103
+ this.#options.environment ?? process.env,
10104
+ this.#options.commandTimeout
10105
+ ),
10106
+ { cache: this.#connected }
10107
+ );
10108
+ #holders = 0;
10109
+ constructor(options) {
10110
+ validateEnv(options.env, dockerErrors);
10111
+ this.#options = options;
10112
+ }
10113
+ async #acquire() {
10114
+ this.#holders++;
10115
+ try {
10116
+ return await this.#connect();
10117
+ } catch (error) {
10118
+ this.#holders--;
10119
+ throw error;
10120
+ }
10121
+ }
10122
+ /** The last holder closes the engine, and the next acquire connects again. */
10123
+ async #release() {
10124
+ if (--this.#holders > 0) return;
10125
+ const engines = [...this.#connected.values()];
10126
+ this.#connected.clear();
10127
+ for (const engine of engines) await engine.dispose();
10128
+ }
10129
+ async #withEngine(fn) {
10130
+ const engine = await this.#acquire();
10131
+ try {
10132
+ return await fn(engine);
10133
+ } finally {
10134
+ await this.#release();
10135
+ }
10136
+ }
10137
+ #strategy(engine, chat2) {
10138
+ const { volumes, ...options } = this.#options;
10139
+ const opts = { ...options, volumes: volumes?.(chat2) ?? [] };
10140
+ if (options.dockerfile !== void 0) {
10141
+ return new ContainerfileStrategy(opts, engine, {
10142
+ dockerfile: options.dockerfile,
10143
+ context: options.context ?? ".",
10144
+ showBuildLogs: options.showBuildLogs ?? false,
10145
+ identity: options.platform
10146
+ });
10147
+ }
10148
+ return new RuntimeStrategy(opts, engine, {
10149
+ image: options.image ?? engine.defaultImage,
10150
+ installers: []
10151
+ });
10152
+ }
10153
+ async open(chat2) {
10154
+ const engine = await this.#acquire();
10155
+ let container;
10156
+ try {
10157
+ container = await this.#strategy(engine, chat2).openChat(
10158
+ chatSandboxName(this.#options.namespace, chat2),
10159
+ chatSandboxLabels(this.#options.namespace, chat2)
10160
+ );
10161
+ } catch (error) {
10162
+ await this.#release();
10163
+ throw error;
10164
+ }
10165
+ const sandbox = chatContainerSandbox(
10166
+ container,
10167
+ dockerErrors,
10168
+ chat2.chatId,
10169
+ () => this.#release()
10170
+ );
10171
+ if (this.#options.readiness) {
10172
+ try {
10173
+ await this.#options.readiness(sandbox);
10174
+ } catch (error) {
10175
+ await sandbox.close().catch(() => {
10176
+ });
10177
+ throw error;
10178
+ }
10179
+ }
10180
+ return sandbox;
10181
+ }
10182
+ /** `docker stop` with the engine's grace, which the init cuts short. */
10183
+ async stop(chat2) {
10184
+ await this.#withEngine(async (engine) => {
10185
+ const found = await engine.docker.containers.find(chatSandboxName(this.#options.namespace, chat2)).catch(unavailable);
10186
+ await found?.stop().catch((error) => {
10187
+ if (error instanceof ContainerNotFoundError) return;
10188
+ unavailable(error);
10189
+ });
10190
+ });
10191
+ }
10192
+ /** `docker rm -f` with the container's anonymous volumes; named volumes stay. */
10193
+ async delete(chat2) {
10194
+ await this.#withEngine(async (engine) => {
10195
+ const found = await engine.find(
10196
+ chatSandboxName(this.#options.namespace, chat2)
10197
+ );
10198
+ await found?.remove();
10199
+ });
10200
+ }
10201
+ };
9924
10202
  async function createDockerSandbox(options = {}) {
9925
10203
  if (!isComposeOptions(options)) {
9926
10204
  validateSandboxOptions(options, dockerErrors);
@@ -11027,6 +11305,7 @@ function buildSubcommandRepair(name, subcommands) {
11027
11305
  // packages/context/src/lib/sandbox/virtual-sandbox.ts
11028
11306
  import { createJustBashSandboxSessionFromNativeSandbox } from "@ai-sdk/sandbox-just-bash";
11029
11307
  import {
11308
+ InMemoryFs,
11030
11309
  Sandbox
11031
11310
  } from "just-bash";
11032
11311
  async function createVirtualSandbox({
@@ -11054,6 +11333,54 @@ async function createVirtualSandbox({
11054
11333
  }
11055
11334
  return sandbox;
11056
11335
  }
11336
+ var VirtualSandboxEnvironment = class {
11337
+ #options;
11338
+ #filesystems = /* @__PURE__ */ new Map();
11339
+ constructor(options = {}) {
11340
+ this.#options = options;
11341
+ }
11342
+ async open(chat2) {
11343
+ let fs = this.#filesystems.get(chat2.chatId);
11344
+ if (fs === void 0) {
11345
+ fs = new InMemoryFs();
11346
+ this.#filesystems.set(chat2.chatId, fs);
11347
+ }
11348
+ const sandbox = await createVirtualSandbox({ ...this.#options, fs });
11349
+ let closing;
11350
+ const close = () => closing ??= sandbox.dispose();
11351
+ const live = (operation) => async (...args) => {
11352
+ if (closing !== void 0) {
11353
+ throw new Error(
11354
+ `The sandbox handle of chat "${chat2.chatId}" is closed.`
11355
+ );
11356
+ }
11357
+ if (this.#filesystems.get(chat2.chatId) !== fs) {
11358
+ throw new SandboxNotFoundError(chat2.chatId);
11359
+ }
11360
+ return operation.apply(sandbox, args);
11361
+ };
11362
+ return Object.assign(sandbox, {
11363
+ run: live(sandbox.run),
11364
+ spawn: live(sandbox.spawn),
11365
+ readFile: live(sandbox.readFile),
11366
+ readBinaryFile: live(sandbox.readBinaryFile),
11367
+ readTextFile: live(sandbox.readTextFile),
11368
+ writeFile: live(sandbox.writeFile),
11369
+ writeBinaryFile: live(sandbox.writeBinaryFile),
11370
+ writeTextFile: live(sandbox.writeTextFile),
11371
+ stat: live(sandbox.stat),
11372
+ listDirectory: live(sandbox.listDirectory),
11373
+ deleteFile: live(sandbox.deleteFile),
11374
+ resume: live(async () => {
11375
+ }),
11376
+ close,
11377
+ [Symbol.asyncDispose]: close
11378
+ });
11379
+ }
11380
+ async delete(chat2) {
11381
+ this.#filesystems.delete(chat2.chatId);
11382
+ }
11383
+ };
11057
11384
 
11058
11385
  // packages/context/src/lib/skills/fragments.ts
11059
11386
  import dedent4 from "dedent";
@@ -13194,7 +13521,7 @@ function staticPartText(part, options) {
13194
13521
 
13195
13522
  // packages/context/src/lib/stream/postgres-notify-change-source.ts
13196
13523
  import { EventEmitter, on } from "node:events";
13197
- import pMemoize3 from "p-memoize";
13524
+ import pMemoize4 from "p-memoize";
13198
13525
  import { z as z17 } from "zod";
13199
13526
 
13200
13527
  // packages/context/src/lib/stream/ddl.stream.postgres-notify.ts
@@ -13307,7 +13634,7 @@ var PostgresNotifyChangeSource = class _PostgresNotifyChangeSource {
13307
13634
  #subscriptions = 0;
13308
13635
  #listener = NOT_LISTENING;
13309
13636
  /** Concurrent subscribers share one LISTEN setup; a failed one runs again. */
13310
- #listen = pMemoize3(() => this.#openListener(), { cache: false });
13637
+ #listen = pMemoize4(() => this.#openListener(), { cache: false });
13311
13638
  #handlers = {
13312
13639
  notification: (message2) => {
13313
13640
  this.#handleNotification(message2);
@@ -14487,6 +14814,7 @@ export {
14487
14814
  DaytonaSandboxError,
14488
14815
  DockerEngine,
14489
14816
  DockerNotAvailableError,
14817
+ DockerSandboxEnvironment,
14490
14818
  DockerSandboxError,
14491
14819
  DockerfileBuildError,
14492
14820
  FragmentLoaderResolver,
@@ -14528,6 +14856,7 @@ export {
14528
14856
  TomlRenderer,
14529
14857
  ToonRenderer,
14530
14858
  UrlBinaryInstaller,
14859
+ VirtualSandboxEnvironment,
14531
14860
  VolumeCreateError,
14532
14861
  VolumeInspectError,
14533
14862
  VolumePathError,