@tsplc/agent 0.5.9 → 0.5.12

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.
Files changed (51) hide show
  1. package/dist/cli.js +2660 -525
  2. package/dist/cli.js.map +32 -18
  3. package/dist/client.js +262 -37
  4. package/dist/client.js.map +4 -4
  5. package/dist/index.js +2325 -415
  6. package/dist/index.js.map +27 -14
  7. package/package.json +6 -5
  8. package/src/access.ts +276 -0
  9. package/src/agent.ts +130 -29
  10. package/src/audit.ts +64 -0
  11. package/src/cli.ts +81 -5
  12. package/src/client.ts +204 -36
  13. package/src/controller.ts +60 -0
  14. package/src/dashboard/index.ts +118 -0
  15. package/src/dashboard/ui/access.ts +192 -0
  16. package/src/dashboard/ui/actions.ts +192 -0
  17. package/src/dashboard/ui/api.ts +158 -0
  18. package/src/dashboard/ui/app.ts +41 -0
  19. package/src/dashboard/ui/approval.ts +132 -0
  20. package/src/dashboard/ui/audit.ts +115 -0
  21. package/src/dashboard/ui/contract.ts +19 -0
  22. package/src/dashboard/ui/dashboard.css +1332 -0
  23. package/src/dashboard/ui/deployment.ts +432 -0
  24. package/src/dashboard/ui/deployments.ts +317 -0
  25. package/src/dashboard/ui/details.ts +240 -0
  26. package/src/dashboard/ui/dom.ts +91 -0
  27. package/src/dashboard/ui/environment.ts +326 -0
  28. package/src/dashboard/ui/format.ts +118 -0
  29. package/src/dashboard/ui/logs.ts +127 -0
  30. package/src/dashboard/ui/main.ts +86 -0
  31. package/src/dashboard/ui/overlay.ts +146 -0
  32. package/src/dashboard/ui/shell.ts +192 -0
  33. package/src/dashboard/ui/source.ts +144 -0
  34. package/src/deploy.ts +174 -144
  35. package/src/deployments/health.ts +80 -0
  36. package/src/deployments/retention.ts +45 -0
  37. package/src/deployments/routes.ts +273 -0
  38. package/src/deployments/runner.ts +877 -0
  39. package/src/deployments/store.ts +233 -0
  40. package/src/environment.ts +284 -0
  41. package/src/index.ts +4 -0
  42. package/src/login.ts +17 -0
  43. package/src/operations.ts +6 -1
  44. package/src/protocol.ts +259 -2
  45. package/src/releases.ts +73 -1
  46. package/src/routes.ts +52 -0
  47. package/src/secrets.ts +74 -4
  48. package/src/server-process.ts +33 -16
  49. package/src/sessions.ts +58 -0
  50. package/src/state.ts +2 -0
  51. package/src/tailscale.ts +112 -0
package/src/protocol.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { rollbackSchema } from "@tsplc/build";
2
- import { tsplcConfigSchema } from "@tsplc/config";
1
+ import { onlineChangeFindingSchema, rollbackSchema } from "@tsplc/build";
2
+ import { secretValue, tsplcConfigSchema } from "@tsplc/config";
3
3
  import { releaseConfigSchema, tcpPort } from "@tsplc/config/build";
4
4
  import { z } from "zod";
5
5
  import { version } from "../package.json";
@@ -49,6 +49,14 @@ export const variableSchema = z.strictObject({
49
49
  });
50
50
  export type Variable = z.infer<typeof variableSchema>;
51
51
 
52
+ /** A target's values, by the config's rule for them. */
53
+ const targetValuesSchema =
54
+ tsplcConfigSchema.shape.targets.unwrap().valueType.shape.values;
55
+
56
+ /** The config's rule for a variable's name: an environment variable's. */
57
+ export const variableName =
58
+ tsplcConfigSchema.shape.secrets.unwrap().shape.names.element;
59
+
52
60
  /**
53
61
  * What `tsplc deploy` uploads beside its files. `config` is the build config with paths
54
62
  * relative to the release: `st/`, `template.project` and `libraries/`.
@@ -73,6 +81,8 @@ export const releaseManifestSchema = z.strictObject({
73
81
  serverTokenEnv: z.string().nonempty().optional(),
74
82
  /** The project's `secrets`, whose placeholders in the ST the agent fills in from Bun.secrets. */
75
83
  secrets: tsplcConfigSchema.shape.secrets,
84
+ /** The values of the target it was built for, which its server starts with; none in a release from before 0.5.12. */
85
+ values: targetValuesSchema,
76
86
  });
77
87
  export type ReleaseManifest = z.infer<typeof releaseManifestSchema>;
78
88
 
@@ -85,6 +95,8 @@ export const deployOptionsSchema = z
85
95
  /** A full download stops the application; without it only an online change is applied. */
86
96
  download: z.boolean(),
87
97
  initializeUser: z.boolean(),
98
+ /** How `POST /api/deployments` queues it; `POST /deploy` runs it at once and ignores this. */
99
+ deployment: z.lazy(() => deploymentRequestSchema).optional(),
88
100
  })
89
101
  .refine(
90
102
  (options) => options.credentials || !options.initializeUser,
@@ -275,3 +287,248 @@ export const auditSchema = z.strictObject({
275
287
  error: z.string().optional(),
276
288
  });
277
289
  export type Audit = z.infer<typeof auditSchema>;
290
+
291
+ /**
292
+ * Who may do what on the agent's dashboard and API, each role including the ones before it: a
293
+ * viewer reads deployments, logs, the debugger and the audit log; a deployer also deploys,
294
+ * approves, cancels, redeploys, rolls back and restarts the server; an admin also manages the
295
+ * environment's secrets and who has which role.
296
+ */
297
+ export const roles = ["viewer", "deployer", "admin"] as const;
298
+ export const roleSchema = z.enum(roles);
299
+ export type Role = z.infer<typeof roleSchema>;
300
+
301
+ /** Whether `role` includes `required`. */
302
+ export const allows = (role: Role, required: Role) =>
303
+ roles.indexOf(role) >= roles.indexOf(required);
304
+
305
+ /** Who made a request, and how the agent knows. */
306
+ export const identitySchema = z.strictObject({
307
+ /** The Tailscale login, or null for a token or a request from the agent's own PC. */
308
+ login: z.string().nullable(),
309
+ /** A name to show: the Tailscale display name, or how the token or PC is known. */
310
+ name: z.string(),
311
+ role: roleSchema,
312
+ /** `server`: the deployed server, with the token the agent started it with. */
313
+ via: z.enum(["tailscale", "token", "local", "server"]),
314
+ });
315
+ export type Identity = z.infer<typeof identitySchema>;
316
+
317
+ /** The commit a deployment was built from, when `tsplc deploy` ran in a git checkout. */
318
+ export const gitSourceSchema = z.strictObject({
319
+ commit: z.string().nonempty(),
320
+ branch: z.string().nullable(),
321
+ /** Uncommitted changes went into the build. */
322
+ dirty: z.boolean(),
323
+ /** The commit's subject line. */
324
+ message: z.string().nullable(),
325
+ });
326
+ export type GitSource = z.infer<typeof gitSourceSchema>;
327
+
328
+ /**
329
+ * How a deployment applies: `apply` runs it as soon as it is its turn; `review` builds it and
330
+ * checks what an online change would do, then waits for someone to approve it.
331
+ */
332
+ export const deploymentModeSchema = z.enum(["apply", "review"]);
333
+ export type DeploymentMode = z.infer<typeof deploymentModeSchema>;
334
+
335
+ /**
336
+ * Where a deployment is. `awaitingApproval` waits on a person: a review to apply, or a full
337
+ * download that would stop the line. A finished deployment is `ready`, `error` or `canceled`.
338
+ */
339
+ export const deploymentStateSchema = z.enum([
340
+ "queued",
341
+ "building",
342
+ "awaitingApproval",
343
+ "applying",
344
+ "starting",
345
+ "verifying",
346
+ "ready",
347
+ "error",
348
+ "canceled",
349
+ ]);
350
+ export type DeploymentState = z.infer<typeof deploymentStateSchema>;
351
+
352
+ /** The steps a deployment goes through, in order; a deployment skips the ones it doesn't need. */
353
+ export const deploymentPhaseNameSchema = z.enum([
354
+ "queue",
355
+ "build",
356
+ "review",
357
+ "apply",
358
+ "server",
359
+ "health",
360
+ ]);
361
+
362
+ const deploymentIdSchema = z.string().regex(/^dpl_[a-z0-9]{16,32}$/);
363
+
364
+ /**
365
+ * A deployment as the agent keeps it, in `deployments/<id>/record.json` of its state directory.
366
+ * Every record of the last 14 days is kept, and always the running one and the last that was
367
+ * healthy, with their releases.
368
+ */
369
+ export const deploymentRecordSchema = z.strictObject({
370
+ id: deploymentIdSchema,
371
+ release: z.string(),
372
+ /** The debug manifest's build id, when the release has one. */
373
+ build: z.string().nullable(),
374
+ createdAt: z.iso.datetime(),
375
+ updatedAt: z.iso.datetime(),
376
+ /** An upload from `tsplc deploy`, or a release the agent already had, deployed again. */
377
+ origin: z.discriminatedUnion("kind", [
378
+ z.strictObject({ kind: z.literal("upload") }),
379
+ z.strictObject({ kind: z.literal("redeploy"), from: deploymentIdSchema }),
380
+ z.strictObject({ kind: z.literal("rollback"), from: deploymentIdSchema }),
381
+ ]),
382
+ git: gitSourceSchema.nullable(),
383
+ /** Who asked for it: the identity behind the request, with the deploying machine's user and host. */
384
+ requestedBy: z.strictObject({
385
+ identity: identitySchema.omit({ role: true }),
386
+ user: z.string().nullable(),
387
+ host: z.string().nullable(),
388
+ }),
389
+ mode: deploymentModeSchema,
390
+ /** What it applies or applied: an online change unless a full download was asked for or approved. */
391
+ operation: deployOperationSchema,
392
+ state: deploymentStateSchema,
393
+ phases: z.array(
394
+ z.strictObject({
395
+ name: deploymentPhaseNameSchema,
396
+ startedAt: z.iso.datetime(),
397
+ finishedAt: z.iso.datetime().nullable(),
398
+ outcome: z.enum(["running", "ok", "failed", "skipped"]),
399
+ }),
400
+ ),
401
+ /** What the online-change check found: refusals, and what the change restarts. */
402
+ findings: z.array(onlineChangeFindingSchema),
403
+ /** What it waits on while `awaitingApproval`. */
404
+ approval: z
405
+ .strictObject({
406
+ reason: z.enum(["review", "downloadRequired"]),
407
+ message: z.string(),
408
+ })
409
+ .nullable(),
410
+ error: z
411
+ .strictObject({
412
+ message: z.string(),
413
+ downloadRequired: z.boolean(),
414
+ rollback: rollbackSchema.optional(),
415
+ })
416
+ .nullable(),
417
+ controllerIds: z
418
+ .strictObject({ codeId: z.string(), dataId: z.string() })
419
+ .nullable(),
420
+ /** What the check after applying found; null until it ran. */
421
+ health: z
422
+ .strictObject({
423
+ controller: z.enum(["ok", "failed"]),
424
+ server: z.enum(["ok", "failed", "none"]),
425
+ plc: z.enum(["ok", "failed", "unknown"]),
426
+ detail: z.string().nullable(),
427
+ })
428
+ .nullable(),
429
+ /** When it became the running deployment, and when another replaced it; null until and while. */
430
+ activeFrom: z.iso.datetime().nullable(),
431
+ activeUntil: z.iso.datetime().nullable(),
432
+ });
433
+ export type DeploymentRecord = z.infer<typeof deploymentRecordSchema>;
434
+
435
+ /** One line of a deployment's log, `deployments/<id>/log.jsonl`. */
436
+ export const deploymentLogLineSchema = z.strictObject({
437
+ /** Counts from 1 within the deployment; `?after=` resumes from it. */
438
+ seq: z.number().int().positive(),
439
+ at: z.iso.datetime(),
440
+ level: z.enum(["info", "warning", "error"]),
441
+ phase: deploymentPhaseNameSchema.nullable(),
442
+ message: z.string(),
443
+ });
444
+ export type DeploymentLogLine = z.infer<typeof deploymentLogLineSchema>;
445
+
446
+ /**
447
+ * What `tsplc deploy` sends with a release to `POST /api/deployments`, in the upload's `options`
448
+ * beside the existing deploy options.
449
+ */
450
+ export const deploymentRequestSchema = z.strictObject({
451
+ mode: deploymentModeSchema,
452
+ git: gitSourceSchema.nullable(),
453
+ });
454
+ export type DeploymentRequest = z.infer<typeof deploymentRequestSchema>;
455
+
456
+ /** `POST /api/deployments`'s answer: the queued deployment and the dashboard page that shows it. */
457
+ export const deploymentCreatedSchema = z.strictObject({
458
+ id: deploymentIdSchema,
459
+ url: z.string(),
460
+ });
461
+
462
+ /** `GET /api/deployments`: newest first, with the running and last healthy ones named. */
463
+ export const deploymentListSchema = z.strictObject({
464
+ deployments: z.array(deploymentRecordSchema),
465
+ current: deploymentIdSchema.nullable(),
466
+ lastGood: deploymentIdSchema.nullable(),
467
+ });
468
+
469
+ /** `POST /api/deployments/:id/approve`: apply it, as a full download when one is required. */
470
+ export const approveSchema = z.strictObject({ download: z.boolean() });
471
+
472
+ /** `POST /api/deployments/:id/redeploy`: deploy its release again. */
473
+ export const redeploySchema = z.strictObject({ mode: deploymentModeSchema });
474
+
475
+ /** `GET /api/deployments/:id/source`: the release's files, by path, with their sizes in bytes. */
476
+ export const deploymentSourceSchema = z.strictObject({
477
+ files: z.array(
478
+ z.strictObject({ path: z.string(), size: z.number().int().nonnegative() }),
479
+ ),
480
+ });
481
+
482
+ /** A secret the deployed release's config declares, or one stored without a declaration: never its value. */
483
+ export const environmentEntrySchema = z.strictObject({
484
+ name: z.string(),
485
+ declared: z.boolean(),
486
+ set: z.boolean(),
487
+ });
488
+ export type EnvironmentEntry = z.infer<typeof environmentEntrySchema>;
489
+
490
+ /** `GET /api/environment`: the plant PC's variables, and what the running release was built with. */
491
+ export const environmentSchema = z.strictObject({
492
+ /** The plain values the running release was built with, from the config's target and this PC. */
493
+ values: targetValuesSchema,
494
+ /** The plain variables stored on this PC, which the next deployment is built with. */
495
+ variables: z.record(variableName, z.string()),
496
+ secrets: z.array(environmentEntrySchema),
497
+ });
498
+ export type EnvironmentListing = z.infer<typeof environmentSchema>;
499
+
500
+ /**
501
+ * `access.json` in the agent's state directory, and the body of `GET` and `PUT /api/access`: the
502
+ * role of each Tailscale login, and the role a tailnet member without one gets, none by default.
503
+ */
504
+ export const accessConfigSchema = z.strictObject({
505
+ roles: z.record(z.string().nonempty(), roleSchema),
506
+ tailnetDefault: roleSchema.nullable(),
507
+ });
508
+ export type AccessConfig = z.infer<typeof accessConfigSchema>;
509
+
510
+ /** `POST /api/session`: the agent's full or read token, which signs a browser in. */
511
+ export const sessionRequestSchema = z.strictObject({ token: z.string() });
512
+
513
+ /** A plain variable's value, which the PLC's program may read through `env()`: no NUL. */
514
+ const plainValue = z
515
+ .string()
516
+ .nonempty("is empty")
517
+ .regex(/^[^\0]*$/, "holds a NUL");
518
+
519
+ /** `PUT /api/environment/:name`: a plain variable's new value, shown and built with, or a secret's. */
520
+ export const environmentValueSchema = z.discriminatedUnion("secret", [
521
+ z.strictObject({ secret: z.literal(false), value: plainValue }),
522
+ z.strictObject({ secret: z.literal(true), value: secretValue }),
523
+ ]);
524
+ export type EnvironmentValue = z.infer<typeof environmentValueSchema>;
525
+
526
+ /**
527
+ * `GET /api/environment/release?service=`: what `tsplc deploy` builds a release with, the plain
528
+ * variables' values and the names of the secrets the PC holds in the service.
529
+ */
530
+ export const plantVariablesSchema = z.strictObject({
531
+ service: z.string().nonempty(),
532
+ values: z.record(variableName, z.string()),
533
+ secrets: z.array(variableName),
534
+ });
package/src/releases.ts CHANGED
@@ -10,7 +10,15 @@ import {
10
10
  stat,
11
11
  writeFile,
12
12
  } from "node:fs/promises";
13
- import { dirname, join, posix, sep } from "node:path";
13
+ import {
14
+ dirname,
15
+ isAbsolute,
16
+ join,
17
+ posix,
18
+ relative,
19
+ resolve,
20
+ sep,
21
+ } from "node:path";
14
22
  import { z } from "zod";
15
23
  import { AgentError } from "./errors";
16
24
  import {
@@ -173,6 +181,70 @@ export const loadRelease = async (
173
181
  return { id, directory, manifest };
174
182
  };
175
183
 
184
+ /** A stored release's files, by path in the release, with their sizes in bytes. */
185
+ export const listReleaseFiles = async (releases: string, id: string) => {
186
+ const directory = join(releases, id);
187
+ if (!existsSync(join(directory, "manifest.json"))) {
188
+ throw new AgentError(`The release ${id} is no longer stored`, 404);
189
+ }
190
+ const files: { path: string; size: number }[] = [];
191
+ for await (const found of new Bun.Glob("**/*").scan({
192
+ cwd: directory,
193
+ dot: true,
194
+ })) {
195
+ files.push({
196
+ path: found.split(sep).join("/"),
197
+ size: (await stat(join(directory, found))).size,
198
+ });
199
+ }
200
+ return files.sort((left, right) => left.path.localeCompare(right.path));
201
+ };
202
+
203
+ /** One file of a stored release; a path that leaves the release is refused. */
204
+ export const readReleaseFile = async (
205
+ releases: string,
206
+ id: string,
207
+ path: string,
208
+ ) => {
209
+ const directory = resolve(releases, id);
210
+ const file = resolve(directory, path);
211
+ const inside = relative(directory, file);
212
+ if (inside === "" || inside.startsWith("..") || isAbsolute(inside)) {
213
+ throw new AgentError(`${path} isn't a path in a release`, 400);
214
+ }
215
+ if (
216
+ !(await stat(file).then(
217
+ (found) => found.isFile(),
218
+ () => false,
219
+ ))
220
+ ) {
221
+ throw new AgentError(`The release ${id} has no file ${path}`, 404);
222
+ }
223
+ return Bun.file(file);
224
+ };
225
+
226
+ /** Deletes every stored release but the `kept` ones; uploads still being stored are left alone. */
227
+ export const pruneReleases = async (
228
+ releases: string,
229
+ kept: ReadonlySet<string>,
230
+ ) => {
231
+ if (!existsSync(releases)) {
232
+ return [];
233
+ }
234
+ const removed = (await readdir(releases, { withFileTypes: true }))
235
+ .filter(
236
+ (entry) =>
237
+ entry.isDirectory() &&
238
+ !entry.name.startsWith(".") &&
239
+ !kept.has(entry.name),
240
+ )
241
+ .map((entry) => entry.name);
242
+ for (const id of removed) {
243
+ await rm(join(releases, id), { recursive: true, force: true });
244
+ }
245
+ return removed;
246
+ };
247
+
176
248
  /** A stored release's files by path, with their digests, and its bucket digests. */
177
249
  interface ReleaseIndex {
178
250
  files: Map<string, string>;
package/src/routes.ts ADDED
@@ -0,0 +1,52 @@
1
+ import type { Identity, Role } from "./protocol";
2
+
3
+ /** One `/api` route: who may call it, and what answers it. */
4
+ export interface ApiRoute {
5
+ method: "GET" | "POST" | "PUT" | "DELETE";
6
+ /**
7
+ * A path with `:name` segments, such as `/api/deployments/:id`. A last segment `*` matches the
8
+ * rest of the path, one segment or more, as param `*`.
9
+ */
10
+ pattern: string;
11
+ role: Role;
12
+ handle: (
13
+ request: Request,
14
+ context: { identity: Identity; params: Readonly<Record<string, string>> },
15
+ ) => Promise<Response>;
16
+ }
17
+
18
+ /** The route `method` and `pathname` name, with the values of its `:name` segments. */
19
+ export const matchRoute = (
20
+ routes: readonly ApiRoute[],
21
+ method: string,
22
+ pathname: string,
23
+ ) => {
24
+ const parts = pathname.split("/");
25
+ for (const route of routes) {
26
+ const pattern = route.pattern.split("/");
27
+ const rest = pattern.at(-1) === "*";
28
+ if (
29
+ route.method !== method ||
30
+ (rest ? parts.length < pattern.length : pattern.length !== parts.length)
31
+ ) {
32
+ continue;
33
+ }
34
+ const params: Record<string, string> = {};
35
+ const matched = pattern.every((segment, index) => {
36
+ const part = parts[index] ?? "";
37
+ if (rest && index === pattern.length - 1) {
38
+ params["*"] = parts.slice(index).map(decodeURIComponent).join("/");
39
+ return part !== "";
40
+ }
41
+ if (segment.startsWith(":")) {
42
+ params[segment.slice(1)] = decodeURIComponent(part);
43
+ return part !== "";
44
+ }
45
+ return segment === part;
46
+ });
47
+ if (matched) {
48
+ return { route, params };
49
+ }
50
+ }
51
+ return undefined;
52
+ };
package/src/secrets.ts CHANGED
@@ -1,13 +1,21 @@
1
+ import { randomBytes } from "node:crypto";
1
2
  import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
2
- import { dirname, join, relative } from "node:path";
3
- import { secretPlaceholder, secretValue } from "@tsplc/config";
3
+ import { dirname, join, relative, sep } from "node:path";
4
+ import {
5
+ type Environment,
6
+ secretPlaceholder,
7
+ secretValue,
8
+ } from "@tsplc/config";
4
9
  import type { ResolvedConfig } from "@tsplc/config/build";
5
10
  import { escapeString } from "@tsplc/iec/st";
6
11
  import { AgentError } from "./errors";
7
12
  import type { Credentials, ReleaseManifest } from "./protocol";
13
+ import { loadRelease } from "./releases";
8
14
 
9
15
  /** The agent's own Bun.secrets service, which holds the controller user and the agent's tokens. */
10
16
  export const agentService = "tsplc-agent";
17
+ /** Where the dashboard stores the environment's secrets while the deployed release declares none. */
18
+ export const environmentService = "tsplc-agent-env";
11
19
  export const controllerSecretNames = {
12
20
  username: "controller-username",
13
21
  password: "controller-password",
@@ -21,6 +29,21 @@ export const agentSetting = async (
21
29
  (await Bun.secrets.get({ service: agentService, name })) ??
22
30
  undefined;
23
31
 
32
+ /**
33
+ * The token the deployed server is started with, made once and kept under the agent's service, so
34
+ * a server an earlier agent started still has a valid one.
35
+ */
36
+ export const serverToken = async () => {
37
+ const name = "server-token";
38
+ const stored = await Bun.secrets.get({ service: agentService, name });
39
+ if (stored) {
40
+ return stored;
41
+ }
42
+ const token = randomBytes(32).toString("hex");
43
+ await Bun.secrets.set({ service: agentService, name, value: token });
44
+ return token;
45
+ };
46
+
24
47
  /** The controller user stored with `tsplc-agent secrets set-controller`, or null. */
25
48
  export const storedCredentials = async (): Promise<Credentials | null> => {
26
49
  const [username, password] = await Promise.all([
@@ -79,7 +102,10 @@ export const readSecrets = async (secrets: ReleaseManifest["secrets"]) => {
79
102
  return values;
80
103
  };
81
104
 
82
- /** Variable `name` for the agent's own use: from Bun.secrets when the release names it as a secret, otherwise `environment`. */
105
+ /**
106
+ * Variable `name` for the agent's own use, as the release's server reads it: from Bun.secrets when
107
+ * the release names it as a secret, else the release's value, else `environment`.
108
+ */
83
109
  export const releaseVariable = async (
84
110
  manifest: ReleaseManifest,
85
111
  name: string,
@@ -87,7 +113,51 @@ export const releaseVariable = async (
87
113
  ) =>
88
114
  manifest.secrets?.names.includes(name)
89
115
  ? Bun.secrets.get({ service: manifest.secrets.service, name })
90
- : environment[name];
116
+ : (manifest.values[name] ?? environment[name]);
117
+
118
+ /** The release's secrets that Bun.secrets holds, by name. */
119
+ const storedSecrets = async (secrets: ReleaseManifest["secrets"]) => {
120
+ if (!secrets) {
121
+ return {};
122
+ }
123
+ const stored = await Promise.all(
124
+ secrets.names.map(async (name) => ({
125
+ name,
126
+ value: await Bun.secrets.get({ service: secrets.service, name }),
127
+ })),
128
+ );
129
+ return Object.fromEntries(
130
+ stored.flatMap(({ name, value }): [string, string][] =>
131
+ value === null ? [] : [[name, value]],
132
+ ),
133
+ );
134
+ };
135
+
136
+ /**
137
+ * The environment the server at `executable`, in a release under `releases`, runs in:
138
+ * `environment`, then the values of the target the release was built for, as the PLC's program
139
+ * got them, then the release's secrets that Bun.secrets holds, so a server reads each as the
140
+ * variable it is.
141
+ */
142
+ export const serverEnvironment = async (
143
+ releases: string,
144
+ executable: string,
145
+ environment: Environment,
146
+ ): Promise<Environment> => {
147
+ const [id = ""] = relative(releases, executable).split(sep);
148
+ const manifest = await loadRelease(releases, id).then(
149
+ (release) => release.manifest,
150
+ () => undefined,
151
+ );
152
+ if (!manifest) {
153
+ return environment;
154
+ }
155
+ return {
156
+ ...environment,
157
+ ...manifest.values,
158
+ ...(await storedSecrets(manifest.secrets)),
159
+ };
160
+ };
91
161
 
92
162
  /** Structured Text with each secret's placeholder replaced by its value, inside the STRING literal that holds it. */
93
163
  const fillSecrets = (st: string, secrets: ReadonlyMap<string, string>) =>
@@ -51,9 +51,14 @@ export const mayStillRun = (
51
51
  record.startedAt > machine.now - machine.uptimeSeconds * 1000 &&
52
52
  machine.alive(record.pid);
53
53
 
54
+ /** Environment variables by name, as a server is started with them. */
55
+ type ServerEnvironment = Readonly<Record<string, string | undefined>>;
56
+
54
57
  /** One running server: one this agent started, or one an earlier agent left running. */
55
58
  interface Running {
56
59
  executable: string;
60
+ /** What it runs in, and what it restarts in after it exits. */
61
+ environment: ServerEnvironment;
57
62
  pid: number;
58
63
  alive: () => boolean;
59
64
  exited: Promise<unknown>;
@@ -61,7 +66,7 @@ interface Running {
61
66
 
62
67
  /**
63
68
  * Runs the deployed server executable, restarting it whenever it exits, and swaps it for
64
- * another release's. The server reads its own environment and secrets, as it would anywhere.
69
+ * another release's. Each start reads the environment afresh, so a restart applies changed secrets.
65
70
  * It runs detached from the agent with its output appended to `output`, so an agent that
66
71
  * restarts, to upgrade or after a crash, leaves the line's server running and takes it over.
67
72
  */
@@ -72,6 +77,8 @@ export const createServerSupervisor = (options: {
72
77
  record: string;
73
78
  /** The file the server's output is appended to. */
74
79
  output: string;
80
+ /** The environment `executable` starts in. */
81
+ environment: (executable: string) => Promise<ServerEnvironment>;
75
82
  log: (message: string) => void;
76
83
  }) => {
77
84
  let current: Running | undefined;
@@ -102,13 +109,16 @@ export const createServerSupervisor = (options: {
102
109
  );
103
110
  void delay(restartDelayMs).then(() => {
104
111
  if (current === running) {
105
- current = spawn(running.executable);
112
+ current = spawn(running.executable, running.environment);
106
113
  }
107
114
  });
108
115
  });
109
116
  };
110
117
 
111
- const spawn = (executable: string): Running => {
118
+ const spawn = (
119
+ executable: string,
120
+ environment: ServerEnvironment,
121
+ ): Running => {
112
122
  // A bundled server runs on the agent's own Bun; releases before bundles shipped an executable.
113
123
  const command = executable.endsWith(".js")
114
124
  ? [process.execPath, executable]
@@ -124,6 +134,7 @@ export const createServerSupervisor = (options: {
124
134
  try {
125
135
  return Bun.spawn(command, {
126
136
  cwd: dirname(executable),
137
+ env: environment,
127
138
  detached: true,
128
139
  stdio: ["ignore", output, output],
129
140
  });
@@ -133,6 +144,7 @@ export const createServerSupervisor = (options: {
133
144
  })();
134
145
  const running: Running = {
135
146
  executable,
147
+ environment,
136
148
  pid: child.pid,
137
149
  alive: () => child.exitCode === null && child.signalCode === null,
138
150
  exited: child.exited,
@@ -143,7 +155,10 @@ export const createServerSupervisor = (options: {
143
155
  };
144
156
 
145
157
  /** Watches a server an earlier agent started, which this one can't wait on. */
146
- const adopt = (record: ServerRecord): Running => {
158
+ const adopt = (
159
+ record: ServerRecord,
160
+ environment: ServerEnvironment,
161
+ ): Running => {
147
162
  const exited = Promise.withResolvers<void>();
148
163
  const watch = setInterval(() => {
149
164
  if (!processAlive(record.pid)) {
@@ -155,6 +170,7 @@ export const createServerSupervisor = (options: {
155
170
  watch.unref();
156
171
  const running: Running = {
157
172
  executable: record.executable,
173
+ environment,
158
174
  pid: record.pid,
159
175
  alive: () => processAlive(record.pid),
160
176
  exited: exited.promise,
@@ -182,8 +198,8 @@ export const createServerSupervisor = (options: {
182
198
  return false;
183
199
  };
184
200
 
185
- const start = (executable: string) => {
186
- current = spawn(executable);
201
+ const start = (executable: string, environment: ServerEnvironment) => {
202
+ current = spawn(executable, environment);
187
203
  return current;
188
204
  };
189
205
 
@@ -216,6 +232,7 @@ export const createServerSupervisor = (options: {
216
232
  * still running and, with a health route, answering it.
217
233
  */
218
234
  resume: async (executable: string) => {
235
+ const environment = await options.environment(executable);
219
236
  const record = await readRecord();
220
237
  if (
221
238
  record?.executable === executable &&
@@ -227,10 +244,10 @@ export const createServerSupervisor = (options: {
227
244
  (await answers(() => processAlive(record.pid), adoptWithinMs))
228
245
  ) {
229
246
  options.log(`Took over the running server (process ${record.pid})`);
230
- current = adopt(record);
247
+ current = adopt(record, environment);
231
248
  return;
232
249
  }
233
- start(executable);
250
+ start(executable, environment);
234
251
  },
235
252
  stop,
236
253
  /** Stops supervising the server and leaves it running, for the agent that replaces this one. */
@@ -239,21 +256,21 @@ export const createServerSupervisor = (options: {
239
256
  },
240
257
  /** Replaces the running server; if the new one doesn't come up, the previous one runs again. */
241
258
  replace: async (executable: string) => {
242
- const previous = current?.executable;
259
+ const previous = current;
260
+ const environment = await options.environment(executable);
243
261
  await stop();
244
262
  let failure: unknown;
245
- const started = await (async () => healthy(start(executable)))().catch(
246
- (error: unknown) => {
247
- failure = error;
248
- return false;
249
- },
250
- );
263
+ const started = await (async () =>
264
+ healthy(start(executable, environment)))().catch((error: unknown) => {
265
+ failure = error;
266
+ return false;
267
+ });
251
268
  if (started) {
252
269
  return;
253
270
  }
254
271
  await stop();
255
272
  if (previous) {
256
- start(previous);
273
+ start(previous.executable, previous.environment);
257
274
  }
258
275
  const reason =
259
276
  failure instanceof Error