@zenera/cli 1.1.59 → 1.2.2

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,255 @@
1
+ /**
2
+ * Release images for `zen server build`: the agent image plus the project and its memory seed,
3
+ * immutable, for Kubernetes. buildReleaseImage builds the agent image (container.ts), stages a
4
+ * context (snapshotProject, the seed from seed.ts, --add trees via copyTree), generates
5
+ * releaseDockerfile, builds `localhost/zenera-release:<hash>` and optionally pushes it
6
+ * (pushImage) to report its digest. parseAdd and checkRelease validate the command's flags.
7
+ * Used by commands/server.ts; deploy-time settings (plugins, keys, URLs) are never baked in.
8
+ */
9
+ import { home } from '@zenera/engine';
10
+ import { memoryDir, readProjectConfig } from '@zenera/neo';
11
+ import { runProcess } from '@zenera/sandbox';
12
+ import { randomBytes } from 'node:crypto';
13
+ import { constants, existsSync, readFileSync } from 'node:fs';
14
+ import { chmod, copyFile, lstat, mkdir, readdir, rename, rm, writeFile } from 'node:fs/promises';
15
+ import { basename, dirname, isAbsolute, join, posix, relative, resolve, sep } from 'node:path';
16
+ import { collect } from "./archive.js";
17
+ import { AGENT_GID, AGENT_UID, buildAgentImage, contentHash, } from "./container.js";
18
+ import { prepareMemorySeed } from "./seed.js";
19
+ import { streamAgentBuild } from "./serverDisplay.js";
20
+ import { bold, CliError, cyan, dim, EXIT, green, note, table, usageError } from "./term.js";
21
+ const IMAGE_REPO = 'localhost/zenera-release';
22
+ const RELEASE_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
23
+ /** Where the image keeps its own things: an --add must not land on (or over) any of them. */
24
+ export const RESERVED_DESTINATIONS = [
25
+ '/project',
26
+ '/seed',
27
+ '/state',
28
+ '/workspace',
29
+ '/opt/zenera/app',
30
+ '/opt/zenera/bin',
31
+ ];
32
+ /** `<src>:<dest>`: src resolved against cwd and present, dest an absolute path of its own. */
33
+ export function parseAdd(spec, cwd) {
34
+ const at = spec.lastIndexOf(':');
35
+ const usage = '--add <src>:<dest>, e.g. --add ./plugins:/opt/zenera/plugins';
36
+ if (at <= 0 || at === spec.length - 1) {
37
+ throw usageError(`not <src>:<dest>: ${spec}`, usage);
38
+ }
39
+ const src = resolve(cwd, spec.slice(0, at));
40
+ const raw = spec.slice(at + 1);
41
+ if (!raw.startsWith('/')) {
42
+ throw usageError(`--add destination must be absolute: ${raw}`, usage);
43
+ }
44
+ if (/\s/.test(raw)) {
45
+ throw usageError(`--add destination must not contain whitespace: ${raw}`, usage);
46
+ }
47
+ if (raw.split('/').includes('..')) {
48
+ throw usageError(`--add destination must not contain '..': ${raw}`, usage);
49
+ }
50
+ const dest = raw.length > 1 ? raw.replace(/\/+$/, '') : raw;
51
+ if (posix.normalize(dest) !== dest) {
52
+ throw usageError(`--add destination is not normalized: ${raw}`, usage);
53
+ }
54
+ // On a reserved path, under one, or over one (`/opt/zenera` would replace its app).
55
+ const clash = RESERVED_DESTINATIONS.find((r) => dest === r || dest.startsWith(`${r}/`) || r.startsWith(dest === '/' ? '/' : `${dest}/`));
56
+ if (clash) {
57
+ throw usageError(`--add destination ${dest} would overlay ${clash}`, `the image keeps ${RESERVED_DESTINATIONS.join(', ')} for itself`);
58
+ }
59
+ if (!existsSync(src)) {
60
+ throw usageError(`--add source does not exist: ${src}`, usage);
61
+ }
62
+ return { src, dest };
63
+ }
64
+ /** A release id as given, checked; the default comes from the content (`r-<hash>`). */
65
+ export function checkRelease(id) {
66
+ if (!RELEASE_ID.test(id)) {
67
+ throw usageError(`not a release id: ${id}`, 'letters, digits, ".", "_" and "-", starting with a letter or digit, at most 64');
68
+ }
69
+ return id;
70
+ }
71
+ /** Image-readable modes: dirs 0755, files 0644, or 0755 when the source is executable. */
72
+ export function releaseMode(mode, isDir) {
73
+ return isDir || mode & 0o111 ? 0o755 : 0o644;
74
+ }
75
+ async function copyOne(src, dest, mode) {
76
+ await mkdir(dirname(dest), { recursive: true });
77
+ // A clone where the filesystem has them; a plain copy where it does not.
78
+ await copyFile(src, dest, constants.COPYFILE_FICLONE);
79
+ await chmod(dest, releaseMode(mode, false));
80
+ }
81
+ /** Directories in `into` made 0755 all the way down (mkdir's modes honour the umask). */
82
+ async function openDirs(into) {
83
+ await chmod(into, 0o755);
84
+ for (const entry of await readdir(into, { withFileTypes: true })) {
85
+ if (entry.isDirectory())
86
+ await openDirs(join(into, entry.name));
87
+ }
88
+ }
89
+ /**
90
+ * The project as the image carries it: what `zen export` would (no `.env`, sessions, `.git`,
91
+ * `node_modules`, scratch, locks, links), minus its memory, which travels as the seed.
92
+ */
93
+ export async function snapshotProject(projectDir, into) {
94
+ const dir = resolve(projectDir);
95
+ const { root, config } = readProjectConfig(dir);
96
+ const memory = memoryDir(root, config);
97
+ const memoryRel = memory && !relative(dir, memory).startsWith('..') && !isAbsolute(relative(dir, memory))
98
+ ? relative(dir, memory).split(sep).join('/')
99
+ : undefined;
100
+ await mkdir(into, { recursive: true });
101
+ let count = 0;
102
+ for (const file of collect(dir, { memory: false }).files) {
103
+ if (memoryRel && (file.rel === memoryRel || file.rel.startsWith(`${memoryRel}/`)))
104
+ continue;
105
+ await copyOne(file.abs, join(into, ...file.rel.split('/')), file.mode);
106
+ count++;
107
+ }
108
+ await openDirs(into);
109
+ return count;
110
+ }
111
+ /** A file or a tree, copied with image-readable modes; links are not followed. */
112
+ export async function copyTree(src, into) {
113
+ const stat = await lstat(src);
114
+ if (stat.isSymbolicLink())
115
+ return;
116
+ if (stat.isDirectory()) {
117
+ await mkdir(into, { recursive: true });
118
+ await chmod(into, 0o755);
119
+ for (const entry of await readdir(src)) {
120
+ await copyTree(join(src, entry), join(into, entry));
121
+ }
122
+ }
123
+ else if (stat.isFile()) {
124
+ await copyOne(src, into, stat.mode);
125
+ }
126
+ }
127
+ export function releaseDockerfile(agentTag, opts) {
128
+ const lines = [
129
+ '# Generated by zen server build. A release: the agent image plus the project.',
130
+ `FROM ${agentTag}`,
131
+ 'USER root',
132
+ 'COPY project/ /project/',
133
+ ...(opts.seed ? ['COPY seed/ /seed/'] : []),
134
+ ...opts.adds.map((a) => `COPY ${a.ctxPath} ${a.dest}`),
135
+ `USER ${AGENT_UID}:${AGENT_GID}`,
136
+ `ENV ZEN_RELEASE=${JSON.stringify(opts.release)} ZEN_PROJECT_ID=${JSON.stringify(opts.projectId)}`,
137
+ `LABEL zenera.release=${JSON.stringify(opts.release)} zenera.project=${JSON.stringify(opts.projectId)}`,
138
+ ];
139
+ return `${lines.join('\n')}\n`;
140
+ }
141
+ /** The arguments of `podman push`, the reference as podman wants it. */
142
+ export function pushArgs(tag, push, digestFile) {
143
+ const ref = push.ref.replace(/^docker:\/\//, '');
144
+ return [
145
+ 'push',
146
+ '--digestfile',
147
+ digestFile,
148
+ ...(push.authfile ? ['--authfile', push.authfile] : []),
149
+ ...(push.insecure ? ['--tls-verify=false'] : []),
150
+ tag,
151
+ `docker://${ref}`,
152
+ ];
153
+ }
154
+ /** Pushes the image and returns its manifest digest (`sha256:…`). */
155
+ export async function pushImage(tag, push, digestFile) {
156
+ const res = await runProcess('podman', pushArgs(tag, push, digestFile), {
157
+ timeoutMs: 60 * 60_000,
158
+ maxBytes: 1024 * 1024,
159
+ });
160
+ if (res.code !== 0) {
161
+ // podman prints progress first; the reason is its `Error:` line.
162
+ const lines = (res.stderr.trim() || res.stdout.trim() || `exit ${res.code}`).split('\n');
163
+ const first = (lines.find((l) => /^Error\b/i.test(l.trim())) ?? lines[0]).trim();
164
+ throw new CliError(`could not push ${tag} to ${push.ref}: ${first}`, EXIT.failed, 'log in first (podman login <registry>), or give --authfile <file>; ' +
165
+ 'for a plain-HTTP registry, --insecure-registry');
166
+ }
167
+ let digest = '';
168
+ try {
169
+ digest = readFileSync(digestFile, 'utf8').trim();
170
+ }
171
+ catch {
172
+ // Checked below.
173
+ }
174
+ if (!/^sha256:[0-9a-f]{64}$/.test(digest)) {
175
+ throw new CliError(`pushed ${push.ref}, but podman reported no digest${digest ? `: ${digest}` : ''}`, EXIT.failed);
176
+ }
177
+ return digest;
178
+ }
179
+ /** The release image for a project: the agent image built first, then the project on top. */
180
+ export async function buildReleaseImage(projectDir, opts = {}) {
181
+ const agent = await buildAgentImage(projectDir, {
182
+ rebuild: opts.rebuild,
183
+ verbose: opts.verbose,
184
+ });
185
+ return buildRelease(projectDir, agent, opts);
186
+ }
187
+ /** The release step alone, on an agent image already built. */
188
+ export async function buildRelease(projectDir, agent, opts = {}) {
189
+ const inspected = await runProcess('podman', ['image', 'inspect', '--format', '{{.Id}}', agent.tag], {
190
+ timeoutMs: 60_000,
191
+ });
192
+ const agentId = inspected.stdout.trim();
193
+ if (inspected.code !== 0 || !agentId) {
194
+ throw new CliError(`cannot inspect the agent image ${agent.tag}: ${(inspected.stderr.trim() || `exit ${inspected.code}`).split('\n')[0]}`, EXIT.sandbox);
195
+ }
196
+ const projectId = opts.projectId ?? basename(resolve(projectDir));
197
+ const ctx = join(home(), 'images', `release-ctx-${randomBytes(4).toString('hex')}`);
198
+ await mkdir(ctx, { recursive: true });
199
+ try {
200
+ await snapshotProject(projectDir, join(ctx, 'project'));
201
+ const seed = await prepareMemorySeed(projectDir, ctx, opts.memorySeed);
202
+ if (seed)
203
+ await rename(seed.dir, join(ctx, 'seed'));
204
+ const adds = [];
205
+ for (const [n, add] of (opts.adds ?? []).entries()) {
206
+ const isDir = (await lstat(add.src)).isDirectory();
207
+ const ctxPath = isDir ? `add/${n}/` : `add/${n}/file`;
208
+ await mkdir(join(ctx, 'add', String(n)), { recursive: true });
209
+ await copyTree(add.src, join(ctx, ...ctxPath.split('/').filter(Boolean)));
210
+ adds.push({ ctxPath, dest: isDir ? `${add.dest}/` : add.dest });
211
+ }
212
+ if (existsSync(join(ctx, 'add')))
213
+ await openDirs(join(ctx, 'add'));
214
+ // The default release is named by what it holds, so the same content is the same release.
215
+ const release = opts.release ??
216
+ `r-${contentHash(ctx, [agentId, ...adds.map((a) => `${a.ctxPath}>${a.dest}`)].join('\0'))}`;
217
+ checkRelease(release);
218
+ await writeFile(join(ctx, 'Dockerfile'), releaseDockerfile(agent.tag, { release, projectId, seed: Boolean(seed), adds }));
219
+ const image = `${IMAGE_REPO}:${contentHash(ctx, `${agentId}\0${release}`)}`;
220
+ const present = await runProcess('podman', ['image', 'exists', image], {
221
+ timeoutMs: 30_000,
222
+ });
223
+ const built = present.code !== 0 || Boolean(opts.rebuild);
224
+ if (built) {
225
+ note();
226
+ note(` ${bold(cyan('Building release image'))}`);
227
+ for (const line of table([
228
+ ['Release', release],
229
+ ['Image', image],
230
+ ['Agent', agent.tag],
231
+ ]))
232
+ note(` ${dim(line)}`);
233
+ await streamAgentBuild('podman', ['build', '-t', image, '-f', join(ctx, 'Dockerfile'), ctx], opts.verbose);
234
+ note(` ${green('✓ Release image built')}`);
235
+ }
236
+ const result = {
237
+ release,
238
+ image,
239
+ agentImage: agent.tag,
240
+ base: agent.base,
241
+ built,
242
+ };
243
+ if (opts.push) {
244
+ note(` ${dim(`Pushing ${image} to ${opts.push.ref}…`)}`);
245
+ result.ref = opts.push.ref.replace(/^docker:\/\//, '');
246
+ result.digest = await pushImage(image, opts.push, join(ctx, 'digest'));
247
+ note(` ${green('✓ Pushed')} ${dim(result.digest)}`);
248
+ }
249
+ return result;
250
+ }
251
+ finally {
252
+ await rm(ctx, { recursive: true, force: true });
253
+ }
254
+ }
255
+ //# sourceMappingURL=release.js.map
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
@@ -0,0 +1,161 @@
1
+ /**
2
+ * Terminal presentation shared by direct and container-based server startup.
3
+ * printServerStarted renders the runtime summary and browser link; streamAgentBuild
4
+ * uses animated compact build progress by default and full grouped logs with --verbose.
5
+ * HOST_MANAGED_ENV lets the image report readiness without repeating the host summary.
6
+ */
7
+ import { spawn } from 'node:child_process';
8
+ import { createInterface } from 'node:readline';
9
+ import { bold, CliError, cut, cyan, dim, EXIT, green, note, plain, progress, red, table, warn, write, yellow, } from "./term.js";
10
+ export const HOST_MANAGED_ENV = 'ZEN_SERVER_HOST_MANAGED';
11
+ export function printServerStarted(info) {
12
+ note();
13
+ note(` ${green(bold(info.image ? '✓ Container started' : '✓ Server ready'))}`);
14
+ note();
15
+ const rows = [
16
+ ['Project', bold(info.project)],
17
+ ['HTTP', cyan(info.url)],
18
+ [
19
+ 'Auth',
20
+ info.auth === 'insecure'
21
+ ? yellow('insecure · JWT signatures not checked')
22
+ : green('JWT · EdDSA verified'),
23
+ ],
24
+ ['Sandbox', info.sandbox],
25
+ ['State', dim(info.root)],
26
+ ['Memory', 'private per user · shared across sessions'],
27
+ ];
28
+ if (info.runtimeUser)
29
+ rows.push(['Process', info.runtimeUser]);
30
+ if (info.image) {
31
+ rows.push([
32
+ 'Image',
33
+ `${cyan(info.image.tag)} ${dim(info.image.built ? '(just built)' : '(cached)')}`,
34
+ ], ['Base', dim(info.image.base)]);
35
+ }
36
+ if (info.page)
37
+ rows.push(['Chat user', bold(info.chatUser ?? 'local')]);
38
+ for (const line of table(rows.map(([label, value]) => [dim(label), value]))) {
39
+ note(` ${line}`);
40
+ }
41
+ if (info.auth === 'insecure') {
42
+ note();
43
+ warn('Anyone with access can impersonate any user. Local testing only.');
44
+ }
45
+ if (info.page) {
46
+ write();
47
+ write(` ${bold('Test chat')}`);
48
+ write(` ${cyan(info.page)}`);
49
+ write();
50
+ }
51
+ note();
52
+ note(dim(' Press Ctrl+C to stop gracefully and save active runs.'));
53
+ note();
54
+ }
55
+ /** Keep the host's published address and paths out of the image's own ready message. */
56
+ export function hostManagedOutput(inAgentImage, env = process.env) {
57
+ return inAgentImage && env[HOST_MANAGED_ENV] === '1';
58
+ }
59
+ const BUILD_ERROR = /^(?:error\b|npm (?:err!|error)\b)|\b(?:fatal error|failed to)\b/i;
60
+ const BUILD_WARNING = /\b(?:warn|warning|deprecated)\b/i;
61
+ function buildLinePrinter() {
62
+ let stage;
63
+ return (line) => {
64
+ const step = /^(\s*(?:\[(\d+)\/(\d+)\] )?STEP \d+\/\d+:)(.*)/.exec(line);
65
+ if (step?.[2] && stage !== step[2]) {
66
+ stage = step[2];
67
+ const name = /\bAS\s+(\S+)/i.exec(step[4])?.[1] ?? 'agent image';
68
+ note();
69
+ note(` ${bold(cyan(`Build stage ${step[2]}/${step[3]} · ${name}`))}`);
70
+ }
71
+ const text = step
72
+ ? `${bold(cyan(step[1]))}${dim(step[4])}`
73
+ : BUILD_ERROR.test(line.trimStart())
74
+ ? red(line)
75
+ : BUILD_WARNING.test(line)
76
+ ? yellow(line)
77
+ : /^(?:Successfully tagged|Successfully built)/i.test(line)
78
+ ? green(line)
79
+ : dim(line);
80
+ note(line ? ` ${text}` : '');
81
+ };
82
+ }
83
+ /** A spinning row with elapsed time in a terminal, or one final row in a piped log. */
84
+ export function buildProgress(verbose = false) {
85
+ const print = buildLinePrinter();
86
+ const bar = progress();
87
+ const tty = Boolean(process.stderr.isTTY);
88
+ const started = Date.now();
89
+ const frames = ['|', '/', '-', '\\'];
90
+ let frame = 0;
91
+ let last = '';
92
+ let finished = false;
93
+ const render = () => {
94
+ const seconds = Math.floor((Date.now() - started) / 1000);
95
+ const text = `${frames[frame++ % frames.length]} ${seconds}s ${last || 'Building…'}`;
96
+ bar.update(` ${dim(plain(cut(text, Math.max(1, (process.stderr.columns || 100) - 2))))}`);
97
+ };
98
+ const timer = !verbose && tty ? setInterval(render, 150) : undefined;
99
+ timer?.unref();
100
+ if (timer)
101
+ render();
102
+ return {
103
+ line(line) {
104
+ if (finished)
105
+ return;
106
+ if (verbose) {
107
+ print(line);
108
+ return;
109
+ }
110
+ if (!line.trim())
111
+ return;
112
+ if (BUILD_ERROR.test(line.trimStart()) || BUILD_WARNING.test(line)) {
113
+ bar.done();
114
+ print(line);
115
+ last = '';
116
+ return;
117
+ }
118
+ last = line;
119
+ if (tty)
120
+ render();
121
+ },
122
+ done() {
123
+ if (finished)
124
+ return;
125
+ finished = true;
126
+ if (timer)
127
+ clearInterval(timer);
128
+ bar.done();
129
+ if (!verbose && !tty && last)
130
+ note(` ${dim(plain(cut(last, 120)))}`);
131
+ last = '';
132
+ },
133
+ };
134
+ }
135
+ /** stdout and stderr are decoded independently so split chunks never corrupt build lines. */
136
+ export function streamAgentBuild(bin, args, verbose = false) {
137
+ const output = buildProgress(verbose);
138
+ return new Promise((done, fail) => {
139
+ const child = spawn(bin, [...args], { stdio: ['ignore', 'pipe', 'pipe'] });
140
+ const tail = [];
141
+ const show = (line) => {
142
+ if (line.trim()) {
143
+ tail.push(line);
144
+ if (tail.length > 20)
145
+ tail.shift();
146
+ }
147
+ output.line(line);
148
+ };
149
+ createInterface({ input: child.stdout, crlfDelay: Infinity })
150
+ .on('line', show)
151
+ .on('error', fail);
152
+ createInterface({ input: child.stderr, crlfDelay: Infinity })
153
+ .on('line', show)
154
+ .on('error', fail);
155
+ child.once('error', fail);
156
+ child.once('close', (code) => code === 0
157
+ ? done()
158
+ : fail(new CliError(`the agent image did not build (exit ${code})`, EXIT.sandbox, tail.slice(-3).join('\n'))));
159
+ }).finally(() => output.done());
160
+ }
161
+ //# sourceMappingURL=serverDisplay.js.map
@@ -0,0 +1,5 @@
1
+ export declare function generateServerKeys(prefix: string): {
2
+ privateKey: string;
3
+ publicKey: string;
4
+ };
5
+ //# sourceMappingURL=serverKeys.d.ts.map
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Ed25519 key-pair generation for standalone secure runtime callers.
3
+ * generateServerKeys writes exclusive PKCS#8 private and SPKI public PEM files,
4
+ * removing files it created if generation cannot finish. Used by zen server keygen;
5
+ * only the public key belongs on the runtime, never the signing private key.
6
+ */
7
+ import { generateKeyPairSync } from 'node:crypto';
8
+ import { closeSync, fchmodSync, openSync, rmSync, writeFileSync } from 'node:fs';
9
+ import { CliError, EXIT } from "./term.js";
10
+ export function generateServerKeys(prefix) {
11
+ const paths = {
12
+ privateKey: `${prefix}.private.pem`,
13
+ publicKey: `${prefix}.public.pem`,
14
+ };
15
+ const created = [];
16
+ try {
17
+ const pair = generateKeyPairSync('ed25519', {
18
+ privateKeyEncoding: { type: 'pkcs8', format: 'pem' },
19
+ publicKeyEncoding: { type: 'spki', format: 'pem' },
20
+ });
21
+ for (const [path, pem, mode] of [
22
+ [paths.privateKey, pair.privateKey, 0o600],
23
+ [paths.publicKey, pair.publicKey, 0o644],
24
+ ]) {
25
+ const fd = openSync(path, 'wx', mode);
26
+ created.push(path);
27
+ try {
28
+ fchmodSync(fd, mode);
29
+ writeFileSync(fd, pem);
30
+ }
31
+ finally {
32
+ closeSync(fd);
33
+ }
34
+ }
35
+ return paths;
36
+ }
37
+ catch (err) {
38
+ const failures = [];
39
+ for (const path of created) {
40
+ try {
41
+ rmSync(path);
42
+ }
43
+ catch (cleanup) {
44
+ failures.push(`${path}: ${cleanup instanceof Error ? cleanup.message : cleanup}`);
45
+ }
46
+ }
47
+ const exists = err instanceof Error && 'code' in err && err.code === 'EEXIST';
48
+ throw new CliError(`cannot generate server keys: ${err instanceof Error ? err.message : err}${failures.length ? `; cleanup failed: ${failures.join('; ')}` : ''}`, EXIT.credentials, exists
49
+ ? 'existing files are never overwritten; choose a new --out prefix'
50
+ : 'use an --out prefix in an existing writable directory');
51
+ }
52
+ }
53
+ //# sourceMappingURL=serverKeys.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zenera/cli",
3
- "version": "1.1.59",
3
+ "version": "1.2.2",
4
4
  "description": "Command-line front end for @zenera/neo: agentic projects you can run, share and commit.",
5
5
  "keywords": [
6
6
  "agents",
@@ -38,7 +38,8 @@
38
38
  "dist",
39
39
  "!dist/**/*.map",
40
40
  "postinstall.mjs",
41
- "templates"
41
+ "templates",
42
+ "assets"
42
43
  ],
43
44
  "engines": {
44
45
  "node": ">=24"
@@ -54,9 +55,11 @@
54
55
  "@google/genai": "^2.30.0",
55
56
  "@inkjs/ui": "^2.0.0",
56
57
  "@openrouter/sdk": "^1.4.25",
57
- "@zenera/engine": "^1.1.59",
58
- "@zenera/neo": "^1.1.59",
59
- "@zenera/view": "^1.1.59",
58
+ "@zenera/engine": "^1.2.2",
59
+ "@zenera/neo": "^1.2.2",
60
+ "@zenera/sandbox": "^1.2.2",
61
+ "@zenera/server": "^1.2.2",
62
+ "@zenera/view": "^1.2.2",
60
63
  "google-auth-library": "^10.0.0",
61
64
  "ink": "^7.1.1",
62
65
  "openai": "^6.0.0",