@tsplc/agent 0.5.8 → 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/dist/client.js CHANGED
@@ -7,12 +7,12 @@ import {
7
7
  import { z as z2 } from "zod";
8
8
 
9
9
  // packages/agent/src/protocol.ts
10
- import { rollbackSchema } from "@tsplc/build";
11
- import { tsplcConfigSchema } from "@tsplc/config";
10
+ import { onlineChangeFindingSchema, rollbackSchema } from "@tsplc/build";
11
+ import { secretValue, tsplcConfigSchema } from "@tsplc/config";
12
12
  import { releaseConfigSchema, tcpPort } from "@tsplc/config/build";
13
13
  import { z } from "zod";
14
14
  // packages/agent/package.json
15
- var version = "0.5.8";
15
+ var version = "0.5.10";
16
16
 
17
17
  // packages/agent/src/protocol.ts
18
18
  var tsplcVersion = version;
@@ -58,7 +58,8 @@ var releaseManifestSchema = z.strictObject({
58
58
  var deployOptionsSchema = z.strictObject({
59
59
  credentials: credentialsSchema.nullable(),
60
60
  download: z.boolean(),
61
- initializeUser: z.boolean()
61
+ initializeUser: z.boolean(),
62
+ deployment: z.lazy(() => deploymentRequestSchema).optional()
62
63
  }).refine((options) => options.credentials || !options.initializeUser, "Initializing the controller's user needs the user's credentials.");
63
64
  var releaseBuckets = 256;
64
65
  var shortHex = z.string().regex(/^[a-f0-9]{16}$/);
@@ -148,6 +149,123 @@ var auditSchema = z.strictObject({
148
149
  release: z.string().optional(),
149
150
  error: z.string().optional()
150
151
  });
152
+ var roles = ["viewer", "deployer", "admin"];
153
+ var roleSchema = z.enum(roles);
154
+ var identitySchema = z.strictObject({
155
+ login: z.string().nullable(),
156
+ name: z.string(),
157
+ role: roleSchema,
158
+ via: z.enum(["tailscale", "token", "local"])
159
+ });
160
+ var gitSourceSchema = z.strictObject({
161
+ commit: z.string().nonempty(),
162
+ branch: z.string().nullable(),
163
+ dirty: z.boolean(),
164
+ message: z.string().nullable()
165
+ });
166
+ var deploymentModeSchema = z.enum(["apply", "review"]);
167
+ var deploymentStateSchema = z.enum([
168
+ "queued",
169
+ "building",
170
+ "awaitingApproval",
171
+ "applying",
172
+ "starting",
173
+ "verifying",
174
+ "ready",
175
+ "error",
176
+ "canceled"
177
+ ]);
178
+ var deploymentPhaseNameSchema = z.enum([
179
+ "queue",
180
+ "build",
181
+ "review",
182
+ "apply",
183
+ "server",
184
+ "health"
185
+ ]);
186
+ var deploymentIdSchema = z.string().regex(/^dpl_[a-z0-9]{16,32}$/);
187
+ var deploymentRecordSchema = z.strictObject({
188
+ id: deploymentIdSchema,
189
+ release: z.string(),
190
+ build: z.string().nullable(),
191
+ createdAt: z.iso.datetime(),
192
+ updatedAt: z.iso.datetime(),
193
+ origin: z.discriminatedUnion("kind", [
194
+ z.strictObject({ kind: z.literal("upload") }),
195
+ z.strictObject({ kind: z.literal("redeploy"), from: deploymentIdSchema }),
196
+ z.strictObject({ kind: z.literal("rollback"), from: deploymentIdSchema })
197
+ ]),
198
+ git: gitSourceSchema.nullable(),
199
+ requestedBy: z.strictObject({
200
+ identity: identitySchema.omit({ role: true }),
201
+ user: z.string().nullable(),
202
+ host: z.string().nullable()
203
+ }),
204
+ mode: deploymentModeSchema,
205
+ operation: deployOperationSchema,
206
+ state: deploymentStateSchema,
207
+ phases: z.array(z.strictObject({
208
+ name: deploymentPhaseNameSchema,
209
+ startedAt: z.iso.datetime(),
210
+ finishedAt: z.iso.datetime().nullable(),
211
+ outcome: z.enum(["running", "ok", "failed", "skipped"])
212
+ })),
213
+ findings: z.array(onlineChangeFindingSchema),
214
+ approval: z.strictObject({
215
+ reason: z.enum(["review", "downloadRequired"]),
216
+ message: z.string()
217
+ }).nullable(),
218
+ error: z.strictObject({
219
+ message: z.string(),
220
+ downloadRequired: z.boolean(),
221
+ rollback: rollbackSchema.optional()
222
+ }).nullable(),
223
+ controllerIds: z.strictObject({ codeId: z.string(), dataId: z.string() }).nullable(),
224
+ health: z.strictObject({
225
+ controller: z.enum(["ok", "failed"]),
226
+ server: z.enum(["ok", "failed", "none"]),
227
+ plc: z.enum(["ok", "failed", "unknown"]),
228
+ detail: z.string().nullable()
229
+ }).nullable(),
230
+ activeFrom: z.iso.datetime().nullable(),
231
+ activeUntil: z.iso.datetime().nullable()
232
+ });
233
+ var deploymentLogLineSchema = z.strictObject({
234
+ seq: z.number().int().positive(),
235
+ at: z.iso.datetime(),
236
+ level: z.enum(["info", "warning", "error"]),
237
+ phase: deploymentPhaseNameSchema.nullable(),
238
+ message: z.string()
239
+ });
240
+ var deploymentRequestSchema = z.strictObject({
241
+ mode: deploymentModeSchema,
242
+ git: gitSourceSchema.nullable()
243
+ });
244
+ var deploymentCreatedSchema = z.strictObject({
245
+ id: deploymentIdSchema,
246
+ url: z.string()
247
+ });
248
+ var deploymentListSchema = z.strictObject({
249
+ deployments: z.array(deploymentRecordSchema),
250
+ current: deploymentIdSchema.nullable(),
251
+ lastGood: deploymentIdSchema.nullable()
252
+ });
253
+ var approveSchema = z.strictObject({ download: z.boolean() });
254
+ var redeploySchema = z.strictObject({ mode: deploymentModeSchema });
255
+ var deploymentSourceSchema = z.strictObject({
256
+ files: z.array(z.strictObject({ path: z.string(), size: z.number().int().nonnegative() }))
257
+ });
258
+ var environmentEntrySchema = z.strictObject({
259
+ name: z.string(),
260
+ declared: z.boolean(),
261
+ set: z.boolean()
262
+ });
263
+ var accessConfigSchema = z.strictObject({
264
+ roles: z.record(z.string().nonempty(), roleSchema),
265
+ tailnetDefault: roleSchema.nullable()
266
+ });
267
+ var sessionRequestSchema = z.strictObject({ token: z.string() });
268
+ var environmentValueSchema = z.strictObject({ value: secretValue });
151
269
 
152
270
  // packages/agent/src/transfer.ts
153
271
  import { createHash } from "node:crypto";
@@ -192,6 +310,46 @@ class AgentOperationError extends Error {
192
310
  this.rollback = rollback;
193
311
  }
194
312
  }
313
+
314
+ class AgentUnreachable extends Error {
315
+ }
316
+ async function* serverSentEvents(body) {
317
+ const reader = body.pipeThrough(new TextDecoderStream).getReader();
318
+ let buffered = "";
319
+ let name = "message";
320
+ let data = [];
321
+ try {
322
+ while (true) {
323
+ const { done, value } = await reader.read().catch((cause) => {
324
+ throw new AgentUnreachable("The connection to the agent broke", {
325
+ cause
326
+ });
327
+ });
328
+ if (done) {
329
+ return;
330
+ }
331
+ buffered += value;
332
+ const lines = buffered.split(/\r?\n/);
333
+ buffered = lines.pop() ?? "";
334
+ for (const line of lines) {
335
+ if (line === "") {
336
+ if (data.length) {
337
+ yield { name, data: data.join(`
338
+ `) };
339
+ }
340
+ name = "message";
341
+ data = [];
342
+ } else if (line.startsWith("event:")) {
343
+ name = line.slice("event:".length).trim();
344
+ } else if (line.startsWith("data:")) {
345
+ data.push(line.slice("data:".length).replace(/^ /, ""));
346
+ }
347
+ }
348
+ }
349
+ } finally {
350
+ await reader.cancel().catch(() => {});
351
+ }
352
+ }
195
353
  var createAgentClient = (options) => {
196
354
  const identity = workerScriptsDigest().then((scripts) => ({ [clientHeaders.scripts]: scripts }), () => ({})).then((scripts) => ({
197
355
  [clientHeaders.user]: userInfo().username,
@@ -199,25 +357,24 @@ var createAgentClient = (options) => {
199
357
  [clientHeaders.version]: tsplcVersion,
200
358
  ...scripts
201
359
  }));
202
- const call = async (path, init = {}) => {
203
- const response = await fetch(new URL(path, options.url), {
204
- ...init,
205
- headers: {
206
- ...init.headers,
207
- ...await identity,
208
- Authorization: `Bearer ${options.token}`
209
- }
210
- }).catch((cause) => {
211
- throw new Error(`Cannot reach the plant agent at ${options.url}`, {
212
- cause
213
- });
214
- });
360
+ const request = async (path, init = {}) => fetch(new URL(path, options.url), {
361
+ ...init,
362
+ headers: {
363
+ ...init.headers,
364
+ ...await identity,
365
+ Authorization: `Bearer ${options.token}`
366
+ }
367
+ }).catch((cause) => {
368
+ throw new AgentUnreachable(`Cannot reach the plant agent at ${options.url}`, { cause });
369
+ });
370
+ const answered = async (response) => {
215
371
  if (!response.ok) {
216
372
  const body = await response.json().catch(() => ({}));
217
373
  throw new AgentOperationError(errorSchema.safeParse(body).data?.error ?? `The agent answered ${response.status}`);
218
374
  }
219
375
  return response;
220
376
  };
377
+ const call = async (path, init = {}) => answered(await request(path, init));
221
378
  const get = async (path, schema) => schema.parse(await (await call(path)).json());
222
379
  const send = async (method, path, body, schema) => schema.parse(await (await call(path, {
223
380
  method,
@@ -255,33 +412,77 @@ var createAgentClient = (options) => {
255
412
  }
256
413
  };
257
414
  const compare = (buckets) => send("POST", "/releases/compare", { buckets }, comparisonSchema);
415
+ const upload = async (release, settings, onProgress) => {
416
+ const agentVersion = (await call("/status")).headers.get(agentVersionHeader);
417
+ if (agentVersion !== tsplcVersion) {
418
+ throw new AgentOperationError(versionMismatch({
419
+ agent: agentVersion,
420
+ client: tsplcVersion,
421
+ agentUpgrades: upgradesItself(agentVersion)
422
+ }));
423
+ }
424
+ const files = await Promise.all(release.files.map(async ({ path, content }) => ({
425
+ path,
426
+ content: await content.bytes()
427
+ })));
428
+ const digests = files.map(({ path, content }) => ({
429
+ path,
430
+ digest: shortDigest(content)
431
+ }));
432
+ const buckets = bucketDigests(digests);
433
+ return releaseUpload({ manifest: release.manifest, options: settings, buckets }, files, await compare(buckets), onProgress);
434
+ };
258
435
  return {
436
+ url: options.url,
259
437
  status: () => get("/status", statusSchema),
260
438
  interfaces: () => get("/interfaces", z2.array(networkInterfaceSchema)),
261
439
  discover: (name) => send("POST", "/discover", { name }, z2.array(controllerSchema)),
262
440
  setTarget: (target) => send("PUT", "/target", target, targetSchema),
263
441
  variables: () => get("/variables", z2.array(variableSchema)),
264
442
  deploy: async (release, settings, onProgress) => {
265
- const agentVersion = (await call("/status")).headers.get(agentVersionHeader);
266
- if (agentVersion !== tsplcVersion) {
267
- throw new AgentOperationError(versionMismatch({
268
- agent: agentVersion,
269
- client: tsplcVersion,
270
- agentUpgrades: upgradesItself(agentVersion)
271
- }));
272
- }
273
- const files = await Promise.all(release.files.map(async ({ path, content }) => ({
274
- path,
275
- content: await content.bytes()
276
- })));
277
- const digests = files.map(({ path, content }) => ({
278
- path,
279
- digest: shortDigest(content)
280
- }));
281
- const buckets = bucketDigests(digests);
282
- const body = await releaseUpload({ manifest: release.manifest, options: settings, buckets }, files, await compare(buckets), onProgress);
443
+ const body = await upload(release, settings, onProgress);
283
444
  return releaseSchema.parse(await operation(await call("/deploy", { method: "POST", ...body }), onProgress));
284
445
  },
446
+ queueDeployment: async (release, settings, onProgress) => {
447
+ const body = await upload(release, settings, onProgress);
448
+ const response = await request("/api/deployments", {
449
+ method: "POST",
450
+ ...body
451
+ });
452
+ if (response.status === 404) {
453
+ return null;
454
+ }
455
+ return deploymentCreatedSchema.parse(await (await answered(response)).json());
456
+ },
457
+ deployments: () => get("/api/deployments", deploymentListSchema),
458
+ deploymentEvents: async function* (id, after) {
459
+ const response = await call(`/api/deployments/${encodeURIComponent(id)}/events?after=${after}`, { headers: { Accept: "text/event-stream" } });
460
+ if (!response.body) {
461
+ throw new AgentUnreachable("The agent returned no event stream");
462
+ }
463
+ for await (const event of serverSentEvents(response.body)) {
464
+ if (event.name === "record") {
465
+ yield {
466
+ kind: "record",
467
+ record: deploymentRecordSchema.parse(JSON.parse(event.data))
468
+ };
469
+ } else if (event.name === "log") {
470
+ yield {
471
+ kind: "log",
472
+ line: deploymentLogLineSchema.parse(JSON.parse(event.data))
473
+ };
474
+ }
475
+ }
476
+ },
477
+ approve: async (id, approval) => {
478
+ await call(`/api/deployments/${encodeURIComponent(id)}/approve`, {
479
+ method: "POST",
480
+ headers: { "Content-Type": "application/json" },
481
+ body: JSON.stringify(approval)
482
+ });
483
+ },
484
+ redeploy: (id, mode) => send("POST", `/api/deployments/${encodeURIComponent(id)}/redeploy`, { mode }, deploymentCreatedSchema),
485
+ rollback: (id) => send("POST", `/api/deployments/${encodeURIComponent(id)}/rollback`, {}, deploymentCreatedSchema),
285
486
  login: async (credentials, onProgress) => loginResultSchema.parse(await operation(await call("/login", {
286
487
  method: "POST",
287
488
  headers: { "Content-Type": "application/json" },
@@ -305,8 +506,9 @@ var releaseUpload = async (header, files, { base, changed }, onProgress) => {
305
506
  };
306
507
  export {
307
508
  AgentOperationError,
509
+ AgentUnreachable,
308
510
  createAgentClient
309
511
  };
310
512
 
311
- //# debugId=1ABBF14A2AD02D7364756E2164756E21
513
+ //# debugId=7C4618C926EB836364756E2164756E21
312
514
  //# sourceMappingURL=client.js.map
@@ -2,11 +2,11 @@
2
2
  "version": 3,
3
3
  "sources": ["../src/client.ts", "../src/protocol.ts", "../src/transfer.ts"],
4
4
  "sourcesContent": [
5
- "import { hostname, userInfo } from \"node:os\";\nimport {\n\ttype LoginCommand,\n\tloginResultSchema,\n\ttype Rollback,\n\tworkerScriptsDigest,\n} from \"@tsplc/build\";\nimport { z } from \"zod\";\nimport {\n\tagentVersionHeader,\n\ttype Comparison,\n\ttype Credentials,\n\tclientHeaders,\n\tcomparisonSchema,\n\tcontrollerSchema,\n\ttype DeployOptions,\n\terrorSchema,\n\teventSchema,\n\tlogoutSchema,\n\tnetworkInterfaceSchema,\n\ttype ReleaseManifest,\n\ttype ReleaseUpload,\n\treleaseSchema,\n\treleaseUploadType,\n\tstatusSchema,\n\ttype Target,\n\ttargetSchema,\n\ttsplcVersion,\n\tupgradesItself,\n\tvariableSchema,\n\tversionMismatch,\n} from \"./protocol\";\nimport {\n\tbucketDigests,\n\tencodeUpload,\n\tfileBucket,\n\ttype ReleaseContent,\n\tshortDigest,\n} from \"./transfer\";\n\n/**\n * A failed agent operation; `downloadRequired` means only a full download can deploy, and\n * `rollback` what became of the controller after a download failed mid-transfer.\n */\nexport class AgentOperationError extends Error {\n\treadonly downloadRequired: boolean;\n\treadonly rollback: Rollback | undefined;\n\n\tconstructor(\n\t\tmessage: string,\n\t\t{\n\t\t\tdownloadRequired = false,\n\t\t\trollback,\n\t\t}: { downloadRequired?: boolean; rollback?: Rollback } = {},\n\t) {\n\t\tsuper(message);\n\t\tthis.downloadRequired = downloadRequired;\n\t\tthis.rollback = rollback;\n\t}\n}\n\n/** A file to upload, at its path in the release. */\nexport interface ReleaseFile {\n\tpath: string;\n\tcontent: Blob;\n}\n\n/** Talks to a plant agent at `url`, such as its Tailscale name and port. */\nexport const createAgentClient = (options: { url: string; token: string }) => {\n\t// The agent records who deployed and who changed the controller, and refuses another tsPLC version.\n\tconst identity = workerScriptsDigest()\n\t\t.then(\n\t\t\t(scripts) => ({ [clientHeaders.scripts]: scripts }),\n\t\t\t// The digest only tells local builds apart; an installation that can't read its scripts still deploys.\n\t\t\t() => ({}),\n\t\t)\n\t\t.then((scripts) => ({\n\t\t\t[clientHeaders.user]: userInfo().username,\n\t\t\t[clientHeaders.host]: hostname(),\n\t\t\t[clientHeaders.version]: tsplcVersion,\n\t\t\t...scripts,\n\t\t}));\n\tconst call = async (path: string, init: RequestInit = {}) => {\n\t\tconst response = await fetch(new URL(path, options.url), {\n\t\t\t...init,\n\t\t\theaders: {\n\t\t\t\t...init.headers,\n\t\t\t\t...(await identity),\n\t\t\t\tAuthorization: `Bearer ${options.token}`,\n\t\t\t},\n\t\t}).catch((cause: unknown) => {\n\t\t\tthrow new Error(`Cannot reach the plant agent at ${options.url}`, {\n\t\t\t\tcause,\n\t\t\t});\n\t\t});\n\t\tif (!response.ok) {\n\t\t\tconst body = await response.json().catch(() => ({}));\n\t\t\tthrow new AgentOperationError(\n\t\t\t\terrorSchema.safeParse(body).data?.error ??\n\t\t\t\t\t`The agent answered ${response.status}`,\n\t\t\t);\n\t\t}\n\t\treturn response;\n\t};\n\tconst get = async <T>(path: string, schema: z.ZodType<T>) =>\n\t\tschema.parse(await (await call(path)).json());\n\tconst send = async <T>(\n\t\tmethod: string,\n\t\tpath: string,\n\t\tbody: unknown,\n\t\tschema: z.ZodType<T>,\n\t) =>\n\t\tschema.parse(\n\t\t\tawait (\n\t\t\t\tawait call(path, {\n\t\t\t\t\tmethod,\n\t\t\t\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\t\t\t\tbody: JSON.stringify(body),\n\t\t\t\t})\n\t\t\t).json(),\n\t\t);\n\n\t/** Reads a streamed operation, reporting progress, until its result or failure. */\n\tconst operation = async (\n\t\tresponse: Response,\n\t\tonProgress: (message: string) => void,\n\t) => {\n\t\tconst reader = response.body\n\t\t\t?.pipeThrough(new TextDecoderStream())\n\t\t\t.getReader();\n\t\tif (!reader) {\n\t\t\tthrow new Error(\"The agent returned no operation stream\");\n\t\t}\n\t\tlet buffered = \"\";\n\t\twhile (true) {\n\t\t\tconst { done, value } = await reader.read();\n\t\t\tif (done) {\n\t\t\t\tthrow new Error(\"The agent closed the operation without a result\");\n\t\t\t}\n\t\t\tbuffered += value;\n\t\t\tconst lines = buffered.split(\"\\n\");\n\t\t\tbuffered = lines.pop() ?? \"\";\n\t\t\tfor (const line of lines.filter(Boolean)) {\n\t\t\t\tconst event = eventSchema.parse(JSON.parse(line));\n\t\t\t\tif (event.kind === \"progress\") {\n\t\t\t\t\tonProgress(event.message);\n\t\t\t\t} else if (event.kind === \"done\") {\n\t\t\t\t\treturn event.result;\n\t\t\t\t} else {\n\t\t\t\t\tthrow new AgentOperationError(event.message, {\n\t\t\t\t\t\tdownloadRequired: event.downloadRequired,\n\t\t\t\t\t\trollback: event.rollback,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t};\n\n\t/** What the agent holds of a release with these bucket digests. */\n\tconst compare = (buckets: string[]) =>\n\t\tsend(\"POST\", \"/releases/compare\", { buckets }, comparisonSchema);\n\n\treturn {\n\t\tstatus: () => get(\"/status\", statusSchema),\n\t\tinterfaces: () => get(\"/interfaces\", z.array(networkInterfaceSchema)),\n\t\tdiscover: (name: string) =>\n\t\t\tsend(\"POST\", \"/discover\", { name }, z.array(controllerSchema)),\n\t\tsetTarget: (target: Target) => send(\"PUT\", \"/target\", target, targetSchema),\n\t\tvariables: () => get(\"/variables\", z.array(variableSchema)),\n\t\tdeploy: async (\n\t\t\trelease: { manifest: ReleaseManifest; files: ReleaseFile[] },\n\t\t\tsettings: DeployOptions,\n\t\t\tonProgress: (message: string) => void,\n\t\t) => {\n\t\t\t// Before uploading: an agent of another version, including one from before version checks,\n\t\t\t// would compile the release with scripts this client doesn't expect.\n\t\t\tconst agentVersion = (await call(\"/status\")).headers.get(\n\t\t\t\tagentVersionHeader,\n\t\t\t);\n\t\t\tif (agentVersion !== tsplcVersion) {\n\t\t\t\tthrow new AgentOperationError(\n\t\t\t\t\tversionMismatch({\n\t\t\t\t\t\tagent: agentVersion,\n\t\t\t\t\t\tclient: tsplcVersion,\n\t\t\t\t\t\tagentUpgrades: upgradesItself(agentVersion),\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst files = await Promise.all(\n\t\t\t\trelease.files.map(async ({ path, content }) => ({\n\t\t\t\t\tpath,\n\t\t\t\t\tcontent: await content.bytes(),\n\t\t\t\t})),\n\t\t\t);\n\t\t\tconst digests = files.map(({ path, content }) => ({\n\t\t\t\tpath,\n\t\t\t\tdigest: shortDigest(content),\n\t\t\t}));\n\t\t\tconst buckets = bucketDigests(digests);\n\t\t\tconst body = await releaseUpload(\n\t\t\t\t{ manifest: release.manifest, options: settings, buckets },\n\t\t\t\tfiles,\n\t\t\t\tawait compare(buckets),\n\t\t\t\tonProgress,\n\t\t\t);\n\t\t\treturn releaseSchema.parse(\n\t\t\t\tawait operation(\n\t\t\t\t\tawait call(\"/deploy\", { method: \"POST\", ...body }),\n\t\t\t\t\tonProgress,\n\t\t\t\t),\n\t\t\t);\n\t\t},\n\t\tlogin: async (\n\t\t\tcredentials: Credentials | null,\n\t\t\tonProgress: (message: string) => void,\n\t\t) =>\n\t\t\tloginResultSchema.parse(\n\t\t\t\tawait operation(\n\t\t\t\t\tawait call(\"/login\", {\n\t\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\t\t\t\t\tbody: JSON.stringify(credentials),\n\t\t\t\t\t}),\n\t\t\t\t\tonProgress,\n\t\t\t\t),\n\t\t\t),\n\t\tcommand: (command: LoginCommand) =>\n\t\t\tsend(\"POST\", \"/login/command\", command, loginResultSchema),\n\t\tlogout: () => send(\"DELETE\", \"/login\", undefined, logoutSchema),\n\t};\n};\nexport type AgentClient = ReturnType<typeof createAgentClient>;\n\n/**\n * A release upload built on the release the agent compared it with: in each bucket that differs,\n * the files the agent lacks and the paths to drop. Without a base, every file.\n */\nconst releaseUpload = async (\n\theader: Pick<ReleaseUpload, \"manifest\" | \"options\" | \"buckets\">,\n\tfiles: readonly ReleaseContent[],\n\t{ base, changed }: Comparison,\n\tonProgress: (message: string) => void,\n) => {\n\tconst stored = new Map(changed.map(({ bucket, files }) => [bucket, files]));\n\tconst uploaded =\n\t\tbase === null\n\t\t\t? files\n\t\t\t: files.filter(({ path, content }) => {\n\t\t\t\t\tconst held = stored.get(fileBucket(path));\n\t\t\t\t\treturn held !== undefined && held[path] !== shortDigest(content);\n\t\t\t\t});\n\tconst paths = new Set(files.map(({ path }) => path));\n\tconst remove = [...stored.values()].flatMap((held) =>\n\t\tObject.keys(held).filter((path) => !paths.has(path)),\n\t);\n\tconst body = await encodeUpload(\n\t\t{ ...header, base, remove } satisfies ReleaseUpload,\n\t\tuploaded,\n\t);\n\tonProgress(\n\t\t`Uploading ${uploaded.length} of ${files.length} files (${Math.ceil(body.length / 1024)} KB)`,\n\t);\n\treturn { headers: { \"Content-Type\": releaseUploadType }, body };\n};\n",
6
- "import { rollbackSchema } from \"@tsplc/build\";\nimport { tsplcConfigSchema } from \"@tsplc/config\";\nimport { releaseConfigSchema, tcpPort } from \"@tsplc/config/build\";\nimport { z } from \"zod\";\nimport { version } from \"../package.json\";\n\n/** The tsPLC version a client and the agent it deploys through must share. */\nexport const tsplcVersion = version;\n\n/** The controller the agent deploys to, as its runtime's TCP block driver address. */\nexport const targetSchema = z.strictObject({\n\thost: z.string().nonempty(),\n\tport: tcpPort,\n});\nexport type Target = z.infer<typeof targetSchema>;\n\nexport const networkInterfaceSchema = z.strictObject({\n\tname: z.string(),\n\taddress: z.ipv4(),\n\tprefixLength: z.number().int().min(0).max(32),\n});\nexport type NetworkInterface = z.infer<typeof networkInterfaceSchema>;\n\n/** A host on the scanned subnet that accepts connections on the CODESYS runtime port. */\nexport const controllerSchema = z.strictObject({\n\taddress: z.ipv4(),\n\tport: z.number().int(),\n\thostname: z.string().nullable(),\n});\nexport type DiscoveredController = z.infer<typeof controllerSchema>;\n\n/** `POST /discover`: the network interface to scan for controllers. */\nexport const discoverSchema = z.strictObject({ name: z.string() });\n\n/**\n * The controller's user, which the agent passes to CODESYS for one operation. A request sends\n * null instead to use the one stored on the agent's PC.\n */\nexport const credentialsSchema = z.strictObject({\n\tusername: z.string().nonempty(),\n\tpassword: z.string().nonempty(),\n});\nexport type Credentials = z.infer<typeof credentialsSchema>;\n\n/** A published leaf of the deployed program, as CODESYS expressions name it. */\nexport const variableSchema = z.strictObject({\n\tpath: z.string(),\n\ttype: z.string(),\n});\nexport type Variable = z.infer<typeof variableSchema>;\n\n/**\n * What `tsplc deploy` uploads beside its files. `config` is the build config with paths\n * relative to the release: `st/`, `template.project` and `libraries/`.\n */\nexport const releaseManifestSchema = z.strictObject({\n\t// Checked against the owner's schema but kept as uploaded: the release id hashes the manifest.\n\tconfig: z.record(z.string(), z.unknown()).superRefine((config, context) => {\n\t\tconst release = releaseConfigSchema.safeParse(config);\n\t\tif (!release.success) {\n\t\t\tcontext.addIssue({\n\t\t\t\tcode: \"custom\",\n\t\t\t\tmessage: `Invalid release config: ${z.prettifyError(release.error)}`,\n\t\t\t});\n\t\t}\n\t}),\n\tvariables: z.array(variableSchema),\n\t/** The server executable's path in the release, when the project builds one. */\n\tserver: z.string().nonempty().optional(),\n\t/** The project's `debug` section; the program's debug manifest is the release's `debug.json`. */\n\tdebug: tsplcConfigSchema.shape.debug,\n\t/** The variable in the agent's environment holding the server's bearer token, for its telemetry and request trace. */\n\tserverTokenEnv: z.string().nonempty().optional(),\n\t/** The project's `secrets`, whose placeholders in the ST the agent fills in from Bun.secrets. */\n\tsecrets: tsplcConfigSchema.shape.secrets,\n});\nexport type ReleaseManifest = z.infer<typeof releaseManifestSchema>;\n\n/** How `tsplc deploy` compresses each file of a multipart upload, the only form agents without `POST /releases/compare` accept. */\nexport const uploadEncoding = \"gzip\";\n\nexport const deployOptionsSchema = z\n\t.strictObject({\n\t\tcredentials: credentialsSchema.nullable(),\n\t\t/** A full download stops the application; without it only an online change is applied. */\n\t\tdownload: z.boolean(),\n\t\tinitializeUser: z.boolean(),\n\t})\n\t.refine(\n\t\t(options) => options.credentials || !options.initializeUser,\n\t\t\"Initializing the controller's user needs the user's credentials.\",\n\t);\nexport type DeployOptions = z.infer<typeof deployOptionsSchema>;\n\n/** How many buckets a release's files fall into for `POST /releases/compare`. */\nexport const releaseBuckets = 256;\n\n/** A release id, or the start of a SHA-256 of content: 16 lowercase hex digits. */\nconst shortHex = z.string().regex(/^[a-f0-9]{16}$/);\n\n/** `POST /releases/compare`: the digest of each bucket of the release about to be deployed. */\nexport const compareRequestSchema = z.strictObject({\n\tbuckets: z.array(shortHex).length(releaseBuckets),\n});\n\n/**\n * Its answer: the stored release the upload can build on, and that release's files, by path and\n * digest, in each bucket that differs. Without a base the whole release is uploaded.\n */\nexport const comparisonSchema = z.strictObject({\n\tbase: shortHex.nullable(),\n\tchanged: z.array(\n\t\tz.strictObject({\n\t\t\tbucket: z\n\t\t\t\t.number()\n\t\t\t\t.int()\n\t\t\t\t.min(0)\n\t\t\t\t.max(releaseBuckets - 1),\n\t\t\tfiles: z.record(z.string(), shortHex),\n\t\t}),\n\t),\n});\nexport type Comparison = z.infer<typeof comparisonSchema>;\n\n/** A `POST /deploy` body in this form is one release upload rather than a multipart form. */\nexport const releaseUploadType = \"application/vnd.tsplc.release+zstd\";\n\n/**\n * A release upload's header. The release is `base`'s files without the `remove` paths, with the\n * uploaded files added or replacing theirs; `buckets` are the digests it must then have.\n */\nexport const releaseUploadSchema = z.strictObject({\n\tmanifest: releaseManifestSchema,\n\toptions: deployOptionsSchema,\n\tbase: shortHex.nullable(),\n\tbuckets: compareRequestSchema.shape.buckets,\n\tremove: z.array(z.string()),\n});\nexport type ReleaseUpload = z.infer<typeof releaseUploadSchema>;\n\n/** Long operations stream one of these per line. */\nexport const eventSchema = z.discriminatedUnion(\"kind\", [\n\tz.strictObject({ kind: z.literal(\"progress\"), message: z.string() }),\n\tz.strictObject({ kind: z.literal(\"done\"), result: z.unknown() }),\n\tz.strictObject({\n\t\tkind: z.literal(\"error\"),\n\t\tmessage: z.string(),\n\t\t/** The controller has no application from this agent yet, so only a full download can deploy. */\n\t\tdownloadRequired: z.boolean(),\n\t\t/**\n\t\t * What became of the controller after a download failed mid-transfer. Sent only to clients that\n\t\t * send their version, since earlier clients reject an event with fields they don't know.\n\t\t */\n\t\trollback: rollbackSchema.optional(),\n\t}),\n]);\nexport type AgentEvent = z.infer<typeof eventSchema>;\n\n/** A failed request's body. */\nexport const errorSchema = z.object({ error: z.string() });\n\nconst deployOperationSchema = z.enum([\"download\", \"online-change\"]);\n\nexport const releaseSchema = z.strictObject({\n\tid: z.string(),\n\tdeployedAt: z.iso.datetime(),\n\toperation: deployOperationSchema,\n\tcontrollerIds: z.strictObject({ codeId: z.string(), dataId: z.string() }),\n\t/** The running server executable, relative to the releases directory. */\n\tserver: z.string().optional(),\n});\nexport type Release = z.infer<typeof releaseSchema>;\n\nexport const statusSchema = z.strictObject({\n\ttarget: targetSchema.nullable(),\n\trelease: releaseSchema.nullable(),\n\tserver: z\n\t\t.strictObject({ executable: z.string(), running: z.boolean() })\n\t\t.nullable(),\n\t/** The open login's application state and forced expressions, or why it can't report them. */\n\tlogin: z\n\t\t.union([\n\t\t\tz.strictObject({ state: z.string(), forced: z.array(z.string()) }),\n\t\t\tz.strictObject({ error: z.string() }),\n\t\t])\n\t\t.nullable(),\n\t/** A controller user is stored on the agent's PC, so requests may leave theirs out. */\n\tcredentialsStored: z.boolean(),\n});\nexport type AgentStatus = z.infer<typeof statusSchema>;\n\n/** A logout's result: why the login couldn't log out, when its container had to be removed instead. */\nexport const logoutSchema = z.strictObject({ failure: z.string().optional() });\n\n/** Who ran a command, and with which tsPLC, as the client reports it in these headers. */\nexport const clientHeaders = {\n\tuser: \"x-tsplc-user\",\n\thost: \"x-tsplc-host\",\n\tversion: \"x-tsplc-version\",\n\t/** The client's `workerScriptsDigest`, which tells a local build from a release of its version. */\n\tscripts: \"x-tsplc-scripts\",\n} as const;\n\n/** The header each agent response names the agent's tsPLC version in; agents before 0.3.0 send none. */\nexport const agentVersionHeader = \"x-tsplc-agent-version\";\n\n/** Whether `version` is at least `minimum`, comparing major, minor and patch. */\nconst atLeast = (version: string, minimum: [number, number, number]) => {\n\tconst parts = version.split(/[.+-]/).slice(0, 3).map(Number);\n\tfor (const [index, wanted] of minimum.entries()) {\n\t\tconst part = parts[index] ?? 0;\n\t\tif (part !== wanted) {\n\t\t\treturn part > wanted;\n\t\t}\n\t}\n\treturn true;\n};\n\n/** Whether an agent of `version` has `tsplc-agent upgrade`, which arrived in 0.5.0. */\nexport const upgradesItself = (version: string | null) =>\n\tversion !== null && atLeast(version, [0, 5, 0]);\n\n/** Why a client and an agent of different tsPLC versions don't deploy, and what to do about it. */\nexport const versionMismatch = (versions: {\n\tagent: string | null;\n\tclient: string;\n\t/** The agent has `tsplc-agent upgrade`. */\n\tagentUpgrades: boolean;\n}) =>\n\t`The plant agent runs ${versions.agent ? `tsPLC ${versions.agent}` : \"a tsPLC older than 0.3.0\"}, but this deployment comes from tsPLC ${versions.client}. A release is compiled by the agent's own CODESYS scripts, so the two must match: on the plant PC, run ${versions.agentUpgrades ? `tsplc-agent upgrade ${versions.client}` : `bun add --global @tsplc/agent@${versions.client}, then restart tsplc-agent serve`}${versions.agent ? `, or deploy with tsPLC ${versions.agent}` : \"\"}`;\n\n/** Who sent a request, as the client reports it. */\nexport const clientIdentity = (request: Request) => {\n\tconst header = (name: string) =>\n\t\trequest.headers.get(name)?.slice(0, 200) || undefined;\n\treturn { user: header(clientHeaders.user), host: header(clientHeaders.host) };\n};\nexport type ClientIdentity = ReturnType<typeof clientIdentity>;\n\n/** The tsPLC a request's client runs, as it reports it; clients before 0.3.0 report none. */\nexport const clientRelease = (request: Request) => ({\n\tversion:\n\t\trequest.headers.get(clientHeaders.version)?.slice(0, 50) || undefined,\n\tscripts:\n\t\trequest.headers.get(clientHeaders.scripts)?.slice(0, 100) || undefined,\n});\nexport type ClientRelease = ReturnType<typeof clientRelease>;\n\n/** A line of the agent's `deployments.jsonl`. */\nexport const deploymentSchema = z.strictObject({\n\tat: z.iso.datetime(),\n\trelease: z.string(),\n\t/** The debug manifest's build id, when the release has one. */\n\tbuild: z.string().optional(),\n\toperation: deployOperationSchema,\n\t/** Whether the request sent the controller user or the agent used its stored one; lines from before 0.2.18 lack it. */\n\tcredentials: z.enum([\"provided\", \"stored\"]).optional(),\n\tuser: z.string().optional(),\n\thost: z.string().optional(),\n});\nexport type Deployment = z.infer<typeof deploymentSchema>;\n\n/** A line of the agent's `audit.jsonl`: a login command that changed the controller. */\nexport const auditSchema = z.strictObject({\n\tat: z.iso.datetime(),\n\t/** As typed after `tsplc`, such as `force` or `reset cold`. */\n\tcommand: z.string(),\n\t/** Expressions written or forced, with their values; unforced expressions map to \"\". */\n\tvalues: z.record(z.string(), z.string()),\n\t/** The values read just before the command, when the read succeeded. */\n\tprevious: z.record(z.string(), z.string()).optional(),\n\tuser: z.string().optional(),\n\thost: z.string().optional(),\n\trelease: z.string().optional(),\n\terror: z.string().optional(),\n});\nexport type Audit = z.infer<typeof auditSchema>;\n",
5
+ "import { hostname, userInfo } from \"node:os\";\nimport {\n\ttype LoginCommand,\n\tloginResultSchema,\n\ttype Rollback,\n\tworkerScriptsDigest,\n} from \"@tsplc/build\";\nimport { z } from \"zod\";\nimport {\n\tagentVersionHeader,\n\ttype Comparison,\n\ttype Credentials,\n\tclientHeaders,\n\tcomparisonSchema,\n\tcontrollerSchema,\n\ttype DeploymentLogLine,\n\ttype DeploymentMode,\n\ttype DeploymentRecord,\n\ttype DeployOptions,\n\tdeploymentCreatedSchema,\n\tdeploymentListSchema,\n\tdeploymentLogLineSchema,\n\tdeploymentRecordSchema,\n\terrorSchema,\n\teventSchema,\n\tlogoutSchema,\n\tnetworkInterfaceSchema,\n\ttype ReleaseManifest,\n\ttype ReleaseUpload,\n\treleaseSchema,\n\treleaseUploadType,\n\tstatusSchema,\n\ttype Target,\n\ttargetSchema,\n\ttsplcVersion,\n\tupgradesItself,\n\tvariableSchema,\n\tversionMismatch,\n} from \"./protocol\";\nimport {\n\tbucketDigests,\n\tencodeUpload,\n\tfileBucket,\n\ttype ReleaseContent,\n\tshortDigest,\n} from \"./transfer\";\n\n/**\n * A failed agent operation; `downloadRequired` means only a full download can deploy, and\n * `rollback` what became of the controller after a download failed mid-transfer.\n */\nexport class AgentOperationError extends Error {\n\treadonly downloadRequired: boolean;\n\treadonly rollback: Rollback | undefined;\n\n\tconstructor(\n\t\tmessage: string,\n\t\t{\n\t\t\tdownloadRequired = false,\n\t\t\trollback,\n\t\t}: { downloadRequired?: boolean; rollback?: Rollback } = {},\n\t) {\n\t\tsuper(message);\n\t\tthis.downloadRequired = downloadRequired;\n\t\tthis.rollback = rollback;\n\t}\n}\n\n/** The agent can't be reached, or the connection to it broke; trying again may succeed. */\nexport class AgentUnreachable extends Error {}\n\n/** One of a deployment's server-sent events: the whole record, or one log line. */\nexport type DeploymentEvent =\n\t| { kind: \"record\"; record: DeploymentRecord }\n\t| { kind: \"log\"; line: DeploymentLogLine };\n\n/** Each event of a `text/event-stream` body as its name and data; comments and other fields are skipped. */\nasync function* serverSentEvents(body: NonNullable<Response[\"body\"]>) {\n\tconst reader = body.pipeThrough(new TextDecoderStream()).getReader();\n\tlet buffered = \"\";\n\tlet name = \"message\";\n\tlet data: string[] = [];\n\ttry {\n\t\twhile (true) {\n\t\t\tconst { done, value } = await reader.read().catch((cause: unknown) => {\n\t\t\t\tthrow new AgentUnreachable(\"The connection to the agent broke\", {\n\t\t\t\t\tcause,\n\t\t\t\t});\n\t\t\t});\n\t\t\tif (done) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tbuffered += value;\n\t\t\tconst lines = buffered.split(/\\r?\\n/);\n\t\t\tbuffered = lines.pop() ?? \"\";\n\t\t\tfor (const line of lines) {\n\t\t\t\tif (line === \"\") {\n\t\t\t\t\tif (data.length) {\n\t\t\t\t\t\tyield { name, data: data.join(\"\\n\") };\n\t\t\t\t\t}\n\t\t\t\t\tname = \"message\";\n\t\t\t\t\tdata = [];\n\t\t\t\t} else if (line.startsWith(\"event:\")) {\n\t\t\t\t\tname = line.slice(\"event:\".length).trim();\n\t\t\t\t} else if (line.startsWith(\"data:\")) {\n\t\t\t\t\tdata.push(line.slice(\"data:\".length).replace(/^ /, \"\"));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} finally {\n\t\tawait reader.cancel().catch(() => {});\n\t}\n}\n\n/** A file to upload, at its path in the release. */\nexport interface ReleaseFile {\n\tpath: string;\n\tcontent: Blob;\n}\n\n/** Talks to a plant agent at `url`, such as its Tailscale name and port. */\nexport const createAgentClient = (options: { url: string; token: string }) => {\n\t// The agent records who deployed and who changed the controller, and refuses another tsPLC version.\n\tconst identity = workerScriptsDigest()\n\t\t.then(\n\t\t\t(scripts) => ({ [clientHeaders.scripts]: scripts }),\n\t\t\t// The digest only tells local builds apart; an installation that can't read its scripts still deploys.\n\t\t\t() => ({}),\n\t\t)\n\t\t.then((scripts) => ({\n\t\t\t[clientHeaders.user]: userInfo().username,\n\t\t\t[clientHeaders.host]: hostname(),\n\t\t\t[clientHeaders.version]: tsplcVersion,\n\t\t\t...scripts,\n\t\t}));\n\tconst request = async (path: string, init: RequestInit = {}) =>\n\t\tfetch(new URL(path, options.url), {\n\t\t\t...init,\n\t\t\theaders: {\n\t\t\t\t...init.headers,\n\t\t\t\t...(await identity),\n\t\t\t\tAuthorization: `Bearer ${options.token}`,\n\t\t\t},\n\t\t}).catch((cause: unknown) => {\n\t\t\tthrow new AgentUnreachable(\n\t\t\t\t`Cannot reach the plant agent at ${options.url}`,\n\t\t\t\t{ cause },\n\t\t\t);\n\t\t});\n\tconst answered = async (response: Response) => {\n\t\tif (!response.ok) {\n\t\t\tconst body = await response.json().catch(() => ({}));\n\t\t\tthrow new AgentOperationError(\n\t\t\t\terrorSchema.safeParse(body).data?.error ??\n\t\t\t\t\t`The agent answered ${response.status}`,\n\t\t\t);\n\t\t}\n\t\treturn response;\n\t};\n\tconst call = async (path: string, init: RequestInit = {}) =>\n\t\tanswered(await request(path, init));\n\tconst get = async <T>(path: string, schema: z.ZodType<T>) =>\n\t\tschema.parse(await (await call(path)).json());\n\tconst send = async <T>(\n\t\tmethod: string,\n\t\tpath: string,\n\t\tbody: unknown,\n\t\tschema: z.ZodType<T>,\n\t) =>\n\t\tschema.parse(\n\t\t\tawait (\n\t\t\t\tawait call(path, {\n\t\t\t\t\tmethod,\n\t\t\t\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\t\t\t\tbody: JSON.stringify(body),\n\t\t\t\t})\n\t\t\t).json(),\n\t\t);\n\n\t/** Reads a streamed operation, reporting progress, until its result or failure. */\n\tconst operation = async (\n\t\tresponse: Response,\n\t\tonProgress: (message: string) => void,\n\t) => {\n\t\tconst reader = response.body\n\t\t\t?.pipeThrough(new TextDecoderStream())\n\t\t\t.getReader();\n\t\tif (!reader) {\n\t\t\tthrow new Error(\"The agent returned no operation stream\");\n\t\t}\n\t\tlet buffered = \"\";\n\t\twhile (true) {\n\t\t\tconst { done, value } = await reader.read();\n\t\t\tif (done) {\n\t\t\t\tthrow new Error(\"The agent closed the operation without a result\");\n\t\t\t}\n\t\t\tbuffered += value;\n\t\t\tconst lines = buffered.split(\"\\n\");\n\t\t\tbuffered = lines.pop() ?? \"\";\n\t\t\tfor (const line of lines.filter(Boolean)) {\n\t\t\t\tconst event = eventSchema.parse(JSON.parse(line));\n\t\t\t\tif (event.kind === \"progress\") {\n\t\t\t\t\tonProgress(event.message);\n\t\t\t\t} else if (event.kind === \"done\") {\n\t\t\t\t\treturn event.result;\n\t\t\t\t} else {\n\t\t\t\t\tthrow new AgentOperationError(event.message, {\n\t\t\t\t\t\tdownloadRequired: event.downloadRequired,\n\t\t\t\t\t\trollback: event.rollback,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t};\n\n\t/** What the agent holds of a release with these bucket digests. */\n\tconst compare = (buckets: string[]) =>\n\t\tsend(\"POST\", \"/releases/compare\", { buckets }, comparisonSchema);\n\n\t/**\n\t * The upload body of `release`, built on what the agent already holds. Refuses an agent of\n\t * another version first.\n\t */\n\tconst upload = async (\n\t\trelease: { manifest: ReleaseManifest; files: ReleaseFile[] },\n\t\tsettings: DeployOptions,\n\t\tonProgress: (message: string) => void,\n\t) => {\n\t\t// Before uploading: an agent of another version, including one from before version checks,\n\t\t// would compile the release with scripts this client doesn't expect.\n\t\tconst agentVersion = (await call(\"/status\")).headers.get(\n\t\t\tagentVersionHeader,\n\t\t);\n\t\tif (agentVersion !== tsplcVersion) {\n\t\t\tthrow new AgentOperationError(\n\t\t\t\tversionMismatch({\n\t\t\t\t\tagent: agentVersion,\n\t\t\t\t\tclient: tsplcVersion,\n\t\t\t\t\tagentUpgrades: upgradesItself(agentVersion),\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\t\tconst files = await Promise.all(\n\t\t\trelease.files.map(async ({ path, content }) => ({\n\t\t\t\tpath,\n\t\t\t\tcontent: await content.bytes(),\n\t\t\t})),\n\t\t);\n\t\tconst digests = files.map(({ path, content }) => ({\n\t\t\tpath,\n\t\t\tdigest: shortDigest(content),\n\t\t}));\n\t\tconst buckets = bucketDigests(digests);\n\t\treturn releaseUpload(\n\t\t\t{ manifest: release.manifest, options: settings, buckets },\n\t\t\tfiles,\n\t\t\tawait compare(buckets),\n\t\t\tonProgress,\n\t\t);\n\t};\n\n\treturn {\n\t\t/** The agent's address, where its dashboard is. */\n\t\turl: options.url,\n\t\tstatus: () => get(\"/status\", statusSchema),\n\t\tinterfaces: () => get(\"/interfaces\", z.array(networkInterfaceSchema)),\n\t\tdiscover: (name: string) =>\n\t\t\tsend(\"POST\", \"/discover\", { name }, z.array(controllerSchema)),\n\t\tsetTarget: (target: Target) => send(\"PUT\", \"/target\", target, targetSchema),\n\t\tvariables: () => get(\"/variables\", z.array(variableSchema)),\n\t\t/** Deploys `release` at once, streaming its progress: `POST /deploy`. */\n\t\tdeploy: async (\n\t\t\trelease: { manifest: ReleaseManifest; files: ReleaseFile[] },\n\t\t\tsettings: DeployOptions,\n\t\t\tonProgress: (message: string) => void,\n\t\t) => {\n\t\t\tconst body = await upload(release, settings, onProgress);\n\t\t\treturn releaseSchema.parse(\n\t\t\t\tawait operation(\n\t\t\t\t\tawait call(\"/deploy\", { method: \"POST\", ...body }),\n\t\t\t\t\tonProgress,\n\t\t\t\t),\n\t\t\t);\n\t\t},\n\t\t/**\n\t\t * Queues `release` as a deployment the agent runs on its own: `POST /api/deployments`. Null\n\t\t * when the agent has no deployments API, so the caller can deploy at once instead.\n\t\t */\n\t\tqueueDeployment: async (\n\t\t\trelease: { manifest: ReleaseManifest; files: ReleaseFile[] },\n\t\t\tsettings: DeployOptions,\n\t\t\tonProgress: (message: string) => void,\n\t\t) => {\n\t\t\tconst body = await upload(release, settings, onProgress);\n\t\t\tconst response = await request(\"/api/deployments\", {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\t...body,\n\t\t\t});\n\t\t\tif (response.status === 404) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\treturn deploymentCreatedSchema.parse(\n\t\t\t\tawait (await answered(response)).json(),\n\t\t\t);\n\t\t},\n\t\tdeployments: () => get(\"/api/deployments\", deploymentListSchema),\n\t\t/**\n\t\t * A deployment's events from after log line `after`, until the agent ends the stream once\n\t\t * the deployment finishes. A broken connection throws `AgentUnreachable`.\n\t\t */\n\t\tdeploymentEvents: async function* (\n\t\t\tid: string,\n\t\t\tafter: number,\n\t\t): AsyncGenerator<DeploymentEvent> {\n\t\t\tconst response = await call(\n\t\t\t\t`/api/deployments/${encodeURIComponent(id)}/events?after=${after}`,\n\t\t\t\t{ headers: { Accept: \"text/event-stream\" } },\n\t\t\t);\n\t\t\tif (!response.body) {\n\t\t\t\tthrow new AgentUnreachable(\"The agent returned no event stream\");\n\t\t\t}\n\t\t\tfor await (const event of serverSentEvents(response.body)) {\n\t\t\t\tif (event.name === \"record\") {\n\t\t\t\t\tyield {\n\t\t\t\t\t\tkind: \"record\",\n\t\t\t\t\t\trecord: deploymentRecordSchema.parse(JSON.parse(event.data)),\n\t\t\t\t\t};\n\t\t\t\t} else if (event.name === \"log\") {\n\t\t\t\t\tyield {\n\t\t\t\t\t\tkind: \"log\",\n\t\t\t\t\t\tline: deploymentLogLineSchema.parse(JSON.parse(event.data)),\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t/** Approves a deployment that waits on a person, as a full download when `download`. */\n\t\tapprove: async (id: string, approval: { download: boolean }) => {\n\t\t\tawait call(`/api/deployments/${encodeURIComponent(id)}/approve`, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\t\t\tbody: JSON.stringify(approval),\n\t\t\t});\n\t\t},\n\t\tredeploy: (id: string, mode: DeploymentMode) =>\n\t\t\tsend(\n\t\t\t\t\"POST\",\n\t\t\t\t`/api/deployments/${encodeURIComponent(id)}/redeploy`,\n\t\t\t\t{ mode },\n\t\t\t\tdeploymentCreatedSchema,\n\t\t\t),\n\t\trollback: (id: string) =>\n\t\t\tsend(\n\t\t\t\t\"POST\",\n\t\t\t\t`/api/deployments/${encodeURIComponent(id)}/rollback`,\n\t\t\t\t{},\n\t\t\t\tdeploymentCreatedSchema,\n\t\t\t),\n\t\tlogin: async (\n\t\t\tcredentials: Credentials | null,\n\t\t\tonProgress: (message: string) => void,\n\t\t) =>\n\t\t\tloginResultSchema.parse(\n\t\t\t\tawait operation(\n\t\t\t\t\tawait call(\"/login\", {\n\t\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\t\t\t\t\tbody: JSON.stringify(credentials),\n\t\t\t\t\t}),\n\t\t\t\t\tonProgress,\n\t\t\t\t),\n\t\t\t),\n\t\tcommand: (command: LoginCommand) =>\n\t\t\tsend(\"POST\", \"/login/command\", command, loginResultSchema),\n\t\tlogout: () => send(\"DELETE\", \"/login\", undefined, logoutSchema),\n\t};\n};\nexport type AgentClient = ReturnType<typeof createAgentClient>;\n\n/**\n * A release upload built on the release the agent compared it with: in each bucket that differs,\n * the files the agent lacks and the paths to drop. Without a base, every file.\n */\nconst releaseUpload = async (\n\theader: Pick<ReleaseUpload, \"manifest\" | \"options\" | \"buckets\">,\n\tfiles: readonly ReleaseContent[],\n\t{ base, changed }: Comparison,\n\tonProgress: (message: string) => void,\n) => {\n\tconst stored = new Map(changed.map(({ bucket, files }) => [bucket, files]));\n\tconst uploaded =\n\t\tbase === null\n\t\t\t? files\n\t\t\t: files.filter(({ path, content }) => {\n\t\t\t\t\tconst held = stored.get(fileBucket(path));\n\t\t\t\t\treturn held !== undefined && held[path] !== shortDigest(content);\n\t\t\t\t});\n\tconst paths = new Set(files.map(({ path }) => path));\n\tconst remove = [...stored.values()].flatMap((held) =>\n\t\tObject.keys(held).filter((path) => !paths.has(path)),\n\t);\n\tconst body = await encodeUpload(\n\t\t{ ...header, base, remove } satisfies ReleaseUpload,\n\t\tuploaded,\n\t);\n\tonProgress(\n\t\t`Uploading ${uploaded.length} of ${files.length} files (${Math.ceil(body.length / 1024)} KB)`,\n\t);\n\treturn { headers: { \"Content-Type\": releaseUploadType }, body };\n};\n",
6
+ "import { onlineChangeFindingSchema, rollbackSchema } from \"@tsplc/build\";\nimport { secretValue, tsplcConfigSchema } from \"@tsplc/config\";\nimport { releaseConfigSchema, tcpPort } from \"@tsplc/config/build\";\nimport { z } from \"zod\";\nimport { version } from \"../package.json\";\n\n/** The tsPLC version a client and the agent it deploys through must share. */\nexport const tsplcVersion = version;\n\n/** The controller the agent deploys to, as its runtime's TCP block driver address. */\nexport const targetSchema = z.strictObject({\n\thost: z.string().nonempty(),\n\tport: tcpPort,\n});\nexport type Target = z.infer<typeof targetSchema>;\n\nexport const networkInterfaceSchema = z.strictObject({\n\tname: z.string(),\n\taddress: z.ipv4(),\n\tprefixLength: z.number().int().min(0).max(32),\n});\nexport type NetworkInterface = z.infer<typeof networkInterfaceSchema>;\n\n/** A host on the scanned subnet that accepts connections on the CODESYS runtime port. */\nexport const controllerSchema = z.strictObject({\n\taddress: z.ipv4(),\n\tport: z.number().int(),\n\thostname: z.string().nullable(),\n});\nexport type DiscoveredController = z.infer<typeof controllerSchema>;\n\n/** `POST /discover`: the network interface to scan for controllers. */\nexport const discoverSchema = z.strictObject({ name: z.string() });\n\n/**\n * The controller's user, which the agent passes to CODESYS for one operation. A request sends\n * null instead to use the one stored on the agent's PC.\n */\nexport const credentialsSchema = z.strictObject({\n\tusername: z.string().nonempty(),\n\tpassword: z.string().nonempty(),\n});\nexport type Credentials = z.infer<typeof credentialsSchema>;\n\n/** A published leaf of the deployed program, as CODESYS expressions name it. */\nexport const variableSchema = z.strictObject({\n\tpath: z.string(),\n\ttype: z.string(),\n});\nexport type Variable = z.infer<typeof variableSchema>;\n\n/**\n * What `tsplc deploy` uploads beside its files. `config` is the build config with paths\n * relative to the release: `st/`, `template.project` and `libraries/`.\n */\nexport const releaseManifestSchema = z.strictObject({\n\t// Checked against the owner's schema but kept as uploaded: the release id hashes the manifest.\n\tconfig: z.record(z.string(), z.unknown()).superRefine((config, context) => {\n\t\tconst release = releaseConfigSchema.safeParse(config);\n\t\tif (!release.success) {\n\t\t\tcontext.addIssue({\n\t\t\t\tcode: \"custom\",\n\t\t\t\tmessage: `Invalid release config: ${z.prettifyError(release.error)}`,\n\t\t\t});\n\t\t}\n\t}),\n\tvariables: z.array(variableSchema),\n\t/** The server executable's path in the release, when the project builds one. */\n\tserver: z.string().nonempty().optional(),\n\t/** The project's `debug` section; the program's debug manifest is the release's `debug.json`. */\n\tdebug: tsplcConfigSchema.shape.debug,\n\t/** The variable in the agent's environment holding the server's bearer token, for its telemetry and request trace. */\n\tserverTokenEnv: z.string().nonempty().optional(),\n\t/** The project's `secrets`, whose placeholders in the ST the agent fills in from Bun.secrets. */\n\tsecrets: tsplcConfigSchema.shape.secrets,\n});\nexport type ReleaseManifest = z.infer<typeof releaseManifestSchema>;\n\n/** How `tsplc deploy` compresses each file of a multipart upload, the only form agents without `POST /releases/compare` accept. */\nexport const uploadEncoding = \"gzip\";\n\nexport const deployOptionsSchema = z\n\t.strictObject({\n\t\tcredentials: credentialsSchema.nullable(),\n\t\t/** A full download stops the application; without it only an online change is applied. */\n\t\tdownload: z.boolean(),\n\t\tinitializeUser: z.boolean(),\n\t\t/** How `POST /api/deployments` queues it; `POST /deploy` runs it at once and ignores this. */\n\t\tdeployment: z.lazy(() => deploymentRequestSchema).optional(),\n\t})\n\t.refine(\n\t\t(options) => options.credentials || !options.initializeUser,\n\t\t\"Initializing the controller's user needs the user's credentials.\",\n\t);\nexport type DeployOptions = z.infer<typeof deployOptionsSchema>;\n\n/** How many buckets a release's files fall into for `POST /releases/compare`. */\nexport const releaseBuckets = 256;\n\n/** A release id, or the start of a SHA-256 of content: 16 lowercase hex digits. */\nconst shortHex = z.string().regex(/^[a-f0-9]{16}$/);\n\n/** `POST /releases/compare`: the digest of each bucket of the release about to be deployed. */\nexport const compareRequestSchema = z.strictObject({\n\tbuckets: z.array(shortHex).length(releaseBuckets),\n});\n\n/**\n * Its answer: the stored release the upload can build on, and that release's files, by path and\n * digest, in each bucket that differs. Without a base the whole release is uploaded.\n */\nexport const comparisonSchema = z.strictObject({\n\tbase: shortHex.nullable(),\n\tchanged: z.array(\n\t\tz.strictObject({\n\t\t\tbucket: z\n\t\t\t\t.number()\n\t\t\t\t.int()\n\t\t\t\t.min(0)\n\t\t\t\t.max(releaseBuckets - 1),\n\t\t\tfiles: z.record(z.string(), shortHex),\n\t\t}),\n\t),\n});\nexport type Comparison = z.infer<typeof comparisonSchema>;\n\n/** A `POST /deploy` body in this form is one release upload rather than a multipart form. */\nexport const releaseUploadType = \"application/vnd.tsplc.release+zstd\";\n\n/**\n * A release upload's header. The release is `base`'s files without the `remove` paths, with the\n * uploaded files added or replacing theirs; `buckets` are the digests it must then have.\n */\nexport const releaseUploadSchema = z.strictObject({\n\tmanifest: releaseManifestSchema,\n\toptions: deployOptionsSchema,\n\tbase: shortHex.nullable(),\n\tbuckets: compareRequestSchema.shape.buckets,\n\tremove: z.array(z.string()),\n});\nexport type ReleaseUpload = z.infer<typeof releaseUploadSchema>;\n\n/** Long operations stream one of these per line. */\nexport const eventSchema = z.discriminatedUnion(\"kind\", [\n\tz.strictObject({ kind: z.literal(\"progress\"), message: z.string() }),\n\tz.strictObject({ kind: z.literal(\"done\"), result: z.unknown() }),\n\tz.strictObject({\n\t\tkind: z.literal(\"error\"),\n\t\tmessage: z.string(),\n\t\t/** The controller has no application from this agent yet, so only a full download can deploy. */\n\t\tdownloadRequired: z.boolean(),\n\t\t/**\n\t\t * What became of the controller after a download failed mid-transfer. Sent only to clients that\n\t\t * send their version, since earlier clients reject an event with fields they don't know.\n\t\t */\n\t\trollback: rollbackSchema.optional(),\n\t}),\n]);\nexport type AgentEvent = z.infer<typeof eventSchema>;\n\n/** A failed request's body. */\nexport const errorSchema = z.object({ error: z.string() });\n\nconst deployOperationSchema = z.enum([\"download\", \"online-change\"]);\n\nexport const releaseSchema = z.strictObject({\n\tid: z.string(),\n\tdeployedAt: z.iso.datetime(),\n\toperation: deployOperationSchema,\n\tcontrollerIds: z.strictObject({ codeId: z.string(), dataId: z.string() }),\n\t/** The running server executable, relative to the releases directory. */\n\tserver: z.string().optional(),\n});\nexport type Release = z.infer<typeof releaseSchema>;\n\nexport const statusSchema = z.strictObject({\n\ttarget: targetSchema.nullable(),\n\trelease: releaseSchema.nullable(),\n\tserver: z\n\t\t.strictObject({ executable: z.string(), running: z.boolean() })\n\t\t.nullable(),\n\t/** The open login's application state and forced expressions, or why it can't report them. */\n\tlogin: z\n\t\t.union([\n\t\t\tz.strictObject({ state: z.string(), forced: z.array(z.string()) }),\n\t\t\tz.strictObject({ error: z.string() }),\n\t\t])\n\t\t.nullable(),\n\t/** A controller user is stored on the agent's PC, so requests may leave theirs out. */\n\tcredentialsStored: z.boolean(),\n});\nexport type AgentStatus = z.infer<typeof statusSchema>;\n\n/** A logout's result: why the login couldn't log out, when its container had to be removed instead. */\nexport const logoutSchema = z.strictObject({ failure: z.string().optional() });\n\n/** Who ran a command, and with which tsPLC, as the client reports it in these headers. */\nexport const clientHeaders = {\n\tuser: \"x-tsplc-user\",\n\thost: \"x-tsplc-host\",\n\tversion: \"x-tsplc-version\",\n\t/** The client's `workerScriptsDigest`, which tells a local build from a release of its version. */\n\tscripts: \"x-tsplc-scripts\",\n} as const;\n\n/** The header each agent response names the agent's tsPLC version in; agents before 0.3.0 send none. */\nexport const agentVersionHeader = \"x-tsplc-agent-version\";\n\n/** Whether `version` is at least `minimum`, comparing major, minor and patch. */\nconst atLeast = (version: string, minimum: [number, number, number]) => {\n\tconst parts = version.split(/[.+-]/).slice(0, 3).map(Number);\n\tfor (const [index, wanted] of minimum.entries()) {\n\t\tconst part = parts[index] ?? 0;\n\t\tif (part !== wanted) {\n\t\t\treturn part > wanted;\n\t\t}\n\t}\n\treturn true;\n};\n\n/** Whether an agent of `version` has `tsplc-agent upgrade`, which arrived in 0.5.0. */\nexport const upgradesItself = (version: string | null) =>\n\tversion !== null && atLeast(version, [0, 5, 0]);\n\n/** Why a client and an agent of different tsPLC versions don't deploy, and what to do about it. */\nexport const versionMismatch = (versions: {\n\tagent: string | null;\n\tclient: string;\n\t/** The agent has `tsplc-agent upgrade`. */\n\tagentUpgrades: boolean;\n}) =>\n\t`The plant agent runs ${versions.agent ? `tsPLC ${versions.agent}` : \"a tsPLC older than 0.3.0\"}, but this deployment comes from tsPLC ${versions.client}. A release is compiled by the agent's own CODESYS scripts, so the two must match: on the plant PC, run ${versions.agentUpgrades ? `tsplc-agent upgrade ${versions.client}` : `bun add --global @tsplc/agent@${versions.client}, then restart tsplc-agent serve`}${versions.agent ? `, or deploy with tsPLC ${versions.agent}` : \"\"}`;\n\n/** Who sent a request, as the client reports it. */\nexport const clientIdentity = (request: Request) => {\n\tconst header = (name: string) =>\n\t\trequest.headers.get(name)?.slice(0, 200) || undefined;\n\treturn { user: header(clientHeaders.user), host: header(clientHeaders.host) };\n};\nexport type ClientIdentity = ReturnType<typeof clientIdentity>;\n\n/** The tsPLC a request's client runs, as it reports it; clients before 0.3.0 report none. */\nexport const clientRelease = (request: Request) => ({\n\tversion:\n\t\trequest.headers.get(clientHeaders.version)?.slice(0, 50) || undefined,\n\tscripts:\n\t\trequest.headers.get(clientHeaders.scripts)?.slice(0, 100) || undefined,\n});\nexport type ClientRelease = ReturnType<typeof clientRelease>;\n\n/** A line of the agent's `deployments.jsonl`. */\nexport const deploymentSchema = z.strictObject({\n\tat: z.iso.datetime(),\n\trelease: z.string(),\n\t/** The debug manifest's build id, when the release has one. */\n\tbuild: z.string().optional(),\n\toperation: deployOperationSchema,\n\t/** Whether the request sent the controller user or the agent used its stored one; lines from before 0.2.18 lack it. */\n\tcredentials: z.enum([\"provided\", \"stored\"]).optional(),\n\tuser: z.string().optional(),\n\thost: z.string().optional(),\n});\nexport type Deployment = z.infer<typeof deploymentSchema>;\n\n/** A line of the agent's `audit.jsonl`: a login command that changed the controller. */\nexport const auditSchema = z.strictObject({\n\tat: z.iso.datetime(),\n\t/** As typed after `tsplc`, such as `force` or `reset cold`. */\n\tcommand: z.string(),\n\t/** Expressions written or forced, with their values; unforced expressions map to \"\". */\n\tvalues: z.record(z.string(), z.string()),\n\t/** The values read just before the command, when the read succeeded. */\n\tprevious: z.record(z.string(), z.string()).optional(),\n\tuser: z.string().optional(),\n\thost: z.string().optional(),\n\trelease: z.string().optional(),\n\terror: z.string().optional(),\n});\nexport type Audit = z.infer<typeof auditSchema>;\n\n/**\n * Who may do what on the agent's dashboard and API, each role including the ones before it: a\n * viewer reads deployments, logs, the debugger and the audit log; a deployer also deploys,\n * approves, cancels, redeploys, rolls back and restarts the server; an admin also manages the\n * environment's secrets and who has which role.\n */\nexport const roles = [\"viewer\", \"deployer\", \"admin\"] as const;\nexport const roleSchema = z.enum(roles);\nexport type Role = z.infer<typeof roleSchema>;\n\n/** Whether `role` includes `required`. */\nexport const allows = (role: Role, required: Role) =>\n\troles.indexOf(role) >= roles.indexOf(required);\n\n/** Who made a request, and how the agent knows. */\nexport const identitySchema = z.strictObject({\n\t/** The Tailscale login, or null for a token or a request from the agent's own PC. */\n\tlogin: z.string().nullable(),\n\t/** A name to show: the Tailscale display name, or how the token or PC is known. */\n\tname: z.string(),\n\trole: roleSchema,\n\tvia: z.enum([\"tailscale\", \"token\", \"local\"]),\n});\nexport type Identity = z.infer<typeof identitySchema>;\n\n/** The commit a deployment was built from, when `tsplc deploy` ran in a git checkout. */\nexport const gitSourceSchema = z.strictObject({\n\tcommit: z.string().nonempty(),\n\tbranch: z.string().nullable(),\n\t/** Uncommitted changes went into the build. */\n\tdirty: z.boolean(),\n\t/** The commit's subject line. */\n\tmessage: z.string().nullable(),\n});\nexport type GitSource = z.infer<typeof gitSourceSchema>;\n\n/**\n * How a deployment applies: `apply` runs it as soon as it is its turn; `review` builds it and\n * checks what an online change would do, then waits for someone to approve it.\n */\nexport const deploymentModeSchema = z.enum([\"apply\", \"review\"]);\nexport type DeploymentMode = z.infer<typeof deploymentModeSchema>;\n\n/**\n * Where a deployment is. `awaitingApproval` waits on a person: a review to apply, or a full\n * download that would stop the line. A finished deployment is `ready`, `error` or `canceled`.\n */\nexport const deploymentStateSchema = z.enum([\n\t\"queued\",\n\t\"building\",\n\t\"awaitingApproval\",\n\t\"applying\",\n\t\"starting\",\n\t\"verifying\",\n\t\"ready\",\n\t\"error\",\n\t\"canceled\",\n]);\nexport type DeploymentState = z.infer<typeof deploymentStateSchema>;\n\n/** The steps a deployment goes through, in order; a deployment skips the ones it doesn't need. */\nexport const deploymentPhaseNameSchema = z.enum([\n\t\"queue\",\n\t\"build\",\n\t\"review\",\n\t\"apply\",\n\t\"server\",\n\t\"health\",\n]);\n\nconst deploymentIdSchema = z.string().regex(/^dpl_[a-z0-9]{16,32}$/);\n\n/**\n * A deployment as the agent keeps it, in `deployments/<id>/record.json` of its state directory.\n * Every record of the last 14 days is kept, and always the running one and the last that was\n * healthy, with their releases.\n */\nexport const deploymentRecordSchema = z.strictObject({\n\tid: deploymentIdSchema,\n\trelease: z.string(),\n\t/** The debug manifest's build id, when the release has one. */\n\tbuild: z.string().nullable(),\n\tcreatedAt: z.iso.datetime(),\n\tupdatedAt: z.iso.datetime(),\n\t/** An upload from `tsplc deploy`, or a release the agent already had, deployed again. */\n\torigin: z.discriminatedUnion(\"kind\", [\n\t\tz.strictObject({ kind: z.literal(\"upload\") }),\n\t\tz.strictObject({ kind: z.literal(\"redeploy\"), from: deploymentIdSchema }),\n\t\tz.strictObject({ kind: z.literal(\"rollback\"), from: deploymentIdSchema }),\n\t]),\n\tgit: gitSourceSchema.nullable(),\n\t/** Who asked for it: the identity behind the request, with the deploying machine's user and host. */\n\trequestedBy: z.strictObject({\n\t\tidentity: identitySchema.omit({ role: true }),\n\t\tuser: z.string().nullable(),\n\t\thost: z.string().nullable(),\n\t}),\n\tmode: deploymentModeSchema,\n\t/** What it applies or applied: an online change unless a full download was asked for or approved. */\n\toperation: deployOperationSchema,\n\tstate: deploymentStateSchema,\n\tphases: z.array(\n\t\tz.strictObject({\n\t\t\tname: deploymentPhaseNameSchema,\n\t\t\tstartedAt: z.iso.datetime(),\n\t\t\tfinishedAt: z.iso.datetime().nullable(),\n\t\t\toutcome: z.enum([\"running\", \"ok\", \"failed\", \"skipped\"]),\n\t\t}),\n\t),\n\t/** What the online-change check found: refusals, and what the change restarts. */\n\tfindings: z.array(onlineChangeFindingSchema),\n\t/** What it waits on while `awaitingApproval`. */\n\tapproval: z\n\t\t.strictObject({\n\t\t\treason: z.enum([\"review\", \"downloadRequired\"]),\n\t\t\tmessage: z.string(),\n\t\t})\n\t\t.nullable(),\n\terror: z\n\t\t.strictObject({\n\t\t\tmessage: z.string(),\n\t\t\tdownloadRequired: z.boolean(),\n\t\t\trollback: rollbackSchema.optional(),\n\t\t})\n\t\t.nullable(),\n\tcontrollerIds: z\n\t\t.strictObject({ codeId: z.string(), dataId: z.string() })\n\t\t.nullable(),\n\t/** What the check after applying found; null until it ran. */\n\thealth: z\n\t\t.strictObject({\n\t\t\tcontroller: z.enum([\"ok\", \"failed\"]),\n\t\t\tserver: z.enum([\"ok\", \"failed\", \"none\"]),\n\t\t\tplc: z.enum([\"ok\", \"failed\", \"unknown\"]),\n\t\t\tdetail: z.string().nullable(),\n\t\t})\n\t\t.nullable(),\n\t/** When it became the running deployment, and when another replaced it; null until and while. */\n\tactiveFrom: z.iso.datetime().nullable(),\n\tactiveUntil: z.iso.datetime().nullable(),\n});\nexport type DeploymentRecord = z.infer<typeof deploymentRecordSchema>;\n\n/** One line of a deployment's log, `deployments/<id>/log.jsonl`. */\nexport const deploymentLogLineSchema = z.strictObject({\n\t/** Counts from 1 within the deployment; `?after=` resumes from it. */\n\tseq: z.number().int().positive(),\n\tat: z.iso.datetime(),\n\tlevel: z.enum([\"info\", \"warning\", \"error\"]),\n\tphase: deploymentPhaseNameSchema.nullable(),\n\tmessage: z.string(),\n});\nexport type DeploymentLogLine = z.infer<typeof deploymentLogLineSchema>;\n\n/**\n * What `tsplc deploy` sends with a release to `POST /api/deployments`, in the upload's `options`\n * beside the existing deploy options.\n */\nexport const deploymentRequestSchema = z.strictObject({\n\tmode: deploymentModeSchema,\n\tgit: gitSourceSchema.nullable(),\n});\nexport type DeploymentRequest = z.infer<typeof deploymentRequestSchema>;\n\n/** `POST /api/deployments`'s answer: the queued deployment and the dashboard page that shows it. */\nexport const deploymentCreatedSchema = z.strictObject({\n\tid: deploymentIdSchema,\n\turl: z.string(),\n});\n\n/** `GET /api/deployments`: newest first, with the running and last healthy ones named. */\nexport const deploymentListSchema = z.strictObject({\n\tdeployments: z.array(deploymentRecordSchema),\n\tcurrent: deploymentIdSchema.nullable(),\n\tlastGood: deploymentIdSchema.nullable(),\n});\n\n/** `POST /api/deployments/:id/approve`: apply it, as a full download when one is required. */\nexport const approveSchema = z.strictObject({ download: z.boolean() });\n\n/** `POST /api/deployments/:id/redeploy`: deploy its release again. */\nexport const redeploySchema = z.strictObject({ mode: deploymentModeSchema });\n\n/** `GET /api/deployments/:id/source`: the release's files, by path, with their sizes in bytes. */\nexport const deploymentSourceSchema = z.strictObject({\n\tfiles: z.array(\n\t\tz.strictObject({ path: z.string(), size: z.number().int().nonnegative() }),\n\t),\n});\n\n/** A secret the deployed release's config declares, or one stored without a declaration: never its value. */\nexport const environmentEntrySchema = z.strictObject({\n\tname: z.string(),\n\tdeclared: z.boolean(),\n\tset: z.boolean(),\n});\nexport type EnvironmentEntry = z.infer<typeof environmentEntrySchema>;\n\n/**\n * `access.json` in the agent's state directory, and the body of `GET` and `PUT /api/access`: the\n * role of each Tailscale login, and the role a tailnet member without one gets, none by default.\n */\nexport const accessConfigSchema = z.strictObject({\n\troles: z.record(z.string().nonempty(), roleSchema),\n\ttailnetDefault: roleSchema.nullable(),\n});\nexport type AccessConfig = z.infer<typeof accessConfigSchema>;\n\n/** `POST /api/session`: the agent's full or read token, which signs a browser in. */\nexport const sessionRequestSchema = z.strictObject({ token: z.string() });\n\n/** `PUT /api/environment/:name`: the secret's new value. */\nexport const environmentValueSchema = z.strictObject({ value: secretValue });\n",
7
7
  "import { createHash } from \"node:crypto\";\nimport { releaseBuckets } from \"./protocol\";\n\n/**\n * How `tsplc deploy` sends a release the agent can build from one it already holds. The release's\n * files fall into buckets by path, and each bucket has a digest; the agent answers which buckets\n * differ from a release it stores and that release's files in them, and the client sends only the\n * files the agent lacks, with the release's other parts named rather than sent. The whole upload\n * is one zstd stream: the release's ST files are thousands of small, similar files.\n */\n\n/** A file of a release, at its path in the release. */\nexport interface ReleaseContent {\n\tpath: string;\n\tcontent: Uint8Array<ArrayBuffer>;\n}\n\n/** The first 16 hex digits of a SHA-256: enough to tell a release's files apart, and short on the wire. */\nexport const shortDigest = (data: Uint8Array | string) =>\n\tcreateHash(\"sha256\").update(data).digest(\"hex\").slice(0, 16);\n\n/** The bucket a release path falls in, the same in every release. */\nexport const fileBucket = (path: string) =>\n\tcreateHash(\"sha256\").update(path).digest().readUInt8(0) % releaseBuckets;\n\n/** Each bucket's digest over the paths and contents of its files, from each file's `shortDigest`. */\nexport const bucketDigests = (\n\tfiles: Iterable<{ path: string; digest: string }>,\n): string[] => {\n\tconst buckets = Array.from({ length: releaseBuckets }, (): string[] => []);\n\tfor (const { path, digest } of files) {\n\t\tbuckets[fileBucket(path)]?.push(`${path}\\0${digest}`);\n\t}\n\treturn buckets.map((entries) => shortDigest(entries.sort().join(\"\\n\")));\n};\n\n/** A frame's length prefix: an unsigned 32-bit big-endian byte count. */\nconst lengthBytes = 4;\n\n/** Frames the upload's header and then each file's path and content, and compresses the lot. */\nexport const encodeUpload = async (\n\theader: unknown,\n\tfiles: readonly ReleaseContent[],\n): Promise<Uint8Array<ArrayBuffer>> => {\n\tconst encoder = new TextEncoder();\n\tconst frames = [\n\t\tencoder.encode(JSON.stringify(header)),\n\t\t...files.flatMap(({ path, content }) => [encoder.encode(path), content]),\n\t];\n\tconst body = new Uint8Array(\n\t\tframes.reduce((total, frame) => total + lengthBytes + frame.length, 0),\n\t);\n\tconst view = new DataView(body.buffer);\n\tlet offset = 0;\n\tfor (const frame of frames) {\n\t\tview.setUint32(offset, frame.length);\n\t\tbody.set(frame, offset + lengthBytes);\n\t\toffset += lengthBytes + frame.length;\n\t}\n\treturn new Uint8Array(await Bun.zstdCompress(body, { level: 12 }));\n};\n\n/** An upload's header, still to be validated, and its files. */\nexport const decodeUpload = async (\n\tcompressed: Uint8Array,\n): Promise<{ header: unknown; files: ReleaseContent[] }> => {\n\tconst body = new Uint8Array(await Bun.zstdDecompress(compressed));\n\tconst view = new DataView(body.buffer, body.byteOffset, body.byteLength);\n\tconst frames: Uint8Array<ArrayBuffer>[] = [];\n\tlet offset = 0;\n\twhile (offset < body.length) {\n\t\tif (offset + lengthBytes > body.length) {\n\t\t\tthrow new Error(\"The release upload ends inside a frame\");\n\t\t}\n\t\tconst end = offset + lengthBytes + view.getUint32(offset);\n\t\tif (end > body.length) {\n\t\t\tthrow new Error(\"The release upload ends inside a frame\");\n\t\t}\n\t\tframes.push(body.subarray(offset + lengthBytes, end));\n\t\toffset = end;\n\t}\n\tconst [header, ...rest] = frames;\n\tif (!header || rest.length % 2 !== 0) {\n\t\tthrow new Error(\n\t\t\t\"The release upload has no header or a file without content\",\n\t\t);\n\t}\n\tconst decoder = new TextDecoder();\n\tconst files = Array.from({ length: rest.length / 2 }, (_, index) => ({\n\t\tpath: decoder.decode(rest[2 * index]),\n\t\tcontent: rest[2 * index + 1] ?? new Uint8Array(),\n\t}));\n\treturn { header: JSON.parse(decoder.decode(header)), files };\n};\n"
8
8
  ],
9
- "mappings": ";AAAA;AACA;AAAA;AAAA;AAAA;AAMA,cAAS;;;ACPT;AACA;AACA;AACA;;;;;AAIO,IAAM,eAAe;AAGrB,IAAM,eAAe,EAAE,aAAa;AAAA,EAC1C,MAAM,EAAE,OAAO,EAAE,SAAS;AAAA,EAC1B,MAAM;AACP,CAAC;AAGM,IAAM,yBAAyB,EAAE,aAAa;AAAA,EACpD,MAAM,EAAE,OAAO;AAAA,EACf,SAAS,EAAE,KAAK;AAAA,EAChB,cAAc,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,EAAE,IAAI,EAAE;AAC7C,CAAC;AAIM,IAAM,mBAAmB,EAAE,aAAa;AAAA,EAC9C,SAAS,EAAE,KAAK;AAAA,EAChB,MAAM,EAAE,OAAO,EAAE,IAAI;AAAA,EACrB,UAAU,EAAE,OAAO,EAAE,SAAS;AAC/B,CAAC;AAIM,IAAM,iBAAiB,EAAE,aAAa,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC;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