@zenera/sandbox 1.3.51 → 1.4.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/base.d.ts CHANGED
@@ -1,5 +1,10 @@
1
1
  import type { PrepareOptions } from './contract.ts';
2
2
  import type { Runner } from './process.ts';
3
+ /**
4
+ * The base's version, its tag. Bump it with every change to sandboxBaseDockerfile(): CI publishes
5
+ * a tag once and never again, and projects move to the new one on `zen check --fix`.
6
+ */
7
+ export declare const SANDBOX_BASE_VERSION = "base-1";
3
8
  export declare const SANDBOX_BASE_REPO = "ghcr.io/zenera-ai/zenera-sandbox";
4
9
  /**
5
10
  * The Playwright whose browser the base carries, for `zen page`: the version @zenera/browser pins
@@ -15,7 +20,7 @@ export declare const PLAYWRIGHT_BROWSERS_PATH = "/opt/ms-playwright";
15
20
  */
16
21
  export declare const SAME_PYTHON_CHECK: string;
17
22
  /**
18
- * The base image's Dockerfile, for `--build-arg ZEN_VERSION=<a published version>`.
23
+ * The base image's Dockerfile, SANDBOX_BASE_VERSION's content.
19
24
  * packages/sandbox/sandbox-base.Dockerfile is this, kept in step by a test.
20
25
  */
21
26
  export declare function sandboxBaseDockerfile(): string;
package/dist/base.js CHANGED
@@ -5,16 +5,28 @@ import { join } from 'node:path';
5
5
  // The sandbox base image
6
6
  //
7
7
  // What every project's sandbox/Dockerfile used to install itself — Python,
8
- // Node, the third-party packages zen's tools need, and @zenera/cli and
9
- // @zenera/rag at the version that wrote the file — built once per release and
10
- // published as ghcr.io/zenera-ai/zenera-sandbox:<version> (CI, RELEASE.md).
11
- // A project's Dockerfile starts `FROM` it and adds only its own needs, so a
12
- // new project pulls a few layers instead of running npm for minutes.
8
+ // Node, the libraries agents' scripts reach for, and zen page's browser — built
9
+ // once and published as ghcr.io/zenera-ai/zenera-sandbox:<SANDBOX_BASE_VERSION>
10
+ // (CI, RELEASE.md). A project's Dockerfile starts `FROM` it and adds only its
11
+ // own needs, so a new project pulls a few layers instead of running npm for
12
+ // minutes.
13
13
  //
14
- // When the image cannot be pulled (offline, air-gapped, not public yet, a
15
- // version not released), the build makes it here from the same Dockerfile and
16
- // tags it as the name the project asked for — slower, never broken.
14
+ // zen is not in it. The base is versioned on its own and changes only when what
15
+ // it holds changes, so a zen release leaves the base, and every project layer
16
+ // built on it, cached. zen reaches a sandbox from its release's runtime image
17
+ // instead: mounted read-only into a podman sandbox (engine sandbox.ts), copied
18
+ // into an agent image (cli container.ts). Older bases were tagged with the zen
19
+ // they held (`:1.3.45`); `zen check --fix` moves a project off them.
20
+ //
21
+ // When the image cannot be pulled (offline, air-gapped, not public yet), the
22
+ // build makes it here from the same Dockerfile and tags it as the name the
23
+ // project asked for — slower, never broken.
17
24
  // ---------------------------------------------------------------------------
25
+ /**
26
+ * The base's version, its tag. Bump it with every change to sandboxBaseDockerfile(): CI publishes
27
+ * a tag once and never again, and projects move to the new one on `zen check --fix`.
28
+ */
29
+ export const SANDBOX_BASE_VERSION = 'base-1';
18
30
  export const SANDBOX_BASE_REPO = 'ghcr.io/zenera-ai/zenera-sandbox';
19
31
  /** `FROM [--platform=…] ghcr.io/zenera-ai/zenera-sandbox:<version>`: the version is the tag. */
20
32
  const BASE_FROM = /^\s*FROM\s+(?:--platform=\S+\s+)?ghcr\.io\/zenera-ai\/zenera-sandbox:([^\s@]+)/gim;
@@ -34,13 +46,14 @@ const REAL_EXECUTABLE = `-c 'import os, sys; print(os.path.realpath(sys.executab
34
46
  export const SAME_PYTHON_CHECK = `p3="$(python3 ${REAL_EXECUTABLE})" && test -n "$p3" ` +
35
47
  `&& test "$(python ${REAL_EXECUTABLE})" = "$p3"`;
36
48
  /**
37
- * The base image's Dockerfile, for `--build-arg ZEN_VERSION=<a published version>`.
49
+ * The base image's Dockerfile, SANDBOX_BASE_VERSION's content.
38
50
  * packages/sandbox/sandbox-base.Dockerfile is this, kept in step by a test.
39
51
  */
40
52
  export function sandboxBaseDockerfile() {
41
53
  return `# Generated from sandboxBaseDockerfile() in src/base.ts - edit that, then run
42
54
  # \`npm run sandbox-base:dockerfile -w packages/sandbox\`. The base every zen project's
43
- # sandbox/Dockerfile starts FROM: ${SANDBOX_BASE_REPO}:<version>.
55
+ # sandbox/Dockerfile starts FROM: ${SANDBOX_BASE_REPO}:${SANDBOX_BASE_VERSION}. Bump
56
+ # SANDBOX_BASE_VERSION with every change. zen is not here: a sandbox gets it from zen's runtime.
44
57
  #
45
58
  # Python and Node both, because an agent asked to look at a repository does not
46
59
  # get to choose which one it finds.
@@ -62,8 +75,8 @@ COPY --from=node /usr/local/lib/node_modules /usr/local/lib/node_modules
62
75
  RUN ln -s /usr/local/lib/node_modules/npm/bin/npm-cli.js /usr/local/bin/npm \\
63
76
  && ln -s /usr/local/lib/node_modules/npm/bin/npx-cli.js /usr/local/bin/npx
64
77
 
65
- # Keep the third-party dependencies of @zenera/{cli,engine,neo,rag,view} cached
66
- # when the pinned CLI release changes. Keep in sync with their package.json files.
78
+ # The third-party libraries of @zenera/{cli,engine,neo,rag,view}, from when zen itself was
79
+ # installed here: agents' scripts may still require() them through NODE_PATH.
67
80
  RUN npm install -g \\
68
81
  "@anthropic-ai/sdk@^0.120.0" \\
69
82
  "@apidevtools/swagger-parser@^12.0.0" \\
@@ -140,14 +153,7 @@ RUN pip install --no-cache-dir \\
140
153
  # download cache there (hundreds of MB after one npm install) counts against the user's storage.
141
154
  ENV npm_config_cache=/tmp/.npm PIP_NO_CACHE_DIR=1
142
155
 
143
- # The zen of this release, so the tools in the container are the ones the session
144
- # outside it was built by. Declared here: an ARG invalidates the cache of every RUN after it.
145
- ARG ZEN_VERSION
146
- RUN test -n "$ZEN_VERSION" \\
147
- && npm install -g "@zenera/cli@$ZEN_VERSION" "@zenera/rag@$ZEN_VERSION" \\
148
- && rm -rf /tmp/.npm
149
-
150
- LABEL zenera.sandbox-base=1 zenera.version=$ZEN_VERSION \\
156
+ LABEL zenera.sandbox-base=${SANDBOX_BASE_VERSION} \\
151
157
  org.opencontainers.image.source=https://github.com/zenera-ai/ZeneraNeo
152
158
  `;
153
159
  }
@@ -176,7 +182,7 @@ export async function ensureSandboxBases(engine, run, dockerfilePath, opts = {})
176
182
  return;
177
183
  }
178
184
  const say = (line) => opts.onProgress?.(line);
179
- for (const { image, version } of sandboxBasesOf(text)) {
185
+ for (const { image } of sandboxBasesOf(text)) {
180
186
  const present = await run(engine, ['image', 'exists', image], { timeoutMs: 30_000 });
181
187
  if (present.code === 0) {
182
188
  continue;
@@ -192,19 +198,11 @@ export async function ensureSandboxBases(engine, run, dockerfilePath, opts = {})
192
198
  const why = (pulled.stderr.trim() || `exit ${pulled.code}`).split('\n').at(-1);
193
199
  say(` could not pull it (${why.slice(0, 200)})`);
194
200
  say(` building it here instead (several minutes, once)`);
201
+ // Whatever tag the project names, this is the current base: an old one is not kept.
195
202
  const ctx = mkdtempSync(join(tmpdir(), 'zen-sandbox-base-'));
196
203
  try {
197
204
  writeFileSync(join(ctx, 'Dockerfile'), sandboxBaseDockerfile());
198
- const built = await run(engine, [
199
- 'build',
200
- '--tag',
201
- image,
202
- '--build-arg',
203
- `ZEN_VERSION=${version}`,
204
- '--file',
205
- join(ctx, 'Dockerfile'),
206
- ctx,
207
- ], { timeoutMs: BUILD_MS, signal: opts.signal });
205
+ const built = await run(engine, ['build', '--tag', image, '--file', join(ctx, 'Dockerfile'), ctx], { timeoutMs: BUILD_MS, signal: opts.signal });
208
206
  if (built.code !== 0) {
209
207
  say(` building the base failed too; the project's build will say why`);
210
208
  }
@@ -103,6 +103,12 @@ export interface SandboxOptions extends SandboxSpec {
103
103
  readOnly?: boolean;
104
104
  /** extra bind mounts; the host side must already exist */
105
105
  mounts?: readonly Mount[];
106
+ /**
107
+ * Images whose files are mounted read-only into the container: zen's own runtime, so a
108
+ * command finds `zen` whatever image the project runs. A backend that cannot mount an image
109
+ * supplies the same files its own way (the agent image has them) or leaves them out.
110
+ */
111
+ imageMounts?: readonly ImageMount[];
106
112
  /**
107
113
  * Environment set on every command rather than on the container: values
108
114
  * that belong to the run, not to the container — the user it is acting for.
@@ -123,6 +129,18 @@ export interface SandboxOptions extends SandboxSpec {
123
129
  */
124
130
  execPaths?: Record<string, readonly string[]>;
125
131
  }
132
+ /** An image's whole filesystem, read-only, at `at` (podman `--mount type=image`). */
133
+ export interface ImageMount {
134
+ /** pulled before the container starts, unless the engine has it */
135
+ image: string;
136
+ /** absolute path in the container; the image's `/opt/x` is at `<at>/opt/x` */
137
+ at: string;
138
+ /**
139
+ * The container starts without it when it cannot be pulled (offline, say), rather than not
140
+ * at all: what it adds is a convenience, not something every command needs.
141
+ */
142
+ optional?: boolean;
143
+ }
126
144
  /**
127
145
  * One session's sandbox. `PodmanSandbox` is one on this machine; a remote
128
146
  * sandbox service is another. The tools and the job model are the same for
package/dist/podman.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { type Mount } from './mounts.ts';
2
2
  import { RootedFs } from './rooted-fs.ts';
3
3
  import { type Runner } from './process.ts';
4
- import { type BuildSpec, type PrepareOptions, type Sandbox, type SandboxFactory, type ExecOptions, type ExecResult, type JobOutput, type JobStopped, type SandboxOptions, type SandboxSpec } from './contract.ts';
4
+ import { type BuildSpec, type PrepareOptions, type Sandbox, type SandboxFactory, type ExecOptions, type ExecResult, type ImageMount, type JobOutput, type JobStopped, type SandboxOptions, type SandboxSpec } from './contract.ts';
5
5
  /** What only a podman sandbox needs: which binary to drive, and how to spawn it. */
6
6
  export interface PodmanHost {
7
7
  /** the container engine binary; `podman` when unset */
@@ -17,6 +17,7 @@ interface Resolved extends Required<Omit<SandboxSpec, 'user' | 'build'>> {
17
17
  key: string;
18
18
  readOnly: boolean;
19
19
  mounts: readonly Mount[];
20
+ imageMounts: readonly ImageMount[];
20
21
  execEnv: Record<string, string>;
21
22
  execPaths: Record<string, readonly string[]>;
22
23
  explicitCpus?: boolean;
@@ -37,7 +38,10 @@ export declare class PodmanSandbox implements Sandbox {
37
38
  constructor(opts: SandboxOptions, host?: PodmanHost);
38
39
  /** Whether anything was actually started — `close` is free when not. */
39
40
  get started(): boolean;
40
- /** Pulls the image, or builds it from the Dockerfile, unless the engine already has it. */
41
+ /**
42
+ * Pulls the image, or builds it from the Dockerfile, unless the engine already has it; then
43
+ * the images mounted into it.
44
+ */
41
45
  prepare(opts?: PrepareOptions): Promise<void>;
42
46
  /**
43
47
  * Idempotent, and single-flight: several tool calls in one batch all await
package/dist/podman.js CHANGED
@@ -57,6 +57,8 @@ export class PodmanSandbox {
57
57
  #ready;
58
58
  #prepared;
59
59
  #created = false;
60
+ /** the image mounts that could be pulled; worked out once, before the container is made */
61
+ #imageMounts;
60
62
  /** kills counted in this container's cgroup as of the last probe */
61
63
  #kills;
62
64
  constructor(opts, host = {}) {
@@ -77,17 +79,49 @@ export class PodmanSandbox {
77
79
  get started() {
78
80
  return this.#created;
79
81
  }
80
- /** Pulls the image, or builds it from the Dockerfile, unless the engine already has it. */
82
+ /**
83
+ * Pulls the image, or builds it from the Dockerfile, unless the engine already has it; then
84
+ * the images mounted into it.
85
+ */
81
86
  prepare(opts = {}) {
82
87
  if (this.#prepared && !opts.force) {
83
88
  return this.#prepared;
84
89
  }
85
- this.#prepared = ensurePodmanImage({ image: this.spec.image, build: this.spec.build }, { engine: this.engine, exec: this.#spawn }, opts).catch((err) => {
90
+ this.#prepared = ensurePodmanImage({ image: this.spec.image, build: this.spec.build }, { engine: this.engine, exec: this.#spawn }, opts)
91
+ .then(async () => {
92
+ this.#imageMounts = undefined;
93
+ await this.#mountable(opts);
94
+ })
95
+ .catch((err) => {
86
96
  this.#prepared = undefined;
87
97
  throw err;
88
98
  });
89
99
  return this.#prepared;
90
100
  }
101
+ /** The image mounts the engine has, pulled when missing; an optional one that fails is left out. */
102
+ #mountable(opts = {}) {
103
+ this.#imageMounts ??= (async () => {
104
+ const have = [];
105
+ for (const m of this.spec.imageMounts) {
106
+ try {
107
+ await ensurePodmanImage({ image: m.image }, { engine: this.engine, exec: this.#spawn }, { onProgress: opts.onProgress, slow: opts.slow, signal: opts.signal });
108
+ have.push(m);
109
+ }
110
+ catch (err) {
111
+ if (!m.optional) {
112
+ throw err;
113
+ }
114
+ // Optional by contract: the sandbox works without it, and says so once.
115
+ opts.onProgress?.(` starting without ${m.image} at ${m.at}: ${err instanceof Error ? err.message : String(err)}`);
116
+ }
117
+ }
118
+ return have;
119
+ })().catch((err) => {
120
+ this.#imageMounts = undefined;
121
+ throw err;
122
+ });
123
+ return this.#imageMounts;
124
+ }
91
125
  /**
92
126
  * Idempotent, and single-flight: several tool calls in one batch all await
93
127
  * the same start rather than racing to create the same container.
@@ -121,13 +155,13 @@ export class PodmanSandbox {
121
155
  if (this.spec.build) {
122
156
  await this.prepare();
123
157
  }
124
- const made = await this.#podman(this.#createArgs());
158
+ const made = await this.#podman(this.#createArgs(await this.#mountable()));
125
159
  if (made.code !== 0) {
126
160
  throw new SandboxError(`could not create container ${this.name}: ${message(made)}`, LOCKS.test(made.stderr) ? locksHint(this.engine) : undefined);
127
161
  }
128
162
  this.#created = true;
129
163
  }
130
- #createArgs() {
164
+ #createArgs(images) {
131
165
  const s = this.spec;
132
166
  const args = ['run', '--detach', '--name', this.name];
133
167
  args.push('--label', 'zenera=1', '--label', `zenera.key=${s.key}`);
@@ -135,6 +169,10 @@ export class PodmanSandbox {
135
169
  for (const m of s.mounts) {
136
170
  args.push('--volume', mount(m));
137
171
  }
172
+ // Read-only: an image mount is never writable unless asked to be.
173
+ for (const m of images) {
174
+ args.push('--mount', `type=image,source=${m.image},destination=${m.at}`);
175
+ }
138
176
  args.push('--workdir', s.workdir);
139
177
  args.push('--network', s.network);
140
178
  if (s.cpus > 0) {
@@ -530,10 +568,23 @@ function resolveSpec(opts) {
530
568
  secrets: opts.secrets ?? [],
531
569
  readOnly: opts.readOnly ?? false,
532
570
  mounts: opts.mounts ?? [],
571
+ imageMounts: checkImageMounts(opts.imageMounts ?? []),
533
572
  execEnv: opts.execEnv ?? {},
534
573
  execPaths: opts.execPaths ?? {},
535
574
  };
536
575
  }
576
+ /** `--mount` options are comma-separated `key=value`s: a comma or `=` in a value would add an option. */
577
+ function checkImageMounts(mounts) {
578
+ for (const m of mounts) {
579
+ if (/[,=\s]/.test(m.image) || !m.image) {
580
+ throw new SandboxError(`not an image to mount: ${JSON.stringify(m.image)}`);
581
+ }
582
+ if (/[,=\s]/.test(m.at) || !posix.isAbsolute(m.at)) {
583
+ throw new SandboxError(`an image mount needs an absolute path: ${JSON.stringify(m.at)}`);
584
+ }
585
+ }
586
+ return mounts;
587
+ }
537
588
  /**
538
589
  * The container's name is a function of its configuration. Change the image
539
590
  * and a new container appears rather than an old one quietly persisting with
@@ -567,6 +618,10 @@ function containerName(spec) {
567
618
  // Appended only when it is set, so adding the profile did not
568
619
  // rename every container that existed before it.
569
620
  ...(spec.hardening === 'strict' ? ['strict'] : []),
621
+ // Likewise; and a new zen's runtime is a new container, not an old one with a stale mount.
622
+ ...(spec.imageMounts.length
623
+ ? [['images', spec.imageMounts.map((m) => [m.image, m.at])]]
624
+ : []),
570
625
  ]))
571
626
  .digest('hex')
572
627
  .slice(0, 10);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zenera/sandbox",
3
- "version": "1.3.51",
3
+ "version": "1.4.0",
4
4
  "description": "Where an agent's commands run and the files they see: the Sandbox contract, podman and bubblewrap implementations, filesystem drivers and a contract test suite for other implementations.",
5
5
  "keywords": [
6
6
  "sandbox",