@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.
- package/README.md +33 -15
- package/assets/chat.html +4539 -0
- package/dist/chat.d.ts +7 -0
- package/dist/chat.js +29 -0
- package/dist/commands/index.js +2 -0
- package/dist/commands/server.d.ts +12 -0
- package/dist/commands/server.js +569 -0
- package/dist/container.d.ts +49 -0
- package/dist/container.js +398 -0
- package/dist/containerCredentials.d.ts +2 -0
- package/dist/containerCredentials.js +33 -0
- package/dist/podman.d.ts +1 -0
- package/dist/podman.js +7 -1
- package/dist/release.d.ts +72 -0
- package/dist/release.js +255 -0
- package/dist/seed.d.ts +6 -0
- package/dist/seed.js +64 -0
- package/dist/serverDisplay.d.ts +24 -0
- package/dist/serverDisplay.js +161 -0
- package/dist/serverKeys.d.ts +5 -0
- package/dist/serverKeys.js +53 -0
- package/package.json +8 -5
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
export declare const AGENT_UID = 10001;
|
|
2
|
+
export declare const AGENT_GID = 10001;
|
|
3
|
+
export interface AgentImage {
|
|
4
|
+
/** the agent image */
|
|
5
|
+
tag: string;
|
|
6
|
+
/** what it was built on: the project's environment */
|
|
7
|
+
base: string;
|
|
8
|
+
built: boolean;
|
|
9
|
+
}
|
|
10
|
+
/** The agent image for a project, built unless this machine has it already. */
|
|
11
|
+
export declare function buildAgentImage(projectDir: string, opts?: {
|
|
12
|
+
rebuild?: boolean;
|
|
13
|
+
verbose?: boolean;
|
|
14
|
+
}): Promise<AgentImage>;
|
|
15
|
+
export interface ContainerRun {
|
|
16
|
+
image: string;
|
|
17
|
+
project: {
|
|
18
|
+
dir: string;
|
|
19
|
+
id: string;
|
|
20
|
+
};
|
|
21
|
+
/** where users' things are kept on this machine: /state inside */
|
|
22
|
+
root: string;
|
|
23
|
+
/** a seed outside the project, mounted read-only */
|
|
24
|
+
memorySeed?: string | null;
|
|
25
|
+
listen: {
|
|
26
|
+
port: number;
|
|
27
|
+
host: string;
|
|
28
|
+
};
|
|
29
|
+
debug: boolean;
|
|
30
|
+
/** Host-side UI links are printed only after podman has started the container. */
|
|
31
|
+
onStarted?: () => void;
|
|
32
|
+
auth: {
|
|
33
|
+
mode: 'jwt';
|
|
34
|
+
publicKey: string;
|
|
35
|
+
issuer: string;
|
|
36
|
+
audience: string;
|
|
37
|
+
} | {
|
|
38
|
+
mode: 'insecure';
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Runs the agent image in podman and stays with it: its log here, its port published on this
|
|
43
|
+
* machine, a Ctrl-C or SIGTERM passed on so its runs save before it goes.
|
|
44
|
+
*/
|
|
45
|
+
export declare function runContainer(run: ContainerRun): Promise<void>;
|
|
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;
|
|
49
|
+
//# sourceMappingURL=container.d.ts.map
|
|
@@ -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
|
+
export 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,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);
|
|
@@ -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
|