@zenera/cli 1.2.1 → 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.
- package/dist/commands/server.js +99 -9
- package/dist/container.d.ts +2 -0
- package/dist/container.js +1 -1
- package/dist/release.d.ts +72 -0
- package/dist/release.js +255 -0
- package/package.json +6 -6
package/dist/commands/server.js
CHANGED
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Server command entry point used by the CLI dispatcher.
|
|
3
|
-
* server dispatches start/check/status/token/keygen; start and startContainer launch
|
|
4
|
-
* the runtime with a fixed seed, token prints a dev JWT,
|
|
3
|
+
* server dispatches start/check/status/token/keygen/build; start and startContainer launch
|
|
4
|
+
* the runtime with a fixed seed, token prints a dev JWT, keygen writes an Ed25519 pair, and
|
|
5
|
+
* build makes (and optionally pushes) a release image with the project baked in (release.ts).
|
|
5
6
|
* On insecure startup, --user only
|
|
6
7
|
* chooses the sub claim for the printed browser link (default local); every API
|
|
7
8
|
* request still selects its user through its own JWT, not a server-wide user setting.
|
|
8
9
|
*/
|
|
9
10
|
import { home } from '@zenera/engine';
|
|
10
|
-
import { readFileSync } from 'node:fs';
|
|
11
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
11
12
|
import { join, resolve } from 'node:path';
|
|
12
13
|
import { parse } from "../args.js";
|
|
13
14
|
import { chatPage, chatUrl } from "../chat.js";
|
|
@@ -15,13 +16,16 @@ import { AGENT_GID, AGENT_UID, buildAgentImage, runContainer } from "../containe
|
|
|
15
16
|
import { stageContainerCredentials } from "../containerCredentials.js";
|
|
16
17
|
import { asCliError, ensurePodmanReady } from "../podman.js";
|
|
17
18
|
import { project as resolveProject } from "../resolve.js";
|
|
19
|
+
import { buildReleaseImage, checkRelease, parseAdd } from "../release.js";
|
|
18
20
|
import { preflight } from "../sandbox.js";
|
|
19
21
|
import { prepareMemorySeed } from "../seed.js";
|
|
20
22
|
import { generateServerKeys } from "../serverKeys.js";
|
|
21
23
|
import { hostManagedOutput, printServerStarted } from "../serverDisplay.js";
|
|
22
|
-
import { CliError, dim, EXIT, green, json, note, red, usageError, write, yellow } from "../term.js";
|
|
23
|
-
const USAGE = 'zen server <start|check|status|token|keygen> [options]';
|
|
24
|
-
const SUBCOMMANDS = ['start', 'check', 'status', 'token', 'keygen'];
|
|
24
|
+
import { bold, CliError, cyan, dim, EXIT, green, json, note, red, table, usageError, write, yellow, } from "../term.js";
|
|
25
|
+
const USAGE = 'zen server <start|check|status|build|token|keygen> [options]';
|
|
26
|
+
const SUBCOMMANDS = ['start', 'check', 'status', 'build', 'token', 'keygen'];
|
|
27
|
+
/** Where a release image keeps the memory seed it was built with. */
|
|
28
|
+
const RELEASE_SEED = '/seed';
|
|
25
29
|
/**
|
|
26
30
|
* The agent server: a project's chats over HTTP, for every user its host vouches for. What the
|
|
27
31
|
* agent image runs (`/opt/zenera/bin/zen server start`); `@zenera/server` is loaded only here,
|
|
@@ -47,6 +51,9 @@ export const server = {
|
|
|
47
51
|
' <prefix>.private.pem (0600) and <prefix>.public.pem.',
|
|
48
52
|
' Existing files are never overwritten. Keep the private',
|
|
49
53
|
' key with the trusted caller, not the runtime.',
|
|
54
|
+
' build A release image: the agent image plus the project and',
|
|
55
|
+
' its memory seed, baked in (never .env, sessions, .git).',
|
|
56
|
+
' Prints its digest when pushed, else its local tag.',
|
|
50
57
|
'',
|
|
51
58
|
' --port <n> Default $ZEN_SERVER_PORT, else 3000.',
|
|
52
59
|
' --host <addr> Default $ZEN_SERVER_HOST, else 127.0.0.1.',
|
|
@@ -82,7 +89,18 @@ export const server = {
|
|
|
82
89
|
' --token <jwt> With status: the token to send (default: an unsigned one,',
|
|
83
90
|
' which an --insecure server takes).',
|
|
84
91
|
'',
|
|
92
|
+
' --release <id> With build: the release id ([A-Za-z0-9._-], at most 64);',
|
|
93
|
+
' default r-<hash of its content>. In the image: $ZEN_RELEASE.',
|
|
94
|
+
' --push <ref> With build: push to a registry, e.g. registry:5000/agent:r42.',
|
|
95
|
+
' --authfile <file> With --push: podman’s auth file for the registry.',
|
|
96
|
+
' --insecure-registry With --push: plain HTTP / unverified TLS (in-cluster registry).',
|
|
97
|
+
' --add <src>:<dest> With build: copy src into the image at dest (absolute, not',
|
|
98
|
+
' /project, /seed, /state, /workspace, /opt/zenera/{app,bin}).',
|
|
99
|
+
' Repeatable; for large plugins.',
|
|
100
|
+
'',
|
|
85
101
|
'Model keys come from the keyring and the environment, as for zen run.',
|
|
102
|
+
'Many servers per project: ZEN_STATE_STORE=<module> keeps users in a store (e.g. S3);',
|
|
103
|
+
'the host lists, releases and drains them through /api/admin.',
|
|
86
104
|
],
|
|
87
105
|
run: async (ctx) => {
|
|
88
106
|
const { values, positionals } = parse(ctx.args, {
|
|
@@ -108,6 +126,11 @@ export const server = {
|
|
|
108
126
|
name: { type: 'string' },
|
|
109
127
|
thread: { type: 'string' },
|
|
110
128
|
out: { type: 'string' },
|
|
129
|
+
release: { type: 'string' },
|
|
130
|
+
push: { type: 'string' },
|
|
131
|
+
authfile: { type: 'string' },
|
|
132
|
+
'insecure-registry': { type: 'boolean' },
|
|
133
|
+
add: { type: 'string', multiple: true },
|
|
111
134
|
}, USAGE);
|
|
112
135
|
const what = positionals[0];
|
|
113
136
|
if (!what || !SUBCOMMANDS.includes(what)) {
|
|
@@ -127,6 +150,8 @@ export const server = {
|
|
|
127
150
|
return token(values);
|
|
128
151
|
case 'keygen':
|
|
129
152
|
return keygen(ctx, values);
|
|
153
|
+
case 'build':
|
|
154
|
+
return build(ctx, values);
|
|
130
155
|
}
|
|
131
156
|
},
|
|
132
157
|
};
|
|
@@ -199,13 +224,19 @@ function whichRoot(ctx, values, env, mod, project) {
|
|
|
199
224
|
return '/state';
|
|
200
225
|
return join(home(), 'servers', project.replace(/[^\w.@-]/g, '_'));
|
|
201
226
|
}
|
|
202
|
-
|
|
227
|
+
/**
|
|
228
|
+
* --memory-seed, --no-memory-seed, else the project's own memory — in a release image, the seed
|
|
229
|
+
* baked in at /seed (its /project carries no memory).
|
|
230
|
+
*/
|
|
231
|
+
function whichSeed(ctx, values, inAgentImage = false) {
|
|
203
232
|
if (values['no-memory-seed']) {
|
|
204
233
|
if (values['memory-seed'])
|
|
205
234
|
throw usageError('--memory-seed or --no-memory-seed', USAGE);
|
|
206
235
|
return null;
|
|
207
236
|
}
|
|
208
|
-
|
|
237
|
+
if (values['memory-seed'])
|
|
238
|
+
return resolve(ctx.cwd, values['memory-seed']);
|
|
239
|
+
return inAgentImage && existsSync(RELEASE_SEED) ? RELEASE_SEED : undefined;
|
|
209
240
|
}
|
|
210
241
|
async function options(ctx, values, env = process.env) {
|
|
211
242
|
const mod = await load();
|
|
@@ -222,7 +253,7 @@ async function options(ctx, values, env = process.env) {
|
|
|
222
253
|
projectDir: project.dir,
|
|
223
254
|
projectId,
|
|
224
255
|
root: whichRoot(ctx, values, env, mod, projectId),
|
|
225
|
-
memorySeed: whichSeed(ctx, values),
|
|
256
|
+
memorySeed: whichSeed(ctx, values, mod.inAgentImage()),
|
|
226
257
|
auth: whichAuth(ctx, values, env, mod),
|
|
227
258
|
debug: Boolean(values.debug ?? truthy(env.ZEN_SERVER_DEBUG)),
|
|
228
259
|
sandbox: sandboxName,
|
|
@@ -235,6 +266,12 @@ async function options(ctx, values, env = process.env) {
|
|
|
235
266
|
: {}),
|
|
236
267
|
hidden: [],
|
|
237
268
|
plugins: mod.envRunPlugins(env),
|
|
269
|
+
// Where users' data lives beyond this disk (ZEN_STATE_STORE), and the soft limits.
|
|
270
|
+
stateStore: await mod.envStateStore(env, {
|
|
271
|
+
projectId,
|
|
272
|
+
root: whichRoot(ctx, values, env, mod, projectId),
|
|
273
|
+
}),
|
|
274
|
+
...mod.envServerLimits(env),
|
|
238
275
|
maxRuns: positive(env.ZEN_RUNTIME_MAX_RUNS, mod.DEFAULTS.maxRuns),
|
|
239
276
|
maxUserRuns: positive(env.ZEN_RUNTIME_MAX_USER_RUNS, mod.DEFAULTS.maxUserRuns),
|
|
240
277
|
maxRunMinutes: positive(env.ZEN_RUNTIME_MAX_RUN_MINUTES, mod.DEFAULTS.maxRunMinutes),
|
|
@@ -402,6 +439,59 @@ async function startContainer(ctx, values) {
|
|
|
402
439
|
});
|
|
403
440
|
process.exit(0);
|
|
404
441
|
}
|
|
442
|
+
/** `build`: a release image, the project baked into the agent image; pushed with --push. */
|
|
443
|
+
async function build(ctx, values) {
|
|
444
|
+
const mod = await load();
|
|
445
|
+
if (mod.inAgentImage()) {
|
|
446
|
+
throw usageError('release images are built on a host with podman, not in the agent image', USAGE);
|
|
447
|
+
}
|
|
448
|
+
if (!values.push && (values.authfile || values['insecure-registry'])) {
|
|
449
|
+
throw usageError('--authfile and --insecure-registry go with --push <ref>', USAGE);
|
|
450
|
+
}
|
|
451
|
+
if (values.push !== undefined && !values.push.trim()) {
|
|
452
|
+
throw usageError('push where? --push <registry>/<name>:<tag>', USAGE);
|
|
453
|
+
}
|
|
454
|
+
const release = values.release === undefined ? undefined : checkRelease(values.release);
|
|
455
|
+
const adds = (values.add ?? []).map((spec) => parseAdd(spec, ctx.cwd));
|
|
456
|
+
const authfile = values.authfile ? resolve(ctx.cwd, values.authfile) : undefined;
|
|
457
|
+
if (authfile && !existsSync(authfile)) {
|
|
458
|
+
throw usageError(`no such auth file: ${authfile}`, USAGE);
|
|
459
|
+
}
|
|
460
|
+
const memorySeed = whichSeed(ctx, values);
|
|
461
|
+
const env = process.env;
|
|
462
|
+
const project = await whichProject(ctx, values, env, mod);
|
|
463
|
+
const result = await buildReleaseImage(project.dir, {
|
|
464
|
+
release,
|
|
465
|
+
memorySeed,
|
|
466
|
+
adds,
|
|
467
|
+
projectId: env.ZEN_PROJECT_ID?.trim() || project.name,
|
|
468
|
+
push: values.push
|
|
469
|
+
? {
|
|
470
|
+
ref: values.push.trim(),
|
|
471
|
+
authfile,
|
|
472
|
+
insecure: Boolean(values['insecure-registry']),
|
|
473
|
+
}
|
|
474
|
+
: undefined,
|
|
475
|
+
rebuild: values.rebuild,
|
|
476
|
+
verbose: values.verbose,
|
|
477
|
+
});
|
|
478
|
+
if (ctx.json) {
|
|
479
|
+
json(result);
|
|
480
|
+
return;
|
|
481
|
+
}
|
|
482
|
+
note();
|
|
483
|
+
note(` ${bold(cyan('Release'))} ${bold(result.release)}${result.built ? '' : dim(' (already built)')}`);
|
|
484
|
+
for (const line of table([
|
|
485
|
+
['Image', result.image],
|
|
486
|
+
['Agent', result.agentImage],
|
|
487
|
+
['Base', result.base],
|
|
488
|
+
...(result.ref ? [['Pushed', result.ref]] : []),
|
|
489
|
+
...(result.digest ? [['Digest', green(result.digest)]] : []),
|
|
490
|
+
]))
|
|
491
|
+
note(` ${line}`);
|
|
492
|
+
note();
|
|
493
|
+
write(result.digest ?? result.image);
|
|
494
|
+
}
|
|
405
495
|
async function status(ctx, values) {
|
|
406
496
|
const mod = await load();
|
|
407
497
|
const on = listenOn(values);
|
package/dist/container.d.ts
CHANGED
|
@@ -44,4 +44,6 @@ export interface ContainerRun {
|
|
|
44
44
|
*/
|
|
45
45
|
export declare function runContainer(run: ContainerRun): Promise<void>;
|
|
46
46
|
export declare function agentDockerfile(base: string, identity: Record<string, string>): string;
|
|
47
|
+
/** Everything that went into the image: the base's id and the context, file by file. */
|
|
48
|
+
export declare function contentHash(ctx: string, baseId: string): string;
|
|
47
49
|
//# sourceMappingURL=container.d.ts.map
|
package/dist/container.js
CHANGED
|
@@ -374,7 +374,7 @@ CMD ["server", "start"]
|
|
|
374
374
|
`;
|
|
375
375
|
}
|
|
376
376
|
/** Everything that went into the image: the base's id and the context, file by file. */
|
|
377
|
-
function contentHash(ctx, baseId) {
|
|
377
|
+
export function contentHash(ctx, baseId) {
|
|
378
378
|
const hash = createHash('sha256').update(baseId);
|
|
379
379
|
const walk = (rel) => {
|
|
380
380
|
for (const entry of readdirSync(join(ctx, rel), { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { type AgentImage } from './container.ts';
|
|
2
|
+
/** Where the image keeps its own things: an --add must not land on (or over) any of them. */
|
|
3
|
+
export declare const RESERVED_DESTINATIONS: readonly ["/project", "/seed", "/state", "/workspace", "/opt/zenera/app", "/opt/zenera/bin"];
|
|
4
|
+
export interface ReleaseAdd {
|
|
5
|
+
/** absolute path on this machine */
|
|
6
|
+
src: string;
|
|
7
|
+
/** absolute path in the image */
|
|
8
|
+
dest: string;
|
|
9
|
+
}
|
|
10
|
+
export interface ReleaseOptions {
|
|
11
|
+
release?: string;
|
|
12
|
+
/** `--memory-seed` (a dir), `--no-memory-seed` (null), or the project's own (undefined) */
|
|
13
|
+
memorySeed?: string | null;
|
|
14
|
+
adds?: readonly ReleaseAdd[];
|
|
15
|
+
push?: {
|
|
16
|
+
ref: string;
|
|
17
|
+
authfile?: string;
|
|
18
|
+
insecure?: boolean;
|
|
19
|
+
};
|
|
20
|
+
projectId?: string;
|
|
21
|
+
rebuild?: boolean;
|
|
22
|
+
verbose?: boolean;
|
|
23
|
+
}
|
|
24
|
+
export interface ReleaseImage {
|
|
25
|
+
release: string;
|
|
26
|
+
/** the release image, tagged locally */
|
|
27
|
+
image: string;
|
|
28
|
+
agentImage: string;
|
|
29
|
+
base: string;
|
|
30
|
+
built: boolean;
|
|
31
|
+
ref?: string;
|
|
32
|
+
digest?: string;
|
|
33
|
+
}
|
|
34
|
+
/** `<src>:<dest>`: src resolved against cwd and present, dest an absolute path of its own. */
|
|
35
|
+
export declare function parseAdd(spec: string, cwd: string): ReleaseAdd;
|
|
36
|
+
/** A release id as given, checked; the default comes from the content (`r-<hash>`). */
|
|
37
|
+
export declare function checkRelease(id: string): string;
|
|
38
|
+
/** Image-readable modes: dirs 0755, files 0644, or 0755 when the source is executable. */
|
|
39
|
+
export declare function releaseMode(mode: number, isDir: boolean): number;
|
|
40
|
+
/**
|
|
41
|
+
* The project as the image carries it: what `zen export` would (no `.env`, sessions, `.git`,
|
|
42
|
+
* `node_modules`, scratch, locks, links), minus its memory, which travels as the seed.
|
|
43
|
+
*/
|
|
44
|
+
export declare function snapshotProject(projectDir: string, into: string): Promise<number>;
|
|
45
|
+
/** A file or a tree, copied with image-readable modes; links are not followed. */
|
|
46
|
+
export declare function copyTree(src: string, into: string): Promise<void>;
|
|
47
|
+
export declare function releaseDockerfile(agentTag: string, opts: {
|
|
48
|
+
release: string;
|
|
49
|
+
projectId: string;
|
|
50
|
+
seed: boolean;
|
|
51
|
+
adds: readonly {
|
|
52
|
+
ctxPath: string;
|
|
53
|
+
dest: string;
|
|
54
|
+
}[];
|
|
55
|
+
}): string;
|
|
56
|
+
/** The arguments of `podman push`, the reference as podman wants it. */
|
|
57
|
+
export declare function pushArgs(tag: string, push: {
|
|
58
|
+
ref: string;
|
|
59
|
+
authfile?: string;
|
|
60
|
+
insecure?: boolean;
|
|
61
|
+
}, digestFile: string): string[];
|
|
62
|
+
/** Pushes the image and returns its manifest digest (`sha256:…`). */
|
|
63
|
+
export declare function pushImage(tag: string, push: {
|
|
64
|
+
ref: string;
|
|
65
|
+
authfile?: string;
|
|
66
|
+
insecure?: boolean;
|
|
67
|
+
}, digestFile: string): Promise<string>;
|
|
68
|
+
/** The release image for a project: the agent image built first, then the project on top. */
|
|
69
|
+
export declare function buildReleaseImage(projectDir: string, opts?: ReleaseOptions): Promise<ReleaseImage>;
|
|
70
|
+
/** The release step alone, on an agent image already built. */
|
|
71
|
+
export declare function buildRelease(projectDir: string, agent: AgentImage, opts?: ReleaseOptions): Promise<ReleaseImage>;
|
|
72
|
+
//# sourceMappingURL=release.d.ts.map
|
package/dist/release.js
ADDED
|
@@ -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/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zenera/cli",
|
|
3
|
-
"version": "1.2.
|
|
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",
|
|
@@ -55,11 +55,11 @@
|
|
|
55
55
|
"@google/genai": "^2.30.0",
|
|
56
56
|
"@inkjs/ui": "^2.0.0",
|
|
57
57
|
"@openrouter/sdk": "^1.4.25",
|
|
58
|
-
"@zenera/engine": "^1.2.
|
|
59
|
-
"@zenera/neo": "^1.2.
|
|
60
|
-
"@zenera/sandbox": "^1.2.
|
|
61
|
-
"@zenera/server": "^1.2.
|
|
62
|
-
"@zenera/view": "^1.2.
|
|
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",
|
|
63
63
|
"google-auth-library": "^10.0.0",
|
|
64
64
|
"ink": "^7.1.1",
|
|
65
65
|
"openai": "^6.0.0",
|