@zenera/cli 1.1.58 → 1.2.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.
@@ -0,0 +1,398 @@
1
+ /**
2
+ * Host-side image build and container lifecycle for zen server start --container.
3
+ * buildAgentImage packs the installed runtime onto the project's sandbox image;
4
+ * agentDockerfile defines its non-root Node/bwrap environment, and runContainer
5
+ * mounts project/state and a startup seed snapshot, publishes the port, follows logs
6
+ * and forwards shutdown before cleaning up the snapshot.
7
+ * Used by commands/server.ts; onStarted lets that command print a host-side chat link.
8
+ */
9
+ import { home, KeyStore, credentials, gcloudAdc, loadProjectEnv, MODEL_CONTEXT_ENV, resolveBuild, writeRuntime, } from '@zenera/engine';
10
+ import { DEFAULT_SANDBOX_IMAGE, readProjectConfig } from '@zenera/neo';
11
+ import { runProcess } from '@zenera/sandbox';
12
+ import { spawn } from 'node:child_process';
13
+ import { createHash, randomBytes } from 'node:crypto';
14
+ import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
15
+ import { createRequire } from 'node:module';
16
+ import { dirname, join } from 'node:path';
17
+ import { fileURLToPath } from 'node:url';
18
+ import { asCliError, ensureImage, ensurePodmanReady } from "./podman.js";
19
+ import { prepareMemorySeed } from "./seed.js";
20
+ import { buildProgress, HOST_MANAGED_ENV, streamAgentBuild } from "./serverDisplay.js";
21
+ import { bold, CliError, cyan, dim, EXIT, green, note, table, yellow } from "./term.js";
22
+ // ---------------------------------------------------------------------------
23
+ // The agent image, built here and run in podman: `zen server start --container`.
24
+ //
25
+ // Two builds. The project's environment — its sandbox/Dockerfile, or its
26
+ // `image:` — exactly as `zen run` builds or pulls it. Then the agent image on
27
+ // top of it: this CLI's own @zenera packages (packed from where they are
28
+ // installed, so it runs this code, released or not) with a Linux Node, a
29
+ // static bwrap, the `zenera` libraries and the image's own environment for
30
+ // commands, all under /opt/zenera, with `zen server start` as its command.
31
+ // Inside it the server finds itself in the agent image: bwrap, /project,
32
+ // /state. Nothing in it builds or starts containers.
33
+ // ---------------------------------------------------------------------------
34
+ /** The packages the server needs, in an order npm can install from files. */
35
+ const PACKAGES = ['sandbox', 'neo', 'view', 'engine', 'server', 'cli'];
36
+ const BWRAP_VERSION = '0.13.1';
37
+ const IMAGE_REPO = 'localhost/zenera-agent';
38
+ export const AGENT_UID = 10001;
39
+ export const AGENT_GID = 10001;
40
+ /** The agent image for a project, built unless this machine has it already. */
41
+ export async function buildAgentImage(projectDir, opts = {}) {
42
+ await ensurePodmanReady({ yes: true }).catch((err) => {
43
+ throw asCliError(err);
44
+ });
45
+ // 1. The project's environment, as `zen run` has it.
46
+ const { root, config } = readProjectConfig(projectDir);
47
+ const build = resolveBuild(root, config.sandbox);
48
+ const base = build?.tag ?? config.sandbox?.image ?? DEFAULT_SANDBOX_IMAGE;
49
+ const baseOutput = buildProgress(opts.verbose);
50
+ try {
51
+ await ensureImage({
52
+ image: base,
53
+ build: build && { dockerfile: build.dockerfile, context: build.context },
54
+ }, { force: opts.rebuild, progress: { onProgress: baseOutput.line } });
55
+ }
56
+ finally {
57
+ baseOutput.done();
58
+ }
59
+ const inspected = await podman(['image', 'inspect', '--format', '{{json .}}', base]);
60
+ const image = JSON.parse(inspected);
61
+ // 2. The context: zen packed, the libraries, the image's environment, the Dockerfile.
62
+ const ctx = join(home(), 'images', `ctx-${randomBytes(4).toString('hex')}`);
63
+ mkdirSync(join(ctx, 'pkgs'), { recursive: true });
64
+ try {
65
+ const tarballs = {};
66
+ for (const name of PACKAGES) {
67
+ tarballs[`@zenera/${name}`] = await pack(packageDir(name), join(ctx, 'pkgs'));
68
+ }
69
+ writeRuntime(join(ctx, 'runtime'));
70
+ mkdirSync(join(ctx, 'etc'), { recursive: true });
71
+ writeFileSync(join(ctx, 'etc', 'image-env.json'), JSON.stringify(envOf(image.Config?.Env)));
72
+ writeFileSync(join(ctx, 'app.json'), JSON.stringify(appManifest(tarballs), null, 2));
73
+ const identity = build
74
+ ? { ZEN_IMAGE_BUILD: build.hash }
75
+ : { ZEN_IMAGE_BASE: base };
76
+ const dockerfile = agentDockerfile(base, identity);
77
+ writeFileSync(join(ctx, 'Dockerfile'), dockerfile);
78
+ // 3. Named by everything that went in, so an unchanged one is not built again.
79
+ const tag = `${IMAGE_REPO}:${contentHash(ctx, image.Id)}`;
80
+ const present = await runProcess('podman', ['image', 'exists', tag], { timeoutMs: 30_000 });
81
+ if (present.code === 0 && !opts.rebuild) {
82
+ return { tag, base, built: false };
83
+ }
84
+ note();
85
+ note(` ${bold(cyan('Building agent image'))}`);
86
+ for (const line of table([
87
+ ['Image', tag],
88
+ ['Base', base],
89
+ ]))
90
+ note(` ${dim(line)}`);
91
+ await streamAgentBuild('podman', ['build', '-t', tag, '-f', join(ctx, 'Dockerfile'), ctx], opts.verbose);
92
+ note(` ${green('✓ Agent image built')}`);
93
+ return { tag, base, built: true };
94
+ }
95
+ finally {
96
+ rmSync(ctx, { recursive: true, force: true });
97
+ }
98
+ }
99
+ /**
100
+ * Runs the agent image in podman and stays with it: its log here, its port published on this
101
+ * machine, a Ctrl-C or SIGTERM passed on so its runs save before it goes.
102
+ */
103
+ export async function runContainer(run) {
104
+ mkdirSync(run.root, { recursive: true, mode: 0o700 });
105
+ const rootless = (await podman(['info', '--format', '{{.Host.Security.Rootless}}'])).trim();
106
+ if (rootless !== 'true' && rootless !== 'false') {
107
+ throw new CliError(`could not determine whether podman is rootless: ${rootless}`, EXIT.sandbox);
108
+ }
109
+ const seed = await prepareMemorySeed(run.project.dir, run.root, run.memorySeed);
110
+ let containerId;
111
+ let stopResult;
112
+ const secretNames = [];
113
+ try {
114
+ const name = `zen-server-${run.project.id.replace(/[^\w.-]/g, '_')}-${run.listen.port}`;
115
+ const env = {
116
+ ...process.env,
117
+ ZEN_PROJECT_ID: run.project.id,
118
+ [HOST_MANAGED_ENV]: '1',
119
+ };
120
+ const args = [
121
+ 'run',
122
+ '--rm',
123
+ '--detach',
124
+ '--name',
125
+ name,
126
+ '--label',
127
+ 'zenera.server=1',
128
+ '--user',
129
+ `${AGENT_UID}:${AGENT_GID}`,
130
+ '--cap-drop',
131
+ 'ALL',
132
+ '--security-opt',
133
+ 'no-new-privileges',
134
+ ...(rootless === 'true'
135
+ ? ['--userns', `keep-id:uid=${AGENT_UID},gid=${AGENT_GID}`]
136
+ : []),
137
+ '--publish',
138
+ `${run.listen.host}:${run.listen.port}:3000`,
139
+ '--volume',
140
+ `${run.project.dir}:/project:ro`,
141
+ '--volume',
142
+ `${run.root}:/state`,
143
+ // Values by name only: podman reads them from its own environment, so no key is on a
144
+ // command line.
145
+ '--env',
146
+ 'ZEN_PROJECT_ID',
147
+ '--env',
148
+ HOST_MANAGED_ENV,
149
+ ];
150
+ const inner = [
151
+ 'server',
152
+ 'start',
153
+ '--host',
154
+ '0.0.0.0',
155
+ '--port',
156
+ '3000',
157
+ '--root',
158
+ '/state',
159
+ ];
160
+ if (seed) {
161
+ args.push('--volume', `${seed.dir}:/seed:ro`);
162
+ inner.push('--memory-seed', '/seed');
163
+ }
164
+ else {
165
+ inner.push('--no-memory-seed');
166
+ }
167
+ if (run.debug)
168
+ inner.push('--debug');
169
+ if (run.auth.mode === 'insecure') {
170
+ env.ZEN_SERVER_INSECURE_LOCAL = '1';
171
+ args.push('--env', 'ZEN_SERVER_INSECURE_LOCAL');
172
+ inner.push('--insecure');
173
+ }
174
+ else {
175
+ env.ZEN_SERVER_JWT_PUBLIC_KEY = run.auth.publicKey;
176
+ args.push('--env', 'ZEN_SERVER_JWT_PUBLIC_KEY');
177
+ inner.push('--jwt-issuer', run.auth.issuer, '--jwt-audience', run.auth.audience);
178
+ }
179
+ const modelCredentials = await modelKeys(run.project.dir);
180
+ for (const name of MODEL_CONTEXT_ENV) {
181
+ const value = process.env[name];
182
+ if (value) {
183
+ env[name] = value;
184
+ args.push('--env', name);
185
+ }
186
+ }
187
+ for (const forwarded of modelCredentials) {
188
+ if (forwarded.holds === 'secret') {
189
+ env[forwarded.env] = forwarded.value;
190
+ args.push('--env', forwarded.env);
191
+ }
192
+ else {
193
+ const name = `zen-server-${randomBytes(8).toString('hex')}-${forwarded.env.toLowerCase()}`;
194
+ const made = await runProcess('podman', ['secret', 'create', name, forwarded.value], {
195
+ timeoutMs: 30_000,
196
+ });
197
+ if (made.code !== 0) {
198
+ throw new CliError(`could not prepare ${forwarded.env}: ${made.stderr.trim() || made.stdout.trim()}`, EXIT.credentials, 'the host must be able to read the credential file');
199
+ }
200
+ secretNames.push(name);
201
+ env[forwarded.env] = `/run/secrets/${name}`;
202
+ args.push('--secret', `${name},type=mount,uid=${AGENT_UID},gid=${AGENT_GID},mode=0400`, '--env', forwarded.env);
203
+ }
204
+ }
205
+ args.push(run.image, ...inner);
206
+ const started = await runProcess('podman', args, { timeoutMs: 120_000, env });
207
+ if (started.code !== 0) {
208
+ throw new CliError(`could not start the agent container: ${(started.stderr.trim() || started.stdout.trim()).split('\n')[0]}`, EXIT.sandbox);
209
+ }
210
+ const id = started.stdout.trim();
211
+ containerId = id;
212
+ const logs = spawn('podman', ['logs', '--follow', name], {
213
+ stdio: ['ignore', 'inherit', 'inherit'],
214
+ });
215
+ run.onStarted?.();
216
+ let stopping = false;
217
+ const stop = async (signal) => {
218
+ if (stopping)
219
+ return;
220
+ stopping = true;
221
+ note();
222
+ note(` ${yellow('Stopping agent container')} ${dim(`(${signal})`)}`);
223
+ stopResult = runProcess('podman', ['stop', '--ignore', '--time', '25', id], {
224
+ timeoutMs: 60_000,
225
+ });
226
+ const stopped = await stopResult;
227
+ if (stopped.code !== 0) {
228
+ note(`could not stop the agent container: ${stopped.stderr.trim() || stopped.stdout.trim()}`);
229
+ }
230
+ };
231
+ const interrupt = () => void stop('SIGINT');
232
+ const terminate = () => void stop('SIGTERM');
233
+ process.once('SIGINT', interrupt);
234
+ process.once('SIGTERM', terminate);
235
+ await new Promise((done, reject) => {
236
+ logs.once('close', () => done());
237
+ logs.once('error', reject);
238
+ }).finally(() => {
239
+ process.removeListener('SIGINT', interrupt);
240
+ process.removeListener('SIGTERM', terminate);
241
+ });
242
+ if (!stopping) {
243
+ throw new CliError('the agent container stopped', EXIT.failed, `podman logs ${name}`);
244
+ }
245
+ }
246
+ finally {
247
+ if (containerId) {
248
+ const stopped = await (stopResult ??
249
+ runProcess('podman', ['stop', '--ignore', '--time', '25', containerId], {
250
+ timeoutMs: 60_000,
251
+ }));
252
+ if (stopped.code !== 0) {
253
+ throw new CliError(`could not stop the agent container: ${stopped.stderr.trim() || stopped.stdout.trim()}`, EXIT.failed, 'the startup memory snapshot and runtime credentials were retained until the container can be stopped');
254
+ }
255
+ }
256
+ try {
257
+ const failures = [];
258
+ for (const name of secretNames) {
259
+ const removed = await runProcess('podman', ['secret', 'rm', name], {
260
+ timeoutMs: 30_000,
261
+ });
262
+ if (removed.code !== 0) {
263
+ failures.push(`${name}: ${removed.stderr.trim() || removed.stdout.trim()}`);
264
+ }
265
+ }
266
+ if (failures.length) {
267
+ throw new CliError(`could not remove runtime credentials: ${failures.join('; ')}`, EXIT.failed, 'remove the reported secrets after the container stops: podman secret rm <name>');
268
+ }
269
+ }
270
+ finally {
271
+ await seed?.cleanup();
272
+ }
273
+ }
274
+ note(` ${green('✓ Server stopped')}`);
275
+ note();
276
+ }
277
+ /** The model keys this machine has, from the keyring and the environment, as a run reads them. */
278
+ async function modelKeys(projectDir) {
279
+ loadProjectEnv(projectDir);
280
+ const keys = await KeyStore.open();
281
+ keys.materialize();
282
+ const found = credentials();
283
+ const adc = !process.env.GOOGLE_APPLICATION_CREDENTIALS ? gcloudAdc() : undefined;
284
+ if (adc)
285
+ found.push({ env: 'GOOGLE_APPLICATION_CREDENTIALS', holds: 'file', value: adc });
286
+ return found;
287
+ }
288
+ const require = createRequire(import.meta.url);
289
+ /** Where an @zenera package this CLI runs is installed: the workspace, or node_modules. */
290
+ function packageDir(name) {
291
+ if (name === 'cli') {
292
+ return dirname(fileURLToPath(new URL('../package.json', import.meta.url)));
293
+ }
294
+ // Its entry, not its manifest: not every package exports ./package.json.
295
+ let dir = dirname(require.resolve(`@zenera/${name}`));
296
+ while (!existsSync(join(dir, 'package.json')) && dirname(dir) !== dir) {
297
+ dir = dirname(dir);
298
+ }
299
+ return dir;
300
+ }
301
+ async function pack(dir, into) {
302
+ const res = await runProcess('npm', ['pack', dir, '--pack-destination', into, '--ignore-scripts', '--silent'], { timeoutMs: 300_000 });
303
+ const file = res.stdout.trim().split('\n').at(-1);
304
+ if (res.code !== 0 || !file) {
305
+ throw new CliError(`could not pack ${dir}: ${(res.stderr.trim() || `exit ${res.code}`).split('\n').at(-1)}`, EXIT.failed);
306
+ }
307
+ return file;
308
+ }
309
+ /**
310
+ * The runtime's own package.json: the CLI from its tarball, and every @zenera package it needs
311
+ * forced to its tarball too — else npm would fetch the released ones and run other code.
312
+ */
313
+ function appManifest(tarballs) {
314
+ const file = (name) => `file:/opt/zenera/pkgs/${tarballs[name]}`;
315
+ return {
316
+ name: 'zenera-runtime',
317
+ private: true,
318
+ dependencies: { '@zenera/cli': file('@zenera/cli') },
319
+ overrides: Object.fromEntries(Object.keys(tarballs).map((name) => [name, file(name)])),
320
+ };
321
+ }
322
+ /** `NAME=value` lines as an object; the commands' starting environment. */
323
+ function envOf(lines = []) {
324
+ const env = {};
325
+ for (const line of lines) {
326
+ const at = line.indexOf('=');
327
+ if (at > 0)
328
+ env[line.slice(0, at)] = line.slice(at + 1);
329
+ }
330
+ return env;
331
+ }
332
+ export function agentDockerfile(base, identity) {
333
+ const entry = '/opt/zenera/app/node_modules/@zenera/cli/dist/main.js';
334
+ return `# Generated by zen server start --container. The project's environment, plus zen.
335
+ FROM docker.io/library/node:24-trixie-slim AS runtime
336
+ COPY pkgs/ /opt/zenera/pkgs/
337
+ COPY app.json /opt/zenera/app/package.json
338
+ RUN cd /opt/zenera/app \\
339
+ && npm install --omit=dev --ignore-scripts --no-audit --no-fund \\
340
+ && mkdir -p /opt/zenera/bin \\
341
+ && cp "$(command -v node)" /opt/zenera/bin/node \\
342
+ && rm -rf /opt/zenera/pkgs \\
343
+ && /opt/zenera/bin/node ${entry} version
344
+
345
+ FROM docker.io/library/alpine:3.22 AS bwrap
346
+ ARG BWRAP_VERSION=${BWRAP_VERSION}
347
+ RUN apk add --no-cache build-base meson ninja pkgconf libcap-dev libcap-static linux-headers curl xz
348
+ RUN mkdir -p /src && curl -fsSL https://github.com/containers/bubblewrap/releases/download/v\${BWRAP_VERSION}/bubblewrap-\${BWRAP_VERSION}.tar.xz \\
349
+ | tar -xJ -C /src --strip-components=1
350
+ RUN cd /src && meson setup build --buildtype=release --prefer-static --default-library=static \\
351
+ -Dc_link_args=-static -Dselinux=disabled -Dman=disabled -Dtests=false \\
352
+ -Dbash_completion=disabled -Dzsh_completion=disabled \\
353
+ && ninja -C build bwrap && strip build/bwrap
354
+
355
+ FROM ${base}
356
+ USER root
357
+ COPY --from=runtime /opt/zenera /opt/zenera
358
+ COPY --from=bwrap /src/build/bwrap /opt/zenera/bin/bwrap
359
+ COPY runtime/ /opt/zenera/runtime/
360
+ COPY etc/ /opt/zenera/etc/
361
+ # Mount points: the image's root is read-only to every command. Node needs glibc: a base
362
+ # without it fails here, not when the server starts.
363
+ RUN mkdir -p /project /state /workspace /home/agent /home/zenera \\
364
+ && chown ${AGENT_UID}:${AGENT_GID} /state /workspace /home/agent /home/zenera \\
365
+ && /opt/zenera/bin/node -e "process.exit(0)"
366
+ ENV HOME=/home/zenera
367
+ USER ${AGENT_UID}:${AGENT_GID}
368
+ ENV ${Object.entries(identity)
369
+ .map(([k, v]) => `${k}=${JSON.stringify(v)}`)
370
+ .join(' ')}
371
+ LABEL zenera.agent=1
372
+ ENTRYPOINT ["/opt/zenera/bin/node", "${entry}"]
373
+ CMD ["server", "start"]
374
+ `;
375
+ }
376
+ /** Everything that went into the image: the base's id and the context, file by file. */
377
+ function contentHash(ctx, baseId) {
378
+ const hash = createHash('sha256').update(baseId);
379
+ const walk = (rel) => {
380
+ for (const entry of readdirSync(join(ctx, rel), { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
381
+ const path = join(rel, entry.name);
382
+ if (entry.isDirectory())
383
+ walk(path);
384
+ else
385
+ hash.update(`\0${path}\0`).update(readFileSync(join(ctx, path)));
386
+ }
387
+ };
388
+ walk('');
389
+ return hash.digest('hex').slice(0, 12);
390
+ }
391
+ async function podman(args) {
392
+ const res = await runProcess('podman', args, { timeoutMs: 60_000, maxBytes: 4 * 1024 * 1024 });
393
+ if (res.code !== 0) {
394
+ throw new CliError(`podman ${args[0]} ${args[1] ?? ''}: ${(res.stderr.trim() || `exit ${res.code}`).split('\n')[0]}`, EXIT.sandbox);
395
+ }
396
+ return res.stdout;
397
+ }
398
+ //# sourceMappingURL=container.js.map
@@ -0,0 +1,2 @@
1
+ export declare function stageContainerCredentials(): Promise<void>;
2
+ //# sourceMappingURL=containerCredentials.d.ts.map
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Runtime staging for credential files mounted into an agent container.
3
+ * stageContainerCredentials copies only known credential files into the server's
4
+ * private, ephemeral zen home and rewrites their environment paths before engines open.
5
+ * Used by server commands in the image: bwrap can bind these container-owned copies
6
+ * when keys are allowed, without re-binding an external Podman secret mount.
7
+ */
8
+ import { credentials, home } from '@zenera/engine';
9
+ import { chmod, copyFile, mkdir, mkdtemp, rm } from 'node:fs/promises';
10
+ import { join } from 'node:path';
11
+ import { CliError, EXIT } from "./term.js";
12
+ export async function stageContainerCredentials() {
13
+ const files = credentials().filter((credential) => credential.holds === 'file');
14
+ if (!files.length)
15
+ return;
16
+ await mkdir(home(), { recursive: true, mode: 0o700 });
17
+ const dir = await mkdtemp(join(home(), '.server-credentials-'));
18
+ const staged = {};
19
+ try {
20
+ for (const file of files) {
21
+ const path = join(dir, `${file.env}.json`);
22
+ await copyFile(file.value, path);
23
+ await chmod(path, 0o600);
24
+ staged[file.env] = path;
25
+ }
26
+ Object.assign(process.env, staged);
27
+ }
28
+ catch (err) {
29
+ await rm(dir, { recursive: true, force: true });
30
+ throw new CliError(`cannot stage runtime credential files: ${err instanceof Error ? err.message : err}`, EXIT.credentials, 'credential files must be readable by the server; do not mount the whole host keyring');
31
+ }
32
+ }
33
+ //# sourceMappingURL=containerCredentials.js.map
package/dist/podman.d.ts CHANGED
@@ -64,6 +64,7 @@ export declare function ensureImage(target: {
64
64
  engine?: string;
65
65
  exec?: typeof runProcess;
66
66
  force?: boolean;
67
+ progress?: Pick<PrepareOptions, 'onProgress' | 'slow'>;
67
68
  }): Promise<void>;
68
69
  /** A sandbox's failure, as the CLI reports it. */
69
70
  export declare function asCliError(err: unknown): unknown;
package/dist/podman.js CHANGED
@@ -1,3 +1,9 @@
1
+ /**
2
+ * Host container-engine preflight used by server, sandbox and project setup commands.
3
+ * ensurePodmanReady checks the binary, machine and socket; ensureImage builds/pulls
4
+ * images with terminalProgress or caller-supplied progress, while asCliError surfaces
5
+ * sandbox failures using the CLI's standard error reporting.
6
+ */
1
7
  import { isBusy, isProjectDir, Registry, sessionIds, sessionsDir } from '@zenera/engine';
2
8
  import { ensurePodmanImage, isImageBuildError, pidAlive, runProcess, SandboxError, } from '@zenera/neo';
3
9
  import { readdirSync, readFileSync, statSync } from 'node:fs';
@@ -92,7 +98,7 @@ export function terminalProgress() {
92
98
  */
93
99
  export async function ensureImage(target, opts = {}) {
94
100
  try {
95
- await ensurePodmanImage(target, { engine: opts.engine, exec: opts.exec }, { ...terminalProgress(), force: opts.force });
101
+ await ensurePodmanImage(target, { engine: opts.engine, exec: opts.exec }, { ...(opts.progress ?? terminalProgress()), force: opts.force });
96
102
  }
97
103
  catch (err) {
98
104
  throw asCliError(err);
package/dist/seed.d.ts ADDED
@@ -0,0 +1,6 @@
1
+ export interface PreparedMemorySeed {
2
+ dir: string;
3
+ cleanup(): Promise<void>;
4
+ }
5
+ export declare function prepareMemorySeed(projectDir: string, serverRoot: string, selected?: string | null): Promise<PreparedMemorySeed | null>;
6
+ //# sourceMappingURL=seed.d.ts.map
package/dist/seed.js ADDED
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Startup memory snapshots for the server CLI and its host-side container launcher.
3
+ * prepareMemorySeed resolves the seed, captures committed SQLite/WAL data and attached
4
+ * files into a rollback-journal snapshot, and returns its path and cleanup function.
5
+ * New users copy this fixed seed; existing private user memories are never replaced.
6
+ */
7
+ import { copyMemory, isMemory, LEGACY_GRAPH_FILE, MEMORY_DB, memoryDir, readProjectConfig, } from '@zenera/neo';
8
+ import { existsSync } from 'node:fs';
9
+ import { chmod, mkdir, mkdtemp, readdir, rm } from 'node:fs/promises';
10
+ import { join } from 'node:path';
11
+ import { DatabaseSync } from 'node:sqlite';
12
+ import { CliError, EXIT } from "./term.js";
13
+ export async function prepareMemorySeed(projectDir, serverRoot, selected) {
14
+ if (selected === null)
15
+ return null;
16
+ let source = selected;
17
+ if (source === undefined) {
18
+ const { root, config } = readProjectConfig(projectDir);
19
+ source = memoryDir(root, config);
20
+ }
21
+ if (!source)
22
+ return null;
23
+ if (!isMemory(source)) {
24
+ if (existsSync(join(source, LEGACY_GRAPH_FILE))) {
25
+ throw new CliError(`the memory seed ${source} holds a version 1 memory`, EXIT.invalid, `convert it first: zen memory migrate --dir ${source}`);
26
+ }
27
+ // An uninitialized seed means every new user starts with empty memory.
28
+ return null;
29
+ }
30
+ await mkdir(serverRoot, { recursive: true, mode: 0o700 });
31
+ const dir = await mkdtemp(join(serverRoot, '.memory-seed-'));
32
+ const cleanup = () => rm(dir, { recursive: true, force: true });
33
+ try {
34
+ await copyMemory(source, dir);
35
+ const db = new DatabaseSync(join(dir, MEMORY_DB));
36
+ try {
37
+ db.exec('PRAGMA journal_mode = DELETE');
38
+ }
39
+ finally {
40
+ db.close();
41
+ }
42
+ await makeReadable(dir);
43
+ return { dir, cleanup };
44
+ }
45
+ catch (err) {
46
+ await cleanup();
47
+ throw new CliError(`cannot snapshot the memory seed ${source}: ${err instanceof Error ? err.message : err}`, EXIT.failed, 'the host must be able to read the seed and create SQLite WAL/SHM files beside it');
48
+ }
49
+ }
50
+ /** The root controls privacy; the mounted snapshot must be readable by image UID 10001. */
51
+ async function makeReadable(dir) {
52
+ await chmod(dir, 0o755);
53
+ for (const entry of await readdir(dir, { withFileTypes: true })) {
54
+ const path = join(dir, entry.name);
55
+ if (entry.isDirectory()) {
56
+ await makeReadable(path);
57
+ }
58
+ else if (entry.isFile()) {
59
+ await chmod(path, 0o644);
60
+ }
61
+ // Never chmod a copied symlink's target outside this snapshot.
62
+ }
63
+ }
64
+ //# sourceMappingURL=seed.js.map
@@ -0,0 +1,24 @@
1
+ import type { AgentImage } from './container.ts';
2
+ export declare const HOST_MANAGED_ENV = "ZEN_SERVER_HOST_MANAGED";
3
+ export interface ServerStartup {
4
+ project: string;
5
+ url: string;
6
+ root: string;
7
+ auth: 'jwt' | 'insecure';
8
+ sandbox: string;
9
+ image?: AgentImage;
10
+ runtimeUser?: string;
11
+ page?: string;
12
+ chatUser?: string;
13
+ }
14
+ export declare function printServerStarted(info: ServerStartup): void;
15
+ /** Keep the host's published address and paths out of the image's own ready message. */
16
+ export declare function hostManagedOutput(inAgentImage: boolean, env?: NodeJS.ProcessEnv): boolean;
17
+ /** A spinning row with elapsed time in a terminal, or one final row in a piped log. */
18
+ export declare function buildProgress(verbose?: boolean): {
19
+ line(line: string): void;
20
+ done(): void;
21
+ };
22
+ /** stdout and stderr are decoded independently so split chunks never corrupt build lines. */
23
+ export declare function streamAgentBuild(bin: string, args: readonly string[], verbose?: boolean): Promise<void>;
24
+ //# sourceMappingURL=serverDisplay.d.ts.map