@tsplc/agent 0.5.9 → 0.5.10

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 (49) hide show
  1. package/dist/cli.js +2462 -533
  2. package/dist/cli.js.map +30 -17
  3. package/dist/client.js +238 -36
  4. package/dist/client.js.map +4 -4
  5. package/dist/index.js +2162 -416
  6. package/dist/index.js.map +25 -13
  7. package/package.json +5 -5
  8. package/src/access.ts +257 -0
  9. package/src/agent.ts +101 -29
  10. package/src/audit.ts +64 -0
  11. package/src/cli.ts +58 -4
  12. package/src/client.ts +181 -36
  13. package/src/dashboard/index.ts +116 -0
  14. package/src/dashboard/ui/access.ts +192 -0
  15. package/src/dashboard/ui/actions.ts +142 -0
  16. package/src/dashboard/ui/api.ts +147 -0
  17. package/src/dashboard/ui/app.ts +41 -0
  18. package/src/dashboard/ui/approval.ts +132 -0
  19. package/src/dashboard/ui/audit.ts +115 -0
  20. package/src/dashboard/ui/contract.ts +16 -0
  21. package/src/dashboard/ui/dashboard.css +1332 -0
  22. package/src/dashboard/ui/deployment.ts +432 -0
  23. package/src/dashboard/ui/deployments.ts +317 -0
  24. package/src/dashboard/ui/details.ts +240 -0
  25. package/src/dashboard/ui/dom.ts +91 -0
  26. package/src/dashboard/ui/environment.ts +224 -0
  27. package/src/dashboard/ui/format.ts +118 -0
  28. package/src/dashboard/ui/logs.ts +127 -0
  29. package/src/dashboard/ui/main.ts +86 -0
  30. package/src/dashboard/ui/overlay.ts +146 -0
  31. package/src/dashboard/ui/shell.ts +171 -0
  32. package/src/dashboard/ui/source.ts +144 -0
  33. package/src/deploy.ts +138 -144
  34. package/src/deployments/health.ts +80 -0
  35. package/src/deployments/retention.ts +45 -0
  36. package/src/deployments/routes.ts +273 -0
  37. package/src/deployments/runner.ts +877 -0
  38. package/src/deployments/store.ts +233 -0
  39. package/src/environment.ts +205 -0
  40. package/src/index.ts +4 -0
  41. package/src/operations.ts +5 -1
  42. package/src/protocol.ts +218 -2
  43. package/src/releases.ts +73 -1
  44. package/src/routes.ts +52 -0
  45. package/src/secrets.ts +43 -2
  46. package/src/server-process.ts +33 -16
  47. package/src/sessions.ts +58 -0
  48. package/src/state.ts +2 -0
  49. 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";
@@ -85,6 +85,8 @@ export const deployOptionsSchema = z
85
85
  /** A full download stops the application; without it only an online change is applied. */
86
86
  download: z.boolean(),
87
87
  initializeUser: z.boolean(),
88
+ /** How `POST /api/deployments` queues it; `POST /deploy` runs it at once and ignores this. */
89
+ deployment: z.lazy(() => deploymentRequestSchema).optional(),
88
90
  })
89
91
  .refine(
90
92
  (options) => options.credentials || !options.initializeUser,
@@ -275,3 +277,217 @@ export const auditSchema = z.strictObject({
275
277
  error: z.string().optional(),
276
278
  });
277
279
  export type Audit = z.infer<typeof auditSchema>;
280
+
281
+ /**
282
+ * Who may do what on the agent's dashboard and API, each role including the ones before it: a
283
+ * viewer reads deployments, logs, the debugger and the audit log; a deployer also deploys,
284
+ * approves, cancels, redeploys, rolls back and restarts the server; an admin also manages the
285
+ * environment's secrets and who has which role.
286
+ */
287
+ export const roles = ["viewer", "deployer", "admin"] as const;
288
+ export const roleSchema = z.enum(roles);
289
+ export type Role = z.infer<typeof roleSchema>;
290
+
291
+ /** Whether `role` includes `required`. */
292
+ export const allows = (role: Role, required: Role) =>
293
+ roles.indexOf(role) >= roles.indexOf(required);
294
+
295
+ /** Who made a request, and how the agent knows. */
296
+ export const identitySchema = z.strictObject({
297
+ /** The Tailscale login, or null for a token or a request from the agent's own PC. */
298
+ login: z.string().nullable(),
299
+ /** A name to show: the Tailscale display name, or how the token or PC is known. */
300
+ name: z.string(),
301
+ role: roleSchema,
302
+ via: z.enum(["tailscale", "token", "local"]),
303
+ });
304
+ export type Identity = z.infer<typeof identitySchema>;
305
+
306
+ /** The commit a deployment was built from, when `tsplc deploy` ran in a git checkout. */
307
+ export const gitSourceSchema = z.strictObject({
308
+ commit: z.string().nonempty(),
309
+ branch: z.string().nullable(),
310
+ /** Uncommitted changes went into the build. */
311
+ dirty: z.boolean(),
312
+ /** The commit's subject line. */
313
+ message: z.string().nullable(),
314
+ });
315
+ export type GitSource = z.infer<typeof gitSourceSchema>;
316
+
317
+ /**
318
+ * How a deployment applies: `apply` runs it as soon as it is its turn; `review` builds it and
319
+ * checks what an online change would do, then waits for someone to approve it.
320
+ */
321
+ export const deploymentModeSchema = z.enum(["apply", "review"]);
322
+ export type DeploymentMode = z.infer<typeof deploymentModeSchema>;
323
+
324
+ /**
325
+ * Where a deployment is. `awaitingApproval` waits on a person: a review to apply, or a full
326
+ * download that would stop the line. A finished deployment is `ready`, `error` or `canceled`.
327
+ */
328
+ export const deploymentStateSchema = z.enum([
329
+ "queued",
330
+ "building",
331
+ "awaitingApproval",
332
+ "applying",
333
+ "starting",
334
+ "verifying",
335
+ "ready",
336
+ "error",
337
+ "canceled",
338
+ ]);
339
+ export type DeploymentState = z.infer<typeof deploymentStateSchema>;
340
+
341
+ /** The steps a deployment goes through, in order; a deployment skips the ones it doesn't need. */
342
+ export const deploymentPhaseNameSchema = z.enum([
343
+ "queue",
344
+ "build",
345
+ "review",
346
+ "apply",
347
+ "server",
348
+ "health",
349
+ ]);
350
+
351
+ const deploymentIdSchema = z.string().regex(/^dpl_[a-z0-9]{16,32}$/);
352
+
353
+ /**
354
+ * A deployment as the agent keeps it, in `deployments/<id>/record.json` of its state directory.
355
+ * Every record of the last 14 days is kept, and always the running one and the last that was
356
+ * healthy, with their releases.
357
+ */
358
+ export const deploymentRecordSchema = z.strictObject({
359
+ id: deploymentIdSchema,
360
+ release: z.string(),
361
+ /** The debug manifest's build id, when the release has one. */
362
+ build: z.string().nullable(),
363
+ createdAt: z.iso.datetime(),
364
+ updatedAt: z.iso.datetime(),
365
+ /** An upload from `tsplc deploy`, or a release the agent already had, deployed again. */
366
+ origin: z.discriminatedUnion("kind", [
367
+ z.strictObject({ kind: z.literal("upload") }),
368
+ z.strictObject({ kind: z.literal("redeploy"), from: deploymentIdSchema }),
369
+ z.strictObject({ kind: z.literal("rollback"), from: deploymentIdSchema }),
370
+ ]),
371
+ git: gitSourceSchema.nullable(),
372
+ /** Who asked for it: the identity behind the request, with the deploying machine's user and host. */
373
+ requestedBy: z.strictObject({
374
+ identity: identitySchema.omit({ role: true }),
375
+ user: z.string().nullable(),
376
+ host: z.string().nullable(),
377
+ }),
378
+ mode: deploymentModeSchema,
379
+ /** What it applies or applied: an online change unless a full download was asked for or approved. */
380
+ operation: deployOperationSchema,
381
+ state: deploymentStateSchema,
382
+ phases: z.array(
383
+ z.strictObject({
384
+ name: deploymentPhaseNameSchema,
385
+ startedAt: z.iso.datetime(),
386
+ finishedAt: z.iso.datetime().nullable(),
387
+ outcome: z.enum(["running", "ok", "failed", "skipped"]),
388
+ }),
389
+ ),
390
+ /** What the online-change check found: refusals, and what the change restarts. */
391
+ findings: z.array(onlineChangeFindingSchema),
392
+ /** What it waits on while `awaitingApproval`. */
393
+ approval: z
394
+ .strictObject({
395
+ reason: z.enum(["review", "downloadRequired"]),
396
+ message: z.string(),
397
+ })
398
+ .nullable(),
399
+ error: z
400
+ .strictObject({
401
+ message: z.string(),
402
+ downloadRequired: z.boolean(),
403
+ rollback: rollbackSchema.optional(),
404
+ })
405
+ .nullable(),
406
+ controllerIds: z
407
+ .strictObject({ codeId: z.string(), dataId: z.string() })
408
+ .nullable(),
409
+ /** What the check after applying found; null until it ran. */
410
+ health: z
411
+ .strictObject({
412
+ controller: z.enum(["ok", "failed"]),
413
+ server: z.enum(["ok", "failed", "none"]),
414
+ plc: z.enum(["ok", "failed", "unknown"]),
415
+ detail: z.string().nullable(),
416
+ })
417
+ .nullable(),
418
+ /** When it became the running deployment, and when another replaced it; null until and while. */
419
+ activeFrom: z.iso.datetime().nullable(),
420
+ activeUntil: z.iso.datetime().nullable(),
421
+ });
422
+ export type DeploymentRecord = z.infer<typeof deploymentRecordSchema>;
423
+
424
+ /** One line of a deployment's log, `deployments/<id>/log.jsonl`. */
425
+ export const deploymentLogLineSchema = z.strictObject({
426
+ /** Counts from 1 within the deployment; `?after=` resumes from it. */
427
+ seq: z.number().int().positive(),
428
+ at: z.iso.datetime(),
429
+ level: z.enum(["info", "warning", "error"]),
430
+ phase: deploymentPhaseNameSchema.nullable(),
431
+ message: z.string(),
432
+ });
433
+ export type DeploymentLogLine = z.infer<typeof deploymentLogLineSchema>;
434
+
435
+ /**
436
+ * What `tsplc deploy` sends with a release to `POST /api/deployments`, in the upload's `options`
437
+ * beside the existing deploy options.
438
+ */
439
+ export const deploymentRequestSchema = z.strictObject({
440
+ mode: deploymentModeSchema,
441
+ git: gitSourceSchema.nullable(),
442
+ });
443
+ export type DeploymentRequest = z.infer<typeof deploymentRequestSchema>;
444
+
445
+ /** `POST /api/deployments`'s answer: the queued deployment and the dashboard page that shows it. */
446
+ export const deploymentCreatedSchema = z.strictObject({
447
+ id: deploymentIdSchema,
448
+ url: z.string(),
449
+ });
450
+
451
+ /** `GET /api/deployments`: newest first, with the running and last healthy ones named. */
452
+ export const deploymentListSchema = z.strictObject({
453
+ deployments: z.array(deploymentRecordSchema),
454
+ current: deploymentIdSchema.nullable(),
455
+ lastGood: deploymentIdSchema.nullable(),
456
+ });
457
+
458
+ /** `POST /api/deployments/:id/approve`: apply it, as a full download when one is required. */
459
+ export const approveSchema = z.strictObject({ download: z.boolean() });
460
+
461
+ /** `POST /api/deployments/:id/redeploy`: deploy its release again. */
462
+ export const redeploySchema = z.strictObject({ mode: deploymentModeSchema });
463
+
464
+ /** `GET /api/deployments/:id/source`: the release's files, by path, with their sizes in bytes. */
465
+ export const deploymentSourceSchema = z.strictObject({
466
+ files: z.array(
467
+ z.strictObject({ path: z.string(), size: z.number().int().nonnegative() }),
468
+ ),
469
+ });
470
+
471
+ /** A secret the deployed release's config declares, or one stored without a declaration: never its value. */
472
+ export const environmentEntrySchema = z.strictObject({
473
+ name: z.string(),
474
+ declared: z.boolean(),
475
+ set: z.boolean(),
476
+ });
477
+ export type EnvironmentEntry = z.infer<typeof environmentEntrySchema>;
478
+
479
+ /**
480
+ * `access.json` in the agent's state directory, and the body of `GET` and `PUT /api/access`: the
481
+ * role of each Tailscale login, and the role a tailnet member without one gets, none by default.
482
+ */
483
+ export const accessConfigSchema = z.strictObject({
484
+ roles: z.record(z.string().nonempty(), roleSchema),
485
+ tailnetDefault: roleSchema.nullable(),
486
+ });
487
+ export type AccessConfig = z.infer<typeof accessConfigSchema>;
488
+
489
+ /** `POST /api/session`: the agent's full or read token, which signs a browser in. */
490
+ export const sessionRequestSchema = z.strictObject({ token: z.string() });
491
+
492
+ /** `PUT /api/environment/:name`: the secret's new value. */
493
+ export const environmentValueSchema = z.strictObject({ value: secretValue });
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,20 @@
1
1
  import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
2
- import { dirname, join, relative } from "node:path";
3
- import { secretPlaceholder, secretValue } from "@tsplc/config";
2
+ import { dirname, join, relative, sep } from "node:path";
3
+ import {
4
+ type Environment,
5
+ secretPlaceholder,
6
+ secretValue,
7
+ } from "@tsplc/config";
4
8
  import type { ResolvedConfig } from "@tsplc/config/build";
5
9
  import { escapeString } from "@tsplc/iec/st";
6
10
  import { AgentError } from "./errors";
7
11
  import type { Credentials, ReleaseManifest } from "./protocol";
12
+ import { loadRelease } from "./releases";
8
13
 
9
14
  /** The agent's own Bun.secrets service, which holds the controller user and the agent's tokens. */
10
15
  export const agentService = "tsplc-agent";
16
+ /** Where the dashboard stores the environment's secrets while the deployed release declares none. */
17
+ export const environmentService = "tsplc-agent-env";
11
18
  export const controllerSecretNames = {
12
19
  username: "controller-username",
13
20
  password: "controller-password",
@@ -89,6 +96,40 @@ export const releaseVariable = async (
89
96
  ? Bun.secrets.get({ service: manifest.secrets.service, name })
90
97
  : environment[name];
91
98
 
99
+ /**
100
+ * The environment the server at `executable`, in a release under `releases`, runs in:
101
+ * `environment` with the release's secrets that Bun.secrets holds, so a server reads them as the
102
+ * variables they are.
103
+ */
104
+ export const serverEnvironment = async (
105
+ releases: string,
106
+ executable: string,
107
+ environment: Environment,
108
+ ): Promise<Environment> => {
109
+ const [id = ""] = relative(releases, executable).split(sep);
110
+ const secrets = await loadRelease(releases, id).then(
111
+ ({ manifest }) => manifest.secrets,
112
+ () => undefined,
113
+ );
114
+ if (!secrets) {
115
+ return environment;
116
+ }
117
+ const stored = await Promise.all(
118
+ secrets.names.map(async (name) => ({
119
+ name,
120
+ value: await Bun.secrets.get({ service: secrets.service, name }),
121
+ })),
122
+ );
123
+ return {
124
+ ...environment,
125
+ ...Object.fromEntries(
126
+ stored.flatMap(({ name, value }): [string, string][] =>
127
+ value === null ? [] : [[name, value]],
128
+ ),
129
+ ),
130
+ };
131
+ };
132
+
92
133
  /** Structured Text with each secret's placeholder replaced by its value, inside the STRING literal that holds it. */
93
134
  const fillSecrets = (st: string, secrets: ReadonlyMap<string, string>) =>
94
135
  [...secrets].reduce(
@@ -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
@@ -0,0 +1,58 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import type { Identity } from "./protocol";
3
+
4
+ /** The cookie a signed-in browser sends: a random session id, never a token. */
5
+ export const sessionCookie = "tsplc_session";
6
+
7
+ /** How long a browser stays signed in. */
8
+ export const sessionLifetimeMs = 12 * 60 * 60 * 1000;
9
+
10
+ /**
11
+ * Browsers signed in with a token, kept in memory: restarting the agent signs every browser out.
12
+ */
13
+ export const createSessions = (now: () => number) => {
14
+ const sessions = new Map<string, { identity: Identity; expires: number }>();
15
+
16
+ const sessionId = (request: Request) =>
17
+ new Bun.CookieMap(request.headers.get("cookie") ?? "").get(sessionCookie);
18
+
19
+ const cookie = (value: string, maxAgeMs: number) =>
20
+ new Bun.Cookie(sessionCookie, value, {
21
+ httpOnly: true,
22
+ sameSite: "strict",
23
+ path: "/",
24
+ maxAge: Math.floor(maxAgeMs / 1000),
25
+ }).serialize();
26
+
27
+ return {
28
+ /** Signs a browser in as `identity`; the answer sets the returned cookie. */
29
+ open: (identity: Identity) => {
30
+ const time = now();
31
+ for (const [id, { expires }] of sessions) {
32
+ if (expires <= time) {
33
+ sessions.delete(id);
34
+ }
35
+ }
36
+ const id = randomBytes(32).toString("base64url");
37
+ sessions.set(id, { identity, expires: time + sessionLifetimeMs });
38
+ return cookie(id, sessionLifetimeMs);
39
+ },
40
+ /** Who the request's cookie signed in, while the session lasts. */
41
+ find: (request: Request) => {
42
+ const id = sessionId(request);
43
+ const session = id === null ? undefined : sessions.get(id);
44
+ if (!session || session.expires <= now()) {
45
+ return null;
46
+ }
47
+ return session.identity;
48
+ },
49
+ /** Ends the request's session; the answer sets the returned cookie, which clears it. */
50
+ close: (request: Request) => {
51
+ const id = sessionId(request);
52
+ if (id !== null) {
53
+ sessions.delete(id);
54
+ }
55
+ return cookie("", 0);
56
+ },
57
+ };
58
+ };
package/src/state.ts CHANGED
@@ -32,6 +32,8 @@ export const openState = async (directory: string) => {
32
32
  release: join(directory, "release.json"),
33
33
  target: join(directory, "target.json"),
34
34
  deployments: join(directory, "deployments.jsonl"),
35
+ /** Each deployment's record and log, under its id. */
36
+ deploymentRecords: join(directory, "deployments"),
35
37
  audit: join(directory, "audit.jsonl"),
36
38
  debug: join(directory, "debug"),
37
39
  /** The running server's process, for the agent that takes it over. */