@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.
- 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 +479 -0
- package/dist/container.d.ts +47 -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/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/dist/tui/links.d.ts +7 -2
- package/dist/tui/links.js +18 -30
- package/package.json +8 -5
package/dist/chat.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export declare function chatPage(): string;
|
|
2
|
+
/** The fragment never reaches the server; HTTP links retain it when opened by macOS. */
|
|
3
|
+
export declare function chatUrl(on: {
|
|
4
|
+
host: string;
|
|
5
|
+
port: number;
|
|
6
|
+
}, token: string): string;
|
|
7
|
+
//# sourceMappingURL=chat.d.ts.map
|
package/dist/chat.js
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Packaged standalone-chat URL helper, used by the server CLI after insecure startup.
|
|
3
|
+
* chatPage locates assets/chat.html for the insecure HTTP route; chatUrl puts the
|
|
4
|
+
* runtime address and dev JWT in that route's fragment, handling IPv6 addresses.
|
|
5
|
+
* A trailing open parameter keeps terminals from trimming the unsigned JWT's final dot.
|
|
6
|
+
*/
|
|
7
|
+
import { existsSync } from 'node:fs';
|
|
8
|
+
import { fileURLToPath } from 'node:url';
|
|
9
|
+
import { CliError, EXIT } from "./term.js";
|
|
10
|
+
export function chatPage() {
|
|
11
|
+
const page = new URL('../assets/chat.html', import.meta.url);
|
|
12
|
+
if (!existsSync(page)) {
|
|
13
|
+
throw new CliError('the packaged test chat page is missing', EXIT.failed, 'reinstall zen');
|
|
14
|
+
}
|
|
15
|
+
return fileURLToPath(page);
|
|
16
|
+
}
|
|
17
|
+
/** The fragment never reaches the server; HTTP links retain it when opened by macOS. */
|
|
18
|
+
export function chatUrl(on, token) {
|
|
19
|
+
chatPage();
|
|
20
|
+
const host = on.host.includes(':') ? `[${on.host}]` : on.host;
|
|
21
|
+
const page = new URL(`http://${host}:${on.port}/chat`);
|
|
22
|
+
page.hash = new URLSearchParams({
|
|
23
|
+
jwt: token,
|
|
24
|
+
server: `http://${host}:${on.port}`,
|
|
25
|
+
open: '1',
|
|
26
|
+
}).toString();
|
|
27
|
+
return page.href;
|
|
28
|
+
}
|
|
29
|
+
//# sourceMappingURL=chat.js.map
|
package/dist/commands/index.js
CHANGED
|
@@ -13,6 +13,7 @@ import { models } from "./models.js";
|
|
|
13
13
|
import { open } from "./open.js";
|
|
14
14
|
import { run } from "./run.js";
|
|
15
15
|
import { sandbox } from "./sandbox.js";
|
|
16
|
+
import { server } from "./server.js";
|
|
16
17
|
import { version } from "./version.js";
|
|
17
18
|
import { view } from "./view.js";
|
|
18
19
|
/**
|
|
@@ -39,6 +40,7 @@ export const COMMANDS = {
|
|
|
39
40
|
import: unpack,
|
|
40
41
|
memory,
|
|
41
42
|
sandbox,
|
|
43
|
+
server,
|
|
42
44
|
cache,
|
|
43
45
|
completion,
|
|
44
46
|
version,
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { Command } from '../command.ts';
|
|
2
|
+
/**
|
|
3
|
+
* The agent server: a project's chats over HTTP, for every user its host vouches for. What the
|
|
4
|
+
* agent image runs (`/opt/zenera/bin/zen server start`); `@zenera/server` is loaded only here,
|
|
5
|
+
* so no other command pays for it.
|
|
6
|
+
*
|
|
7
|
+
* Who a request is for is the `sub` of a JWT the host signs for that request (EdDSA, checked
|
|
8
|
+
* with its public key); each user's chats and memory are in a folder of their own. `--insecure`
|
|
9
|
+
* reads the token without checking it, on loopback only, for trying it out.
|
|
10
|
+
*/
|
|
11
|
+
export declare const server: Command;
|
|
12
|
+
//# sourceMappingURL=server.d.ts.map
|
|
@@ -0,0 +1,479 @@
|
|
|
1
|
+
/**
|
|
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, and keygen writes an Ed25519 pair.
|
|
5
|
+
* On insecure startup, --user only
|
|
6
|
+
* chooses the sub claim for the printed browser link (default local); every API
|
|
7
|
+
* request still selects its user through its own JWT, not a server-wide user setting.
|
|
8
|
+
*/
|
|
9
|
+
import { home } from '@zenera/engine';
|
|
10
|
+
import { readFileSync } from 'node:fs';
|
|
11
|
+
import { join, resolve } from 'node:path';
|
|
12
|
+
import { parse } from "../args.js";
|
|
13
|
+
import { chatPage, chatUrl } from "../chat.js";
|
|
14
|
+
import { AGENT_GID, AGENT_UID, buildAgentImage, runContainer } from "../container.js";
|
|
15
|
+
import { stageContainerCredentials } from "../containerCredentials.js";
|
|
16
|
+
import { asCliError, ensurePodmanReady } from "../podman.js";
|
|
17
|
+
import { project as resolveProject } from "../resolve.js";
|
|
18
|
+
import { preflight } from "../sandbox.js";
|
|
19
|
+
import { prepareMemorySeed } from "../seed.js";
|
|
20
|
+
import { generateServerKeys } from "../serverKeys.js";
|
|
21
|
+
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'];
|
|
25
|
+
/**
|
|
26
|
+
* The agent server: a project's chats over HTTP, for every user its host vouches for. What the
|
|
27
|
+
* agent image runs (`/opt/zenera/bin/zen server start`); `@zenera/server` is loaded only here,
|
|
28
|
+
* so no other command pays for it.
|
|
29
|
+
*
|
|
30
|
+
* Who a request is for is the `sub` of a JWT the host signs for that request (EdDSA, checked
|
|
31
|
+
* with its public key); each user's chats and memory are in a folder of their own. `--insecure`
|
|
32
|
+
* reads the token without checking it, on loopback only, for trying it out.
|
|
33
|
+
*/
|
|
34
|
+
export const server = {
|
|
35
|
+
summary: 'Serve a project’s chats over HTTP, for every user its host vouches for.',
|
|
36
|
+
usage: USAGE,
|
|
37
|
+
banner: { head: 'Zenera', accent: 'Server', subtitle: 'Agent Server', hue: 'crimson' },
|
|
38
|
+
details: [
|
|
39
|
+
' start Listen, after the checks below pass.',
|
|
40
|
+
' check Whether it could start here: commands have somewhere to',
|
|
41
|
+
' run, the image is this project\u2019s, the root is this',
|
|
42
|
+
' server\u2019s.',
|
|
43
|
+
' status A running server\u2019s own report (/api/status).',
|
|
44
|
+
' token Print an unsigned token for an --insecure server:',
|
|
45
|
+
' --user <id> [--email …] [--role …] [--thread <id>].',
|
|
46
|
+
' keygen Generate Ed25519 keys: --out <prefix> writes',
|
|
47
|
+
' <prefix>.private.pem (0600) and <prefix>.public.pem.',
|
|
48
|
+
' Existing files are never overwritten. Keep the private',
|
|
49
|
+
' key with the trusted caller, not the runtime.',
|
|
50
|
+
'',
|
|
51
|
+
' --port <n> Default $ZEN_SERVER_PORT, else 3000.',
|
|
52
|
+
' --host <addr> Default $ZEN_SERVER_HOST, else 127.0.0.1.',
|
|
53
|
+
' --project <name|dir> The project; default $PROJECT_DIR, else the one you are',
|
|
54
|
+
' in, as zen run (in the agent image: /project).',
|
|
55
|
+
' --root <dir> Every user\u2019s chats and memory: users/<user>/{sessions,',
|
|
56
|
+
' memory}. Default $ZEN_SERVER_ROOT, else',
|
|
57
|
+
' ~/.zenera/neo/servers/<project> (in the agent image: /state).',
|
|
58
|
+
' --memory-seed <dir> What each user\u2019s memory starts as, copied the first time',
|
|
59
|
+
' they need one. Default: the project\u2019s own.',
|
|
60
|
+
' --no-memory-seed Every user starts with an empty memory.',
|
|
61
|
+
'',
|
|
62
|
+
' --jwt-public-key <file> The PEM (Ed25519) its tokens are signed for; default',
|
|
63
|
+
' $ZEN_SERVER_JWT_PUBLIC_KEY (the PEM itself).',
|
|
64
|
+
' --jwt-issuer <iss> Default zenera-app. --jwt-audience <aud> Default zenera-runtime.',
|
|
65
|
+
' --insecure Read tokens without checking them: no key, any signature,',
|
|
66
|
+
' any age. Local testing only; loopback or --container',
|
|
67
|
+
' with its port published on loopback.',
|
|
68
|
+
' Prints an HTTP /chat link to the bundled React test chat.',
|
|
69
|
+
' --user <id> Browser user with --insecure (default local); required',
|
|
70
|
+
' with token. API callers still choose their user via JWT.',
|
|
71
|
+
'',
|
|
72
|
+
' --container Run it in podman, in an image built from the project\u2019s',
|
|
73
|
+
' sandbox/Dockerfile and this zen: commands under bwrap,',
|
|
74
|
+
' with what that Dockerfile installed. --rebuild to build',
|
|
75
|
+
' it again.',
|
|
76
|
+
' --verbose With --container: all image build lines, grouped and',
|
|
77
|
+
' colored. Default: one updating line; warnings stay visible.',
|
|
78
|
+
' --debug The Test tab\u2019s routes: runs, traces, memory.',
|
|
79
|
+
' --sandbox <podman|bwrap> Where commands run; default $ZEN_SERVER_SANDBOX,',
|
|
80
|
+
' else bwrap inside the agent image and podman anywhere',
|
|
81
|
+
' else, as zen run.',
|
|
82
|
+
' --token <jwt> With status: the token to send (default: an unsigned one,',
|
|
83
|
+
' which an --insecure server takes).',
|
|
84
|
+
'',
|
|
85
|
+
'Model keys come from the keyring and the environment, as for zen run.',
|
|
86
|
+
],
|
|
87
|
+
run: async (ctx) => {
|
|
88
|
+
const { values, positionals } = parse(ctx.args, {
|
|
89
|
+
port: { type: 'string' },
|
|
90
|
+
host: { type: 'string' },
|
|
91
|
+
project: { type: 'string' },
|
|
92
|
+
root: { type: 'string' },
|
|
93
|
+
'memory-seed': { type: 'string' },
|
|
94
|
+
'no-memory-seed': { type: 'boolean' },
|
|
95
|
+
'jwt-public-key': { type: 'string' },
|
|
96
|
+
'jwt-issuer': { type: 'string' },
|
|
97
|
+
'jwt-audience': { type: 'string' },
|
|
98
|
+
insecure: { type: 'boolean' },
|
|
99
|
+
debug: { type: 'boolean' },
|
|
100
|
+
sandbox: { type: 'string' },
|
|
101
|
+
container: { type: 'boolean' },
|
|
102
|
+
rebuild: { type: 'boolean' },
|
|
103
|
+
verbose: { type: 'boolean' },
|
|
104
|
+
token: { type: 'string' },
|
|
105
|
+
user: { type: 'string' },
|
|
106
|
+
email: { type: 'string' },
|
|
107
|
+
role: { type: 'string' },
|
|
108
|
+
name: { type: 'string' },
|
|
109
|
+
thread: { type: 'string' },
|
|
110
|
+
out: { type: 'string' },
|
|
111
|
+
}, USAGE);
|
|
112
|
+
const what = positionals[0];
|
|
113
|
+
if (!what || !SUBCOMMANDS.includes(what)) {
|
|
114
|
+
throw usageError(what ? `unknown subcommand: ${what}` : 'which one?', USAGE);
|
|
115
|
+
}
|
|
116
|
+
if (positionals.length > 1) {
|
|
117
|
+
throw usageError('one subcommand at a time', USAGE);
|
|
118
|
+
}
|
|
119
|
+
switch (what) {
|
|
120
|
+
case 'start':
|
|
121
|
+
return values.container ? startContainer(ctx, values) : start(ctx, values);
|
|
122
|
+
case 'check':
|
|
123
|
+
return check(ctx, values);
|
|
124
|
+
case 'status':
|
|
125
|
+
return status(ctx, values);
|
|
126
|
+
case 'token':
|
|
127
|
+
return token(values);
|
|
128
|
+
case 'keygen':
|
|
129
|
+
return keygen(ctx, values);
|
|
130
|
+
}
|
|
131
|
+
},
|
|
132
|
+
};
|
|
133
|
+
function keygen(ctx, values) {
|
|
134
|
+
if (!values.out?.trim()) {
|
|
135
|
+
throw usageError('give an output prefix: --out <prefix>', USAGE);
|
|
136
|
+
}
|
|
137
|
+
const paths = generateServerKeys(resolve(ctx.cwd, values.out));
|
|
138
|
+
if (ctx.json) {
|
|
139
|
+
json(paths);
|
|
140
|
+
}
|
|
141
|
+
else {
|
|
142
|
+
write(`Private key: ${paths.privateKey}`);
|
|
143
|
+
write(`Public key: ${paths.publicKey}`);
|
|
144
|
+
}
|
|
145
|
+
note('Keep the private key with the trusted caller. Give only the public key to zen server.');
|
|
146
|
+
}
|
|
147
|
+
async function load() {
|
|
148
|
+
return import('@zenera/server');
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* The project: --project (a name or a directory, as `zen run --project`), else $PROJECT_DIR, else
|
|
152
|
+
* /project in the agent image, else the one this directory is in — or a registered one to pick.
|
|
153
|
+
*/
|
|
154
|
+
async function whichProject(ctx, values, env, mod) {
|
|
155
|
+
const given = values.project ?? env.PROJECT_DIR?.trim();
|
|
156
|
+
if (!given && mod.inAgentImage()) {
|
|
157
|
+
return { dir: '/project', name: env.ZEN_PROJECT_ID?.trim() || 'project' };
|
|
158
|
+
}
|
|
159
|
+
const found = await resolveProject({ project: given, cwd: ctx.cwd });
|
|
160
|
+
return { dir: found.dir, name: found.name };
|
|
161
|
+
}
|
|
162
|
+
/** The verification a token gets: the host's key, or none at all (`--insecure`). */
|
|
163
|
+
function whichAuth(ctx, values, env, mod) {
|
|
164
|
+
if (values.insecure) {
|
|
165
|
+
if (values['jwt-public-key']) {
|
|
166
|
+
throw usageError('--insecure checks no key: drop --jwt-public-key', USAGE);
|
|
167
|
+
}
|
|
168
|
+
if (mod.inAgentImage() && !mod.insecureHere(env)) {
|
|
169
|
+
throw usageError('--insecure is never for a pod: give it the public key', USAGE);
|
|
170
|
+
}
|
|
171
|
+
return { mode: 'insecure' };
|
|
172
|
+
}
|
|
173
|
+
let publicKey = env.ZEN_SERVER_JWT_PUBLIC_KEY?.trim() ?? '';
|
|
174
|
+
if (values['jwt-public-key']) {
|
|
175
|
+
try {
|
|
176
|
+
publicKey = readFileSync(resolve(ctx.cwd, values['jwt-public-key']), 'utf8');
|
|
177
|
+
}
|
|
178
|
+
catch (err) {
|
|
179
|
+
throw usageError(`cannot read the public key: ${err.message}`, USAGE);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
if (!publicKey) {
|
|
183
|
+
throw usageError('no key to check tokens with', 'give the public key its tokens are signed for (--jwt-public-key or ' +
|
|
184
|
+
'$ZEN_SERVER_JWT_PUBLIC_KEY), or try it with --insecure');
|
|
185
|
+
}
|
|
186
|
+
return {
|
|
187
|
+
mode: 'jwt',
|
|
188
|
+
publicKey,
|
|
189
|
+
issuer: values['jwt-issuer'] ?? (env.ZEN_SERVER_JWT_ISSUER?.trim() || mod.DEFAULT_ISSUER),
|
|
190
|
+
audience: values['jwt-audience'] ?? (env.ZEN_SERVER_JWT_AUDIENCE?.trim() || mod.DEFAULT_AUDIENCE),
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
/** --root, else $ZEN_SERVER_ROOT, else /state in the agent image, else in the zen home. */
|
|
194
|
+
function whichRoot(ctx, values, env, mod, project) {
|
|
195
|
+
const given = values.root ?? env.ZEN_SERVER_ROOT?.trim();
|
|
196
|
+
if (given)
|
|
197
|
+
return resolve(ctx.cwd, given);
|
|
198
|
+
if (mod.inAgentImage())
|
|
199
|
+
return '/state';
|
|
200
|
+
return join(home(), 'servers', project.replace(/[^\w.@-]/g, '_'));
|
|
201
|
+
}
|
|
202
|
+
function whichSeed(ctx, values) {
|
|
203
|
+
if (values['no-memory-seed']) {
|
|
204
|
+
if (values['memory-seed'])
|
|
205
|
+
throw usageError('--memory-seed or --no-memory-seed', USAGE);
|
|
206
|
+
return null;
|
|
207
|
+
}
|
|
208
|
+
return values['memory-seed'] ? resolve(ctx.cwd, values['memory-seed']) : undefined;
|
|
209
|
+
}
|
|
210
|
+
async function options(ctx, values, env = process.env) {
|
|
211
|
+
const mod = await load();
|
|
212
|
+
if (mod.inAgentImage())
|
|
213
|
+
await stageContainerCredentials();
|
|
214
|
+
const project = await whichProject(ctx, values, env, mod);
|
|
215
|
+
const projectId = env.ZEN_PROJECT_ID?.trim() || project.name;
|
|
216
|
+
const sandboxName = values.sandbox ?? (env.ZEN_SERVER_SANDBOX?.trim() || mod.defaultSandbox());
|
|
217
|
+
if (sandboxName !== 'bwrap' && sandboxName !== 'podman') {
|
|
218
|
+
throw usageError(`--sandbox is bwrap or podman, not ${sandboxName}`, USAGE);
|
|
219
|
+
}
|
|
220
|
+
const settings = {
|
|
221
|
+
...mod.DEFAULTS,
|
|
222
|
+
projectDir: project.dir,
|
|
223
|
+
projectId,
|
|
224
|
+
root: whichRoot(ctx, values, env, mod, projectId),
|
|
225
|
+
memorySeed: whichSeed(ctx, values),
|
|
226
|
+
auth: whichAuth(ctx, values, env, mod),
|
|
227
|
+
debug: Boolean(values.debug ?? truthy(env.ZEN_SERVER_DEBUG)),
|
|
228
|
+
sandbox: sandboxName,
|
|
229
|
+
sandboxProvider: mod.SANDBOX_PROVIDERS[sandboxName],
|
|
230
|
+
// As `zen run` readies podman: the machine started, the image pulled or built.
|
|
231
|
+
...(sandboxName === 'podman'
|
|
232
|
+
? {
|
|
233
|
+
preflight: (setup) => preflight(setup, true),
|
|
234
|
+
}
|
|
235
|
+
: {}),
|
|
236
|
+
hidden: [],
|
|
237
|
+
plugins: mod.envRunPlugins(env),
|
|
238
|
+
maxRuns: positive(env.ZEN_RUNTIME_MAX_RUNS, mod.DEFAULTS.maxRuns),
|
|
239
|
+
maxUserRuns: positive(env.ZEN_RUNTIME_MAX_USER_RUNS, mod.DEFAULTS.maxUserRuns),
|
|
240
|
+
maxRunMinutes: positive(env.ZEN_RUNTIME_MAX_RUN_MINUTES, mod.DEFAULTS.maxRunMinutes),
|
|
241
|
+
runLogMaxBytes: positive(env.ZEN_RUNTIME_RUN_LOG_MAX_MB, mod.DEFAULTS.runLogMaxBytes / 2 ** 20) *
|
|
242
|
+
2 ** 20,
|
|
243
|
+
};
|
|
244
|
+
return { mod, settings, listen: listenOn(values, env) };
|
|
245
|
+
}
|
|
246
|
+
/** --port/--host, else $ZEN_SERVER_PORT/$ZEN_SERVER_HOST, else 127.0.0.1:3000. */
|
|
247
|
+
function listenOn(values, env = process.env) {
|
|
248
|
+
const text = values.port ?? env.ZEN_SERVER_PORT?.trim() ?? '3000';
|
|
249
|
+
const port = Number(text);
|
|
250
|
+
if (!Number.isInteger(port) || port < 0 || port > 65535) {
|
|
251
|
+
throw usageError(`not a port: ${text}`, USAGE);
|
|
252
|
+
}
|
|
253
|
+
return { port, host: values.host ?? (env.ZEN_SERVER_HOST?.trim() || '127.0.0.1') };
|
|
254
|
+
}
|
|
255
|
+
function describe(on) {
|
|
256
|
+
return on.host?.includes(':') ? `[${on.host}]:${on.port}` : `${on.host}:${on.port}`;
|
|
257
|
+
}
|
|
258
|
+
const LOOPBACK = new Set(['127.0.0.1', '::1', 'localhost']);
|
|
259
|
+
async function check(ctx, values) {
|
|
260
|
+
if (values.container) {
|
|
261
|
+
await ensurePodmanReady({ yes: true }).catch((err) => {
|
|
262
|
+
throw asCliError(err);
|
|
263
|
+
});
|
|
264
|
+
write(green('✓ podman is ready: start --container builds what it needs'));
|
|
265
|
+
return;
|
|
266
|
+
}
|
|
267
|
+
const { mod, settings } = await options(ctx, values);
|
|
268
|
+
mod.configure(settings);
|
|
269
|
+
const report = await mod.serverStatus();
|
|
270
|
+
const errors = mod.startupErrors(report);
|
|
271
|
+
if (ctx.json) {
|
|
272
|
+
json({ ok: errors.length === 0, errors, status: report });
|
|
273
|
+
}
|
|
274
|
+
else {
|
|
275
|
+
printStatus(report);
|
|
276
|
+
for (const e of errors)
|
|
277
|
+
write(red(`✗ ${e}`));
|
|
278
|
+
if (!errors.length)
|
|
279
|
+
write(green('✓ ready to start'));
|
|
280
|
+
}
|
|
281
|
+
if (errors.length) {
|
|
282
|
+
throw new CliError('the server cannot start here', EXIT.sandbox);
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
async function start(ctx, values) {
|
|
286
|
+
const { mod, settings, listen } = await options(ctx, values);
|
|
287
|
+
if (settings.auth.mode === 'insecure' && !LOOPBACK.has(listen.host) && !mod.insecureHere()) {
|
|
288
|
+
throw usageError(`--insecure listens on loopback only, not ${listen.host}`, USAGE);
|
|
289
|
+
}
|
|
290
|
+
mod.configure(settings);
|
|
291
|
+
if (settings.sandbox === 'podman') {
|
|
292
|
+
// What `zen run` does first: podman there and its machine running, without asking.
|
|
293
|
+
await ensurePodmanReady({ yes: true }).catch((err) => {
|
|
294
|
+
throw asCliError(err);
|
|
295
|
+
});
|
|
296
|
+
}
|
|
297
|
+
const errors = mod.startupErrors(await mod.serverStatus());
|
|
298
|
+
if (errors.length) {
|
|
299
|
+
for (const e of errors)
|
|
300
|
+
note(red(`✗ ${e}`));
|
|
301
|
+
throw new CliError('the server cannot start here', EXIT.sandbox, 'zen server check');
|
|
302
|
+
}
|
|
303
|
+
const managed = hostManagedOutput(mod.inAgentImage());
|
|
304
|
+
const page = settings.auth.mode === 'insecure' && !mod.inAgentImage()
|
|
305
|
+
? chatUrl(listen, mod.unsignedToken({ sub: values.user ?? 'local' }))
|
|
306
|
+
: undefined;
|
|
307
|
+
const onHost = !mod.inAgentImage();
|
|
308
|
+
const seed = onHost
|
|
309
|
+
? await prepareMemorySeed(settings.projectDir, settings.root, settings.memorySeed)
|
|
310
|
+
: null;
|
|
311
|
+
if (onHost)
|
|
312
|
+
settings.memorySeed = seed?.dir ?? null;
|
|
313
|
+
try {
|
|
314
|
+
const app = mod.createServer({
|
|
315
|
+
...settings,
|
|
316
|
+
...(settings.auth.mode === 'insecure' ? { chatPage: chatPage() } : {}),
|
|
317
|
+
});
|
|
318
|
+
await app.listen(listen);
|
|
319
|
+
if (managed) {
|
|
320
|
+
note(` ${green('✓ HTTP listener ready')}`);
|
|
321
|
+
}
|
|
322
|
+
else {
|
|
323
|
+
printServerStarted({
|
|
324
|
+
project: settings.projectId,
|
|
325
|
+
url: `http://${describe(listen)}`,
|
|
326
|
+
root: settings.root,
|
|
327
|
+
auth: settings.auth.mode,
|
|
328
|
+
sandbox: `${settings.sandboxProvider}${settings.debug ? ' · debug routes enabled' : ''}`,
|
|
329
|
+
page,
|
|
330
|
+
chatUser: values.user,
|
|
331
|
+
});
|
|
332
|
+
}
|
|
333
|
+
// A stopping container: runs end as interrupted and save their sessions within the grace
|
|
334
|
+
// period, then the process ends — whatever a run's tools left open must not keep it alive.
|
|
335
|
+
await new Promise((done, fail) => {
|
|
336
|
+
let stopping = false;
|
|
337
|
+
const stop = (signal) => {
|
|
338
|
+
if (stopping)
|
|
339
|
+
return;
|
|
340
|
+
stopping = true;
|
|
341
|
+
note();
|
|
342
|
+
note(` ${yellow('Stopping server')} ${dim(`(${signal} · ${mod.activeRuns()} active runs)`)}`);
|
|
343
|
+
void app.stop(20_000).then(done, fail);
|
|
344
|
+
};
|
|
345
|
+
process.once('SIGTERM', () => stop('SIGTERM'));
|
|
346
|
+
process.once('SIGINT', () => stop('SIGINT'));
|
|
347
|
+
});
|
|
348
|
+
}
|
|
349
|
+
finally {
|
|
350
|
+
await seed?.cleanup();
|
|
351
|
+
}
|
|
352
|
+
if (!managed) {
|
|
353
|
+
note(` ${green('✓ Server stopped')}`);
|
|
354
|
+
note();
|
|
355
|
+
}
|
|
356
|
+
process.exit(0);
|
|
357
|
+
}
|
|
358
|
+
/** `--container`: the agent image built from the project, run in podman, its port here. */
|
|
359
|
+
async function startContainer(ctx, values) {
|
|
360
|
+
const mod = await load();
|
|
361
|
+
if (mod.inAgentImage()) {
|
|
362
|
+
throw usageError('already inside the agent image: drop --container', USAGE);
|
|
363
|
+
}
|
|
364
|
+
if (values.sandbox) {
|
|
365
|
+
throw usageError('--container runs commands under bwrap in it: drop --sandbox', USAGE);
|
|
366
|
+
}
|
|
367
|
+
const env = process.env;
|
|
368
|
+
const project = await whichProject(ctx, values, env, mod);
|
|
369
|
+
const projectId = env.ZEN_PROJECT_ID?.trim() || project.name;
|
|
370
|
+
const auth = whichAuth(ctx, values, env, mod);
|
|
371
|
+
const listen = listenOn(values, env);
|
|
372
|
+
if (auth.mode === 'insecure' && !LOOPBACK.has(listen.host)) {
|
|
373
|
+
throw usageError(`--insecure listens on loopback only, not ${listen.host}`, USAGE);
|
|
374
|
+
}
|
|
375
|
+
const page = auth.mode === 'insecure'
|
|
376
|
+
? chatUrl(listen, mod.unsignedToken({ sub: values.user ?? 'local' }))
|
|
377
|
+
: undefined;
|
|
378
|
+
const image = await buildAgentImage(project.dir, {
|
|
379
|
+
rebuild: values.rebuild,
|
|
380
|
+
verbose: values.verbose,
|
|
381
|
+
});
|
|
382
|
+
const root = whichRoot(ctx, values, env, mod, projectId);
|
|
383
|
+
await runContainer({
|
|
384
|
+
image: image.tag,
|
|
385
|
+
project: { dir: project.dir, id: projectId },
|
|
386
|
+
root,
|
|
387
|
+
memorySeed: whichSeed(ctx, values),
|
|
388
|
+
listen,
|
|
389
|
+
debug: Boolean(values.debug),
|
|
390
|
+
auth,
|
|
391
|
+
onStarted: () => printServerStarted({
|
|
392
|
+
project: projectId,
|
|
393
|
+
url: `http://${describe(listen)}`,
|
|
394
|
+
root,
|
|
395
|
+
auth: auth.mode,
|
|
396
|
+
sandbox: `bwrap (agent container)${values.debug ? ' · debug routes enabled' : ''}`,
|
|
397
|
+
image,
|
|
398
|
+
runtimeUser: `UID/GID ${AGENT_UID}:${AGENT_GID} (non-root)`,
|
|
399
|
+
page,
|
|
400
|
+
chatUser: values.user,
|
|
401
|
+
}),
|
|
402
|
+
});
|
|
403
|
+
process.exit(0);
|
|
404
|
+
}
|
|
405
|
+
async function status(ctx, values) {
|
|
406
|
+
const mod = await load();
|
|
407
|
+
const on = listenOn(values);
|
|
408
|
+
const target = '/api/status';
|
|
409
|
+
// An unsigned token, unless given one: what an --insecure server takes.
|
|
410
|
+
const bearer = values.token ??
|
|
411
|
+
mod.unsignedToken({ sub: values.user ?? 'zen-status', req: `GET ${target}` });
|
|
412
|
+
let res;
|
|
413
|
+
try {
|
|
414
|
+
res = await fetch(`http://${describe(on)}${target}`, {
|
|
415
|
+
headers: { authorization: `Bearer ${bearer}` },
|
|
416
|
+
signal: AbortSignal.timeout(10_000),
|
|
417
|
+
});
|
|
418
|
+
}
|
|
419
|
+
catch (err) {
|
|
420
|
+
throw new CliError(`no server answered on ${describe(on)}: ${err.cause?.code ?? err}`, EXIT.failed, 'is it running? --port and --host say where');
|
|
421
|
+
}
|
|
422
|
+
if (!res.ok) {
|
|
423
|
+
throw new CliError(`${describe(on)} answered ${res.status}: ${(await res.text()).slice(0, 200)}`, EXIT.failed, res.status === 401
|
|
424
|
+
? 'it checks its tokens: give it one signed for it, --token'
|
|
425
|
+
: undefined);
|
|
426
|
+
}
|
|
427
|
+
const report = (await res.json());
|
|
428
|
+
if (ctx.json) {
|
|
429
|
+
json(report);
|
|
430
|
+
return;
|
|
431
|
+
}
|
|
432
|
+
printStatus(report);
|
|
433
|
+
}
|
|
434
|
+
/** An unsigned token: what an --insecure server takes, for curl and the like. */
|
|
435
|
+
async function token(values) {
|
|
436
|
+
const mod = await load();
|
|
437
|
+
if (!values.user) {
|
|
438
|
+
throw usageError('for whom? --user <id>', USAGE);
|
|
439
|
+
}
|
|
440
|
+
write(mod.unsignedToken({
|
|
441
|
+
sub: values.user,
|
|
442
|
+
...(values.email ? { email: values.email } : {}),
|
|
443
|
+
...(values.role ? { role: values.role } : {}),
|
|
444
|
+
...(values.name ? { name: values.name } : {}),
|
|
445
|
+
...(values.thread ? { thr: values.thread } : {}),
|
|
446
|
+
}));
|
|
447
|
+
}
|
|
448
|
+
function printStatus(s) {
|
|
449
|
+
const row = (k, v) => write(`${dim(k.padEnd(9))} ${v}`);
|
|
450
|
+
row('project', `${s.project.id} ${dim(s.project.dir)}`);
|
|
451
|
+
row('auth', s.auth === 'insecure' ? yellow('insecure (tokens not checked)') : 'jwt (EdDSA, checked)');
|
|
452
|
+
row('listen', `${s.listen ?? dim('not yet')}${s.debug ? dim(' · debug routes on') : ''}`);
|
|
453
|
+
row('sandbox', s.sandbox.ok
|
|
454
|
+
? `${s.sandbox.provider}${s.sandbox.proc ? dim(` · ${s.sandbox.proc} /proc`) : ''}`
|
|
455
|
+
: red(`${s.sandbox.provider}: ${s.sandbox.error}`));
|
|
456
|
+
const img = s.image;
|
|
457
|
+
row('image', img.error
|
|
458
|
+
? red(img.error)
|
|
459
|
+
: img.matches === undefined
|
|
460
|
+
? yellow('not built by zen (no identity to check)')
|
|
461
|
+
: img.matches
|
|
462
|
+
? `${img.build ?? img.base}${img.release ? dim(` · release ${img.release}`) : ''}`
|
|
463
|
+
: red(`${img.build ?? img.base}, project wants ${img.wants.build ?? img.wants.image}`));
|
|
464
|
+
row('root', s.root.error
|
|
465
|
+
? red(s.root.error)
|
|
466
|
+
: `${s.root.dir} ${dim(s.root.version === undefined
|
|
467
|
+
? 'new: written on start'
|
|
468
|
+
: `layout ${s.root.version} of ${s.root.supported}`)}`);
|
|
469
|
+
row('memory', s.memorySeed ? `seeded from ${s.memorySeed}` : dim('no seed: each user starts empty'));
|
|
470
|
+
row('versions', dim(`server ${s.server} · engine ${s.zen.engine} · node ${s.node}`));
|
|
471
|
+
}
|
|
472
|
+
function truthy(v) {
|
|
473
|
+
return v !== undefined && /^(1|true|yes|on)$/i.test(v.trim());
|
|
474
|
+
}
|
|
475
|
+
function positive(v, fallback) {
|
|
476
|
+
const n = Number(v);
|
|
477
|
+
return v !== undefined && Number.isFinite(n) && n > 0 ? n : fallback;
|
|
478
|
+
}
|
|
479
|
+
//# sourceMappingURL=server.js.map
|
|
@@ -0,0 +1,47 @@
|
|
|
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
|
+
//# sourceMappingURL=container.d.ts.map
|