@tsplc/agent 0.2.16 → 0.2.18

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/src/agent.ts CHANGED
@@ -1,659 +1,192 @@
1
- import { execFile } from "node:child_process";
2
1
  import { timingSafeEqual } from "node:crypto";
3
- import { existsSync } from "node:fs";
4
- import { mkdir, readdir, readFile, stat, writeFile } from "node:fs/promises";
5
2
  import { join } from "node:path";
6
- import { setTimeout as delay } from "node:timers/promises";
7
- import { promisify } from "node:util";
8
- import {
9
- type ControllerLogin,
10
- explicitDownload,
11
- failureReason,
12
- findControllerLogin,
13
- gatewayImage,
14
- type LoginCommand,
15
- loginCommandSchema,
16
- openControllerLogin,
17
- resolveConfig,
18
- startWarmController,
19
- updateWarmController,
20
- } from "@tsplc/build";
21
- import {
22
- createDebugger,
23
- createDebugHandler,
24
- createLoginAdapter,
25
- type Debugger,
26
- loadManifest,
27
- LoginUnavailable,
28
- noLogin,
29
- timelineEntries,
30
- } from "@tsplc/debug";
3
+ import { loginCommandSchema } from "@tsplc/build";
31
4
  import { z } from "zod";
5
+ import { createDebugging } from "./debugging";
6
+ import { createDeployments } from "./deploy";
32
7
  import { discoverControllers, networkInterfaces } from "./discovery";
8
+ import { AgentError, errorMessage } from "./errors";
9
+ import { createLogin } from "./login";
10
+ import { createOperations } from "./operations";
33
11
  import {
34
- type AgentEvent,
35
- type AgentStatus,
36
- type Audit,
37
- auditSchema,
38
- clientHeaders,
39
- type Credentials,
40
- credentialsSchema,
41
- type Deployment,
42
- deploymentSchema,
43
- deployOptionsSchema,
44
- type Release,
45
- releaseSchema,
46
- type Target,
47
- targetSchema,
12
+ type AgentStatus,
13
+ clientIdentity,
14
+ credentialsSchema,
15
+ discoverSchema,
16
+ targetSchema,
48
17
  } from "./protocol";
49
- import { appendJsonl, readJsonl } from "./logs";
50
- import { loadRelease, readUpload, saveRelease } from "./releases";
18
+ import { storedCredentials } from "./secrets";
51
19
  import { createServerSupervisor } from "./server-process";
52
-
53
- const execute = promisify(execFile);
54
-
55
- /** The gateway reaches controllers through this Docker network. */
56
- const network = "tsplc-agent";
57
- /**
58
- * Builder containers reach the gateway by name on this internal network, which has no internet.
59
- * With internet, CODESYS asks a certificate authority about each DLL it loads, without caching
60
- * the answer, and opening a project takes minutes instead of seconds.
61
- */
62
- const codesysNetwork = "tsplc-agent-codesys";
63
- const gateway = { host: "tsplc-agent-gateway", port: 1217 };
64
- const loginContainer = "tsplc-agent-login";
65
- /** Keeps CODESYS running between deployments, so each skips starting it. */
66
- const deployContainer = "tsplc-agent-deploy";
67
- /** CODESYS reads the controller user from these for one operation; the agent never stores it. */
68
- const credentialNames = {
69
- usernameEnv: "TSPLC_DEVICE_USERNAME",
70
- passwordEnv: "TSPLC_DEVICE_PASSWORD",
71
- };
72
-
73
- class AgentError extends Error {
74
- constructor(
75
- message: string,
76
- readonly status: number,
77
- readonly downloadRequired = false,
78
- ) {
79
- super(message);
80
- }
81
- }
82
-
83
- const json = (body: unknown, status = 200) => Response.json(body, { status });
84
-
85
- const message = (error: unknown) => (error instanceof Error ? error.message : String(error));
86
-
87
- /** A login's state comes back within a second; one that takes this long waits on a hung worker. */
88
- const loginStateTimeout = 30_000;
89
- const stoppedAnswering = { error: "The login stopped answering" };
90
-
91
- /** Log entries a new debugger starts its timeline with. */
92
- const recentEntries = 500;
93
-
94
- /** Who sent a request, as the client reports it. */
95
- const clientOf = (request: Request) => {
96
- const header = (name: string) => request.headers.get(name)?.slice(0, 200) || undefined;
97
- return { user: header(clientHeaders.user), host: header(clientHeaders.host) };
98
- };
99
-
100
- /** How an audited login command reads in the log, or nothing for commands that only read. */
101
- const auditOf = (command: LoginCommand) => {
102
- switch (command.command) {
103
- case "write":
104
- case "force":
105
- return { command: command.command, values: command.values };
106
- case "unforce":
107
- return {
108
- command: command.restore ? "unforce --restore" : "unforce",
109
- values: Object.fromEntries(command.expressions.map((expression) => [expression, ""])),
110
- };
111
- case "start":
112
- case "stop":
113
- return { command: command.command, values: {} };
114
- case "reset":
115
- return { command: `reset ${command.kind.toLowerCase()}`, values: {} };
116
- case "state":
117
- case "read":
118
- return undefined;
119
- }
120
- };
20
+ import { openState } from "./state";
121
21
 
122
22
  const matches = (presented: string, token: string) => {
123
- const actual = Buffer.from(presented);
124
- const expected = Buffer.from(token);
125
- return actual.length === expected.length && timingSafeEqual(actual, expected);
126
- };
127
-
128
- const readJson = async <T>(path: string, schema: z.ZodType<T>) =>
129
- existsSync(path) ? schema.parse(JSON.parse(await readFile(path, "utf8"))) : null;
130
-
131
- const docker = (...args: string[]) => execute("docker", args).then(({ stdout }) => stdout.trim());
132
-
133
- const ensureNetwork = async (name: string, ...options: string[]) => {
134
- if (!(await docker("network", "ls", "--quiet", "--filter", `name=^${name}$`)))
135
- await docker("network", "create", ...options, name);
136
- };
137
-
138
- /** The gateway container stays up between operations, as a CODESYS gateway service would. */
139
- const ensureGateway = async () => {
140
- await ensureNetwork(network);
141
- await ensureNetwork(codesysNetwork, "--internal");
142
- if (!(await docker("container", "ls", "--quiet", "--filter", `name=^${gateway.host}$`))) {
143
- await docker("rm", "--force", gateway.host);
144
- await docker(
145
- "run",
146
- "--detach",
147
- "--restart",
148
- "unless-stopped",
149
- "--platform",
150
- "linux/amd64",
151
- "--network",
152
- network,
153
- "--name",
154
- gateway.host,
155
- gatewayImage,
156
- );
157
- }
158
- // Gateways started by earlier agents are only on `network`.
159
- const networks = await docker(
160
- "inspect",
161
- "--format",
162
- "{{json .NetworkSettings.Networks}}",
163
- gateway.host,
164
- );
165
- if (!(codesysNetwork in JSON.parse(networks)))
166
- await docker("network", "connect", codesysNetwork, gateway.host);
167
- };
168
-
169
- /** Hands the controller user to CODESYS through the environment for the duration of `run`. */
170
- const withCredentials = async <T>(credentials: Credentials, run: () => Promise<T>) => {
171
- process.env[credentialNames.usernameEnv] = credentials.username;
172
- process.env[credentialNames.passwordEnv] = credentials.password;
173
- try {
174
- return await run();
175
- } finally {
176
- delete process.env[credentialNames.usernameEnv];
177
- delete process.env[credentialNames.passwordEnv];
178
- }
179
- };
180
-
181
- /** Relays the newest controller job's progress log, which CODESYS appends to as it works. */
182
- const followProgress = (controller: string, emit: (event: AgentEvent) => void) => {
183
- const jobs = join(controller, ".codesys/controller/jobs");
184
- const since = Date.now();
185
- let following = true;
186
- const done = (async () => {
187
- let log: string | undefined;
188
- let offset = 0;
189
- while (following) {
190
- await delay(2000);
191
- if (!log && existsSync(jobs)) {
192
- for (const job of await readdir(jobs)) {
193
- const path = join(jobs, job, ".codesys/controller/progress.log");
194
- if (existsSync(path) && (await stat(path)).mtimeMs >= since) log = path;
195
- }
196
- }
197
- if (!log) continue;
198
- const text = await readFile(log, "utf8");
199
- for (const line of text.slice(offset).split("\n").filter(Boolean))
200
- emit({ kind: "progress", message: line.replace(/^\S+Z /, "") });
201
- offset = text.length;
202
- }
203
- })();
204
- return async () => {
205
- following = false;
206
- await done;
207
- };
23
+ const actual = Buffer.from(presented);
24
+ const expected = Buffer.from(token);
25
+ return actual.length === expected.length && timingSafeEqual(actual, expected);
208
26
  };
209
27
 
210
28
  export interface AgentOptions {
211
- /** Releases, the controller's download baseline and the selected target live here. */
212
- state: string;
213
- token: string;
214
- /** Accepted only for the debugger (`/debug/*`) and `GET /status`. */
215
- readToken?: string;
216
- /** The deployed server's health route; without it a server that stays up 5 s counts as started. */
217
- serverHealthUrl?: string;
218
- log: (message: string) => void;
29
+ /** Releases, the controller's download baseline and the selected target live here. */
30
+ state: string;
31
+ token: string;
32
+ /** Accepted only for the debugger (`/debug/*`) and `GET /status`. */
33
+ readToken?: string;
34
+ /** The deployed server's health route; without it a server that stays up 5 s counts as started. */
35
+ serverHealthUrl?: string;
36
+ log: (message: string) => void;
219
37
  }
220
38
 
221
39
  /** The plant agent's routes. It runs one deployment or login operation at a time. */
222
40
  export const createAgent = async (options: AgentOptions) => {
223
- const paths = {
224
- releases: join(options.state, "releases"),
225
- controller: join(options.state, "controller"),
226
- release: join(options.state, "release.json"),
227
- target: join(options.state, "target.json"),
228
- deployments: join(options.state, "deployments.jsonl"),
229
- audit: join(options.state, "audit.jsonl"),
230
- debug: join(options.state, "debug"),
231
- };
232
- await mkdir(options.state, { recursive: true });
233
- const server = createServerSupervisor({ healthUrl: options.serverHealthUrl, log: options.log });
234
- const deployed = await readJson(paths.release, releaseSchema);
235
- if (deployed?.server) server.start(join(paths.releases, deployed.server));
236
- let busy: string | undefined;
237
-
238
- const requireTarget = async () => {
239
- const target = await readJson(paths.target, targetSchema);
240
- if (!target) throw new AgentError("Select the controller first: tsplc target", 409);
241
- return target;
242
- };
243
-
244
- /** The release's build config, aimed at `target` through the agent's gateway. */
245
- const controllerConfig = (release: Awaited<ReturnType<typeof saveRelease>>, target: Target) => ({
246
- ...resolveConfig(
247
- {
248
- ...release.manifest.config,
249
- online: { network: codesysNetwork, gateway, device: target, credentials: credentialNames },
250
- },
251
- join(release.directory, "manifest.json"),
252
- ),
253
- // The baseline outlives releases: an online change compares against the last download.
254
- outDir: paths.controller,
255
- });
256
-
257
- const currentRelease = async () => {
258
- const release = await readJson(paths.release, releaseSchema);
259
- if (!release) throw new AgentError("Nothing has been deployed yet: tsplc deploy", 409);
260
- return loadRelease(paths.releases, release.id);
261
- };
262
-
263
- /** CODESYS starts for the deployed release in the background, so the first deployment finds it running. */
264
- const warming = (async () => {
265
- const target = await readJson(paths.target, targetSchema);
266
- if (!deployed || !target) return;
267
- await ensureGateway();
268
- const release = await loadRelease(paths.releases, deployed.id);
269
- await startWarmController(controllerConfig(release, target), deployContainer);
270
- })().catch((error: unknown) => {
271
- options.log(
272
- `Starting CODESYS failed: ${error instanceof Error ? error.message : String(error)}`,
273
- );
274
- });
275
-
276
- /** Login commands, the debugger's reads among them, run one at a time. */
277
- let loginGeneration = 0;
278
- let commands: Promise<unknown> = Promise.resolve();
279
- const enqueue = <Result>(run: () => Promise<Result>) => {
280
- const generation = loginGeneration;
281
- const sent = commands.then(() => {
282
- if (generation !== loginGeneration) throw new AgentError("The login was closed", 409);
283
- return run();
284
- });
285
- commands = sent.catch(() => undefined);
286
- return sent;
287
- };
288
- const send = (login: ControllerLogin, loginCommand: LoginCommand) =>
289
- enqueue(() => login.send(loginCommand));
290
-
291
- /** What the debugger reads through: the open login, which it never opens itself. */
292
- const readLogin = async ([first, ...rest]: string[]) => {
293
- if (busy === "a login")
294
- throw new LoginUnavailable("The engineering login is opening", { state: "connecting" });
295
- if (busy) throw new LoginUnavailable(`Live values pause during ${busy}`);
296
- const login = await findControllerLogin(loginContainer);
297
- if (!login) throw new LoginUnavailable(noLogin);
298
- if (!first) return {};
299
- const result = await send(login, { command: "read", expressions: [first, ...rest] });
300
- if (!("values" in result)) throw new Error("The login answered a read without values");
301
- return result.values;
302
- };
303
-
304
- /**
305
- * The deployed release's debugger, when it has a debug manifest. It reads the controller
306
- * through the agent's engineering login, and the server's telemetry and requests through the
307
- * server's health origin.
308
- */
309
- const startDebugger = async () => {
310
- const release = await readJson(paths.release, releaseSchema);
311
- if (!release) return null;
312
- const { directory, manifest: releaseManifest } = await loadRelease(paths.releases, release.id);
313
- const manifestFile = join(directory, "debug.json");
314
- if (!existsSync(manifestFile)) return null;
315
- const manifest = await loadManifest(manifestFile);
316
- const serverToken =
317
- releaseManifest.serverTokenEnv && process.env[releaseManifest.serverTokenEnv];
318
- const debug = await createDebugger({
319
- manifest,
320
- adapter: createLoginAdapter({
321
- read: readLogin,
322
- probe: manifest.build.target,
323
- endpoint: "the agent's login",
324
- }),
325
- stateDirectory: paths.debug,
326
- watch: releaseManifest.debug?.watch ?? {},
327
- ...(options.serverHealthUrl &&
328
- serverToken && {
329
- server: { url: new URL(options.serverHealthUrl).origin, token: serverToken },
330
- }),
331
- release: { id: release.id, deployedAt: release.deployedAt, operation: release.operation },
332
- timeline: [
333
- ...(await readJsonl(paths.deployments, deploymentSchema, recentEntries)).map(
334
- ({ at, ...deployment }) => timelineEntries.deploy(at, deployment),
335
- ),
336
- ...(await readJsonl(paths.audit, auditSchema, recentEntries)).map(({ at, ...audit }) =>
337
- timelineEntries.audit(at, audit),
338
- ),
339
- ],
340
- log: options.log,
341
- });
342
- return { debug, handle: createDebugHandler(debug, options.log) };
343
- };
344
- type Debugging = { debug: Debugger; handle: ReturnType<typeof createDebugHandler> } | null;
345
- const debuggerFailed = (error: unknown): Debugging => {
346
- options.log(`Starting the debugger failed: ${message(error)}`);
347
- return null;
348
- };
349
- let debugging: Promise<Debugging> = startDebugger().catch(debuggerFailed);
350
- /** Replaces the debugger after the release changes. */
351
- const restartDebugger = () => {
352
- debugging = debugging.then(async (current) => {
353
- await current?.debug.close();
354
- return startDebugger().catch(debuggerFailed);
355
- });
356
- };
357
-
358
- /** Streams one exclusive operation's events, then its result, as newline-delimited JSON. */
359
- const operation = (
360
- name: string,
361
- run: (emit: (event: AgentEvent) => void) => Promise<unknown>,
362
- ) => {
363
- if (busy) throw new AgentError(`The agent is busy with ${busy}`, 409);
364
- busy = name;
365
- const encoder = new TextEncoder();
366
- // A client that disconnects doesn't stop the operation; it just stops hearing about it.
367
- let listening = true;
368
- return new Response(
369
- new ReadableStream({
370
- start: async (controller) => {
371
- const write = (text: string) => {
372
- if (listening) controller.enqueue(encoder.encode(text));
373
- };
374
- const emit = (event: AgentEvent) => write(`${JSON.stringify(event)}\n`);
375
- // CODESYS can stay silent for minutes; blank lines keep proxies from closing the stream.
376
- const heartbeat = setInterval(() => write("\n"), 15_000);
377
- try {
378
- emit({ kind: "done", result: await run(emit) });
379
- } catch (error) {
380
- options.log(`${name} failed: ${error instanceof Error ? error.stack : String(error)}`);
381
- emit({
382
- kind: "error",
383
- message: error instanceof Error ? error.message : String(error),
384
- downloadRequired:
385
- (error instanceof AgentError && error.downloadRequired) ||
386
- (error instanceof Error && error.message.includes(explicitDownload)),
387
- });
388
- } finally {
389
- clearInterval(heartbeat);
390
- busy = undefined;
391
- if (listening) controller.close();
392
- }
393
- },
394
- cancel: () => {
395
- listening = false;
396
- },
397
- }),
398
- { headers: { "Content-Type": "application/x-ndjson" } },
399
- );
400
- };
401
-
402
- const deploy = async (form: FormData, client: ReturnType<typeof clientOf>) => {
403
- const settings = deployOptionsSchema.parse(JSON.parse(z.string().parse(form.get("options"))));
404
- const upload = await readUpload(form);
405
- const target = await requireTarget();
406
- if (await findControllerLogin(loginContainer))
407
- throw new AgentError("A login is open; log out before deploying: tsplc logout", 409);
408
- return operation("a deployment", async (emit) => {
409
- const release = await saveRelease(paths.releases, upload);
410
- const config = controllerConfig(release, target);
411
- if (
412
- !settings.download &&
413
- !existsSync(join(paths.controller, ".codesys/controller/current.json"))
414
- )
415
- throw new AgentError(
416
- "The controller has no application downloaded by this agent; only a full download can deploy",
417
- 409,
418
- true,
419
- );
420
- const previous = await readJson(paths.release, releaseSchema);
421
- // Server paths are relative to the releases directory.
422
- const serverPath = release.manifest.server && `${release.id}/${release.manifest.server}`;
423
- if (serverPath) {
424
- emit({ kind: "progress", message: "Starting the new server" });
425
- await server.replace(join(paths.releases, serverPath));
426
- }
427
- const kind = settings.download ? "download" : "online-change";
428
- emit({ kind: "progress", message: `Starting the ${kind}` });
429
- await ensureGateway();
430
- await warming;
431
- const stopFollowing = followProgress(paths.controller, emit);
432
- const receipt = await updateWarmController(config, deployContainer, kind, {
433
- initializeUser: settings.initializeUser,
434
- credentials: settings.credentials,
435
- })
436
- .catch(async (failure: unknown) => {
437
- if (serverPath) {
438
- emit({ kind: "progress", message: "Restoring the previous server" });
439
- await (previous?.server
440
- ? server.replace(join(paths.releases, previous.server))
441
- : server.stop());
442
- }
443
- throw failure;
444
- })
445
- .finally(stopFollowing);
446
- const deployedRelease: Release = {
447
- id: release.id,
448
- deployedAt: new Date().toISOString(),
449
- operation: kind,
450
- controllerIds: receipt.controllerIds,
451
- // A release without a server leaves the previous one running.
452
- server: serverPath ?? previous?.server,
453
- };
454
- await writeFile(paths.release, JSON.stringify(deployedRelease, null, 2));
455
- const debugManifest = join(release.directory, "debug.json");
456
- const deployment: Deployment = {
457
- at: deployedRelease.deployedAt,
458
- release: release.id,
459
- ...(existsSync(debugManifest) && { build: (await loadManifest(debugManifest)).build.id }),
460
- operation: kind,
461
- ...client,
462
- };
463
- await appendJsonl(paths.deployments, deployment);
464
- restartDebugger();
465
- return deployedRelease;
466
- });
467
- };
468
-
469
- const openLogin = async (credentials: Credentials) => {
470
- const release = await currentRelease();
471
- const config = controllerConfig(release, await requireTarget());
472
- return operation("a login", async (emit) => {
473
- if (await findControllerLogin(loginContainer))
474
- throw new AgentError("A login is already open", 409);
475
- emit({ kind: "progress", message: "Logging in; CODESYS takes minutes to start" });
476
- await ensureGateway();
477
- const login = await withCredentials(credentials, () =>
478
- openControllerLogin(config, loginContainer),
479
- );
480
- return send(login, { command: "state" });
481
- });
482
- };
483
-
484
- const requireLogin = async () => {
485
- if (busy) throw new AgentError(`The agent is busy with ${busy}`, 409);
486
- const generation = loginGeneration;
487
- const login = await findControllerLogin(loginContainer);
488
- if (generation !== loginGeneration) throw new AgentError("The login was closed", 409);
489
- if (busy) throw new AgentError(`The agent is busy with ${busy}`, 409);
490
- if (!login) throw new AgentError("No login is open: tsplc login", 409);
491
- return login;
492
- };
493
-
494
- /** Runs a login command; one that changes the controller goes to the audit log, with the values it replaces. */
495
- const command = async (loginCommand: LoginCommand, client: ReturnType<typeof clientOf>) => {
496
- const login = await requireLogin();
497
- const change = auditOf(loginCommand);
498
- if (!change) return send(login, loginCommand);
499
- return enqueue(async () => {
500
- const [first, ...rest] = Object.keys(change.values);
501
- // Without the old values the command is still worth running and recording.
502
- const previous = first
503
- ? await login
504
- .send({ command: "read", expressions: [first, ...rest] })
505
- .then((result) => ("values" in result ? result.values : undefined))
506
- .catch(() => undefined)
507
- : undefined;
508
- const audit = async (error?: unknown) => {
509
- const entry: Audit = {
510
- at: new Date().toISOString(),
511
- ...change,
512
- ...(previous && { previous }),
513
- ...client,
514
- release: (await readJson(paths.release, releaseSchema))?.id,
515
- ...(error !== undefined && { error: message(error) }),
516
- };
517
- await appendJsonl(paths.audit, entry);
518
- const { at, ...details } = entry;
519
- (await debugging)?.debug.record(timelineEntries.audit(at, details));
520
- };
521
- try {
522
- const result = await login.send(loginCommand);
523
- await audit();
524
- return result;
525
- } catch (error) {
526
- await audit(error);
527
- throw error;
528
- }
529
- });
530
- };
531
-
532
- /**
533
- * The open login's state. A login that lost the controller, or whose worker died or hangs, is
534
- * reported as failed, so the CLI can log it out and open a new one.
535
- */
536
- const loginStatus = async (): Promise<AgentStatus["login"]> => {
537
- const login = await findControllerLogin(loginContainer);
538
- if (!login) return null;
539
- if (!(await login.ready()))
540
- // A login still opening has its container but doesn't answer yet.
541
- return busy === "a login" ? null : stoppedAnswering;
542
- try {
543
- const state = await Promise.race([
544
- send(login, { command: "state" }),
545
- delay(loginStateTimeout, null),
546
- ]);
547
- if (!state) return stoppedAnswering;
548
- return "state" in state ? state : null;
549
- } catch (error) {
550
- return { error: failureReason(error) };
551
- }
552
- };
553
-
554
- const status = async (): Promise<AgentStatus> => ({
555
- target: await readJson(paths.target, targetSchema),
556
- release: await readJson(paths.release, releaseSchema),
557
- server: server.status() ?? null,
558
- login: await loginStatus(),
559
- });
560
-
561
- const route = async (request: Request): Promise<Response> => {
562
- const { pathname } = new URL(request.url);
563
- const key = `${request.method} ${pathname}`;
564
- switch (key) {
565
- case "GET /status":
566
- return json(await status());
567
- case "GET /interfaces":
568
- return json(networkInterfaces());
569
- case "POST /discover": {
570
- const { name } = z.strictObject({ name: z.string() }).parse(await request.json());
571
- const selected = networkInterfaces().find((network) => network.name === name);
572
- if (!selected) throw new AgentError(`No IPv4 interface named ${name}`, 404);
573
- return json(await discoverControllers(selected));
574
- }
575
- case "PUT /target": {
576
- const target = targetSchema.parse(await request.json());
577
- await writeFile(paths.target, JSON.stringify(target, null, 2));
578
- return json(target);
579
- }
580
- case "GET /variables":
581
- return json((await currentRelease()).manifest.variables);
582
- case "POST /deploy":
583
- return deploy(await request.formData(), clientOf(request));
584
- case "POST /login":
585
- return openLogin(credentialsSchema.parse(await request.json()));
586
- case "POST /login/command":
587
- return json(
588
- await command(loginCommandSchema.parse(await request.json()), clientOf(request)),
589
- );
590
- case "DELETE /login": {
591
- const login = await requireLogin();
592
- busy = "a logout";
593
- loginGeneration++;
594
- try {
595
- const failure = await login.close();
596
- commands = Promise.resolve();
597
- if (failure)
598
- options.log(`The login couldn't log out (${failure}); its container was removed`);
599
- return json(failure ? { failure } : {});
600
- } finally {
601
- busy = undefined;
602
- }
603
- }
604
- default:
605
- return json({ error: `No route ${key}` }, 404);
606
- }
607
- };
608
-
609
- /** The debugger's UI and API under `/debug`. */
610
- const debugRoute = async (request: Request, route: string) => {
611
- const current = await debugging;
612
- if (!current)
613
- return json(
614
- { error: "The deployed release has no debug manifest, or the debugger failed to start" },
615
- 503,
616
- );
617
- return current.handle(request, route);
618
- };
619
-
620
- return {
621
- fetch: async (request: Request) => {
622
- const { pathname, search, searchParams } = new URL(request.url);
623
- const debugPath = pathname.startsWith("/debug/");
624
- // The UI's relative links need the trailing slash.
625
- if (pathname === "/debug")
626
- return new Response(null, { status: 308, headers: { Location: `/debug/${search}` } });
627
- // The page and its script hold no data, and a browser loads the script without the token.
628
- if (request.method === "GET" && (pathname === "/debug/" || pathname === "/debug/ui.js"))
629
- return debugRoute(request, pathname.slice("/debug".length));
630
- // EventSource can't send headers, so the debugger also takes `?token=`.
631
- const presented =
632
- /^Bearer (.+)$/.exec(request.headers.get("authorization") ?? "")?.[1] ??
633
- (debugPath ? searchParams.get("token") : null) ??
634
- "";
635
- const full = matches(presented, options.token);
636
- const read =
637
- options.readToken !== undefined &&
638
- matches(presented, options.readToken) &&
639
- (debugPath || (request.method === "GET" && pathname === "/status"));
640
- if (!full && !read) return json({ error: "Unauthorized" }, 401);
641
- try {
642
- if (debugPath) return await debugRoute(request, pathname.slice("/debug".length));
643
- return await route(request);
644
- } catch (error) {
645
- if (error instanceof AgentError) return json({ error: error.message }, error.status);
646
- if (error instanceof z.ZodError) return json({ error: z.prettifyError(error) }, 400);
647
- options.log(
648
- `${request.method} ${request.url} failed: ${error instanceof Error ? error.stack : String(error)}`,
649
- );
650
- return json({ error: error instanceof Error ? error.message : String(error) }, 500);
651
- }
652
- },
653
- /** Stops the debugger and the supervised server; a login container keeps running for the next agent. */
654
- stop: async () => {
655
- await (await debugging)?.debug.close();
656
- await server.stop();
657
- },
658
- };
41
+ const { log } = options;
42
+ const state = await openState(options.state);
43
+ const server = createServerSupervisor({
44
+ healthUrl: options.serverHealthUrl,
45
+ log,
46
+ });
47
+ const deployed = await state.release();
48
+ if (deployed?.server) {
49
+ server.start(join(state.paths.releases, deployed.server));
50
+ }
51
+ const operations = createOperations(log);
52
+ const login = createLogin({
53
+ state,
54
+ operations,
55
+ onAudit: (entry) => debugging.record(entry),
56
+ log,
57
+ });
58
+ const debugging = createDebugging({
59
+ state,
60
+ readLogin: login.read,
61
+ serverHealthUrl: options.serverHealthUrl,
62
+ log,
63
+ });
64
+ const deployments = createDeployments({
65
+ state,
66
+ operations,
67
+ server,
68
+ debugging,
69
+ log,
70
+ });
71
+
72
+ const route = async (request: Request): Promise<Response> => {
73
+ const { pathname } = new URL(request.url);
74
+ const key = `${request.method} ${pathname}`;
75
+ switch (key) {
76
+ case "GET /status": {
77
+ const status: AgentStatus = {
78
+ target: await state.target(),
79
+ release: await state.release(),
80
+ server: server.status() ?? null,
81
+ login: await login.status(),
82
+ credentialsStored: (await storedCredentials()) !== null,
83
+ };
84
+ return Response.json(status);
85
+ }
86
+ case "GET /interfaces":
87
+ return Response.json(networkInterfaces());
88
+ case "POST /discover": {
89
+ const { name } = discoverSchema.parse(await request.json());
90
+ const selected = networkInterfaces().find(
91
+ (network) => network.name === name,
92
+ );
93
+ if (!selected) {
94
+ throw new AgentError(`No IPv4 interface named ${name}`, 404);
95
+ }
96
+ return Response.json(await discoverControllers(selected));
97
+ }
98
+ case "PUT /target": {
99
+ const target = targetSchema.parse(await request.json());
100
+ await state.setTarget(target);
101
+ return Response.json(target);
102
+ }
103
+ case "GET /variables":
104
+ return Response.json((await state.requireRelease()).manifest.variables);
105
+ case "POST /deploy":
106
+ return deployments.deploy(
107
+ await request.formData(),
108
+ clientIdentity(request),
109
+ );
110
+ case "POST /login":
111
+ return login.open(
112
+ credentialsSchema.nullable().parse(await request.json()),
113
+ );
114
+ case "POST /login/command":
115
+ return Response.json(
116
+ await login.command(
117
+ loginCommandSchema.parse(await request.json()),
118
+ clientIdentity(request),
119
+ ),
120
+ );
121
+ case "DELETE /login":
122
+ return Response.json(await login.logout());
123
+ default:
124
+ return Response.json({ error: `No route ${key}` }, { status: 404 });
125
+ }
126
+ };
127
+
128
+ return {
129
+ fetch: async (request: Request) => {
130
+ const { pathname, search, searchParams } = new URL(request.url);
131
+ const debugPath = pathname.startsWith("/debug/");
132
+ // The UI's relative links need the trailing slash.
133
+ if (pathname === "/debug") {
134
+ return new Response(null, {
135
+ status: 308,
136
+ headers: { Location: `/debug/${search}` },
137
+ });
138
+ }
139
+ // The page and its script hold no data, and a browser loads the script without the token.
140
+ if (
141
+ request.method === "GET" &&
142
+ (pathname === "/debug/" || pathname === "/debug/ui.js")
143
+ ) {
144
+ return debugging.handle(request, pathname.slice("/debug".length));
145
+ }
146
+ // EventSource can't send headers, so the debugger also takes `?token=`.
147
+ const presented =
148
+ /^Bearer (.+)$/.exec(request.headers.get("authorization") ?? "")?.[1] ??
149
+ (debugPath ? searchParams.get("token") : null) ??
150
+ "";
151
+ const full = matches(presented, options.token);
152
+ const read =
153
+ options.readToken !== undefined &&
154
+ matches(presented, options.readToken) &&
155
+ (debugPath || (request.method === "GET" && pathname === "/status"));
156
+ if (!full && !read) {
157
+ return Response.json({ error: "Unauthorized" }, { status: 401 });
158
+ }
159
+ try {
160
+ if (debugPath) {
161
+ return await debugging.handle(
162
+ request,
163
+ pathname.slice("/debug".length),
164
+ );
165
+ }
166
+ return await route(request);
167
+ } catch (error) {
168
+ if (error instanceof AgentError) {
169
+ return Response.json(
170
+ { error: error.message },
171
+ { status: error.status },
172
+ );
173
+ }
174
+ if (error instanceof z.ZodError) {
175
+ return Response.json(
176
+ { error: z.prettifyError(error) },
177
+ { status: 400 },
178
+ );
179
+ }
180
+ log(
181
+ `${request.method} ${request.url} failed: ${error instanceof Error ? error.stack : String(error)}`,
182
+ );
183
+ return Response.json({ error: errorMessage(error) }, { status: 500 });
184
+ }
185
+ },
186
+ /** Stops the debugger and the supervised server; a login container keeps running for the next agent. */
187
+ stop: async () => {
188
+ await debugging.close();
189
+ await server.stop();
190
+ },
191
+ };
659
192
  };