@deepagents/context 7.11.0 → 7.13.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}`);
@@ -7752,6 +7762,33 @@ function containerSession(container, errors) {
7752
7762
  deleteFile: ({ path: path6, abortSignal }) => deleteFileOverExec(container, path6, abortSignal)
7753
7763
  };
7754
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
+ }
7755
7792
 
7756
7793
  // packages/context/src/lib/sandbox/docker-sandbox-errors.ts
7757
7794
  var DockerSandboxError = class extends ContainerSandboxError {
@@ -7962,6 +7999,14 @@ function createInstallerContext(shell, containerId, image) {
7962
7999
  };
7963
8000
  }
7964
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
+
7965
8010
  // packages/context/src/lib/sandbox/container-sandbox.ts
7966
8011
  var CONTAINER_NAME_PATTERN = /^[A-Za-z0-9_.-]+$/;
7967
8012
  function validateSandboxOptions(opts, errors) {
@@ -8031,6 +8076,45 @@ var ContainerSandboxStrategy = class {
8031
8076
  }
8032
8077
  return sandbox;
8033
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
+ }
8034
8118
  containerName() {
8035
8119
  return this.name ? `sandbox-${this.name}` : `sandbox-${randomUUID2().slice(0, 8)}`;
8036
8120
  }
@@ -8801,14 +8885,6 @@ function createReadFileTool({
8801
8885
  });
8802
8886
  }
8803
8887
 
8804
- // packages/context/src/lib/sandbox/types.ts
8805
- var SandboxNotFoundError = class extends Error {
8806
- constructor(sandbox, options) {
8807
- super(`The sandbox "${sandbox}" no longer exists.`, options);
8808
- this.name = "SandboxNotFoundError";
8809
- }
8810
- };
8811
-
8812
8888
  // packages/context/src/lib/sandbox/bash-tool.ts
8813
8889
  var DEFAULT_MAX_FILES = 1e3;
8814
8890
  var DEFAULT_MAX_OUTPUT_LENGTH = 3e4;
@@ -9396,9 +9472,10 @@ import {
9396
9472
  PathNotFoundError
9397
9473
  } from "@zukhruf/docker";
9398
9474
  import spawn3, { SubprocessError as SubprocessError3 } from "nano-spawn";
9399
- import { hash } from "node:crypto";
9475
+ import { hash as hash2 } from "node:crypto";
9400
9476
  import { readFileSync as readFileSync2 } from "node:fs";
9401
9477
  import { posix as posix3 } from "node:path";
9478
+ import pMemoize3 from "p-memoize";
9402
9479
  function isDockerfileOptions(opts) {
9403
9480
  return "dockerfile" in opts;
9404
9481
  }
@@ -9428,10 +9505,11 @@ function mount(volume) {
9428
9505
  } : {}
9429
9506
  };
9430
9507
  }
9431
- function containerCreateRequest(image, opts, workdir) {
9508
+ function containerCreateRequest(image, opts, workdir, lifetime) {
9432
9509
  const { HostConfig, ...config } = opts.container ?? {};
9433
9510
  return {
9434
9511
  ...config,
9512
+ ...lifetime.kind === "chat" ? { Labels: { ...config.Labels, ...lifetime.labels } } : {},
9435
9513
  Image: image,
9436
9514
  WorkingDir: workdir,
9437
9515
  Env: Object.entries(opts.env ?? {}).map(
@@ -9440,7 +9518,9 @@ function containerCreateRequest(image, opts, workdir) {
9440
9518
  ...opts.command === void 0 ? { Cmd: ["tail", "-f", "/dev/null"] } : opts.command === null || opts.command.length === 0 ? {} : { Cmd: [...opts.command] },
9441
9519
  HostConfig: {
9442
9520
  ...HostConfig,
9443
- 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 },
9444
9524
  Mounts: (opts.volumes ?? []).map(mount)
9445
9525
  }
9446
9526
  };
@@ -9633,12 +9713,16 @@ var DockerContainer = class {
9633
9713
  if (this.#isExecOnly(target)) return statOverExec(this, target, signal);
9634
9714
  try {
9635
9715
  const followed = await this.#followLinks(target, signal);
9636
- 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;
9637
9721
  } catch (error) {
9638
9722
  if (isUnexplainedFailure(error)) {
9639
9723
  return statOverExec(this, target, signal);
9640
9724
  }
9641
- throw error;
9725
+ throw this.#notFound(error);
9642
9726
  }
9643
9727
  }
9644
9728
  async writeFile(path6, content, signal) {
@@ -9689,6 +9773,37 @@ var DockerContainer = class {
9689
9773
  }
9690
9774
  }
9691
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
+ };
9692
9807
  var DockerEngine = class _DockerEngine {
9693
9808
  bindMountsOnClient = false;
9694
9809
  defaultImage = "bash:5.3-alpine3.24";
@@ -9723,6 +9838,43 @@ var DockerEngine = class _DockerEngine {
9723
9838
  info.HostConfig?.AutoRemove === true
9724
9839
  );
9725
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
+ }
9726
9878
  async attach(name, image) {
9727
9879
  const found = await this.docker.containers.find(name).catch(unavailable);
9728
9880
  if (!found) return void 0;
@@ -9733,8 +9885,11 @@ var DockerEngine = class _DockerEngine {
9733
9885
  return this.container(name, found, info);
9734
9886
  }
9735
9887
  async run(image, name, opts, workdir) {
9736
- const started = await this.#createAndStart(image, name, opts, workdir);
9737
- 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;
9738
9893
  try {
9739
9894
  return {
9740
9895
  created: true,
@@ -9746,10 +9901,13 @@ var DockerEngine = class _DockerEngine {
9746
9901
  throw error;
9747
9902
  }
9748
9903
  }
9749
- /** Creates and starts the container; `undefined` when another caller has the name. */
9750
- 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) {
9751
9909
  try {
9752
- const body = containerCreateRequest(image, opts, workdir);
9910
+ const body = containerCreateRequest(image, opts, workdir, lifetime);
9753
9911
  const create = () => this.docker.containers.createOrGet(body, {
9754
9912
  name,
9755
9913
  platform: opts.platform
@@ -9759,14 +9917,14 @@ var DockerEngine = class _DockerEngine {
9759
9917
  await this.docker.images.pull(image, { platform: opts.platform });
9760
9918
  return create();
9761
9919
  });
9762
- if (!result.created) return void 0;
9920
+ if (!result.created) return result;
9763
9921
  try {
9764
9922
  await result.container.start();
9765
9923
  } catch (error) {
9766
9924
  await result.container[Symbol.asyncDispose]();
9767
9925
  throw error;
9768
9926
  }
9769
- return result.container;
9927
+ return result;
9770
9928
  } catch (error) {
9771
9929
  throw this.#runError(error, image, opts.volumes ?? []);
9772
9930
  }
@@ -9881,7 +10039,7 @@ var ComposeStrategy = class extends ContainerSandboxStrategy {
9881
10039
  this.dockerEngine = engine;
9882
10040
  this.composeFile = args.compose;
9883
10041
  this.service = args.service;
9884
- 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)}`;
9885
10043
  }
9886
10044
  compose(command) {
9887
10045
  return spawn3(
@@ -9936,6 +10094,111 @@ var ComposeStrategy = class extends ContainerSandboxStrategy {
9936
10094
  });
9937
10095
  }
9938
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
+ };
9939
10202
  async function createDockerSandbox(options = {}) {
9940
10203
  if (!isComposeOptions(options)) {
9941
10204
  validateSandboxOptions(options, dockerErrors);
@@ -13258,7 +13521,7 @@ function staticPartText(part, options) {
13258
13521
 
13259
13522
  // packages/context/src/lib/stream/postgres-notify-change-source.ts
13260
13523
  import { EventEmitter, on } from "node:events";
13261
- import pMemoize3 from "p-memoize";
13524
+ import pMemoize4 from "p-memoize";
13262
13525
  import { z as z17 } from "zod";
13263
13526
 
13264
13527
  // packages/context/src/lib/stream/ddl.stream.postgres-notify.ts
@@ -13371,7 +13634,7 @@ var PostgresNotifyChangeSource = class _PostgresNotifyChangeSource {
13371
13634
  #subscriptions = 0;
13372
13635
  #listener = NOT_LISTENING;
13373
13636
  /** Concurrent subscribers share one LISTEN setup; a failed one runs again. */
13374
- #listen = pMemoize3(() => this.#openListener(), { cache: false });
13637
+ #listen = pMemoize4(() => this.#openListener(), { cache: false });
13375
13638
  #handlers = {
13376
13639
  notification: (message2) => {
13377
13640
  this.#handleNotification(message2);
@@ -14551,6 +14814,7 @@ export {
14551
14814
  DaytonaSandboxError,
14552
14815
  DockerEngine,
14553
14816
  DockerNotAvailableError,
14817
+ DockerSandboxEnvironment,
14554
14818
  DockerSandboxError,
14555
14819
  DockerfileBuildError,
14556
14820
  FragmentLoaderResolver,