@tsplc/tmp-agent 0.0.0-stage → 0.6.3

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 (65) hide show
  1. package/README.md +26 -2
  2. package/dist/cli.js +4888 -0
  3. package/dist/cli.js.map +53 -0
  4. package/dist/client.js +514 -0
  5. package/dist/client.js.map +12 -0
  6. package/dist/index.js +3680 -0
  7. package/dist/index.js.map +41 -0
  8. package/package.json +61 -4
  9. package/src/access.ts +260 -0
  10. package/src/agent.ts +461 -0
  11. package/src/audit.ts +74 -0
  12. package/src/cli.ts +290 -0
  13. package/src/client.ts +407 -0
  14. package/src/codesys.ts +195 -0
  15. package/src/dashboard/index.ts +159 -0
  16. package/src/dashboard/ui/access.ts +191 -0
  17. package/src/dashboard/ui/actions.ts +207 -0
  18. package/src/dashboard/ui/api.ts +138 -0
  19. package/src/dashboard/ui/app.ts +41 -0
  20. package/src/dashboard/ui/approval.ts +131 -0
  21. package/src/dashboard/ui/audit.ts +115 -0
  22. package/src/dashboard/ui/contract.ts +19 -0
  23. package/src/dashboard/ui/dashboard.css +1332 -0
  24. package/src/dashboard/ui/deployment.ts +431 -0
  25. package/src/dashboard/ui/deployments.ts +319 -0
  26. package/src/dashboard/ui/details.ts +214 -0
  27. package/src/dashboard/ui/dom.ts +87 -0
  28. package/src/dashboard/ui/environment.ts +345 -0
  29. package/src/dashboard/ui/format.ts +124 -0
  30. package/src/dashboard/ui/logs.ts +126 -0
  31. package/src/dashboard/ui/main.ts +88 -0
  32. package/src/dashboard/ui/overlay.ts +144 -0
  33. package/src/dashboard/ui/shell.ts +185 -0
  34. package/src/dashboard/ui/source.ts +144 -0
  35. package/src/debugging.ts +142 -0
  36. package/src/deploy.ts +203 -0
  37. package/src/deployments/health.ts +98 -0
  38. package/src/deployments/retention.ts +44 -0
  39. package/src/deployments/routes.ts +281 -0
  40. package/src/deployments/runner.ts +900 -0
  41. package/src/deployments/store.ts +209 -0
  42. package/src/deployments/submission.ts +78 -0
  43. package/src/discovery.ts +90 -0
  44. package/src/environment.ts +214 -0
  45. package/src/errors.ts +12 -0
  46. package/src/index.ts +36 -0
  47. package/src/instance.ts +51 -0
  48. package/src/login.ts +267 -0
  49. package/src/logs.ts +115 -0
  50. package/src/maintenance.ts +303 -0
  51. package/src/operations.ts +149 -0
  52. package/src/processes.ts +41 -0
  53. package/src/protocol.ts +557 -0
  54. package/src/releases.ts +414 -0
  55. package/src/restarts.ts +96 -0
  56. package/src/routes.ts +128 -0
  57. package/src/secrets.ts +174 -0
  58. package/src/server-process.ts +264 -0
  59. package/src/service.ts +194 -0
  60. package/src/sessions.ts +58 -0
  61. package/src/state.ts +126 -0
  62. package/src/tailscale.ts +112 -0
  63. package/src/terminal.ts +57 -0
  64. package/src/transfer.ts +94 -0
  65. package/src/upgrade.ts +153 -0
package/src/agent.ts ADDED
@@ -0,0 +1,461 @@
1
+ import { controllerCredentialsSchema, loginCommandSchema } from "@tsplc/build";
2
+ import type { Environment } from "@tsplc/config";
3
+ import { runtimePort } from "@tsplc/config/build";
4
+ import { plantAgentEnv } from "@tsplc/server/plant-agent";
5
+ import { createAccess, type Peer } from "./access";
6
+ import { createAudit } from "./audit";
7
+ import { type CodesysSettings, describeBuilder } from "./codesys";
8
+ import { createDashboard } from "./dashboard";
9
+ import { createDebugging } from "./debugging";
10
+ import { createDeployments } from "./deploy";
11
+ import { createDeploymentRoutes } from "./deployments/routes";
12
+ import { discoverControllers, networkInterfaces } from "./discovery";
13
+ import { createEnvironment } from "./environment";
14
+ import { AgentError, errorMessage } from "./errors";
15
+ import { createLogin } from "./login";
16
+ import { createOperations } from "./operations";
17
+ import {
18
+ type AgentExit,
19
+ type AgentStatus,
20
+ agentExitPath,
21
+ agentHoldPath,
22
+ agentVersionHeader,
23
+ clientIdentity,
24
+ clientRelease,
25
+ compareRequestSchema,
26
+ debuggerMount,
27
+ discoverSchema,
28
+ exitSchema,
29
+ statusPath,
30
+ targetSchema,
31
+ tsplcVersion,
32
+ } from "./protocol";
33
+ import {
34
+ createReleaseStore,
35
+ type ReleaseStore,
36
+ readDeployRequest,
37
+ releaseServerFile,
38
+ storedReleaseOf,
39
+ } from "./releases";
40
+ import { createRestartRoutes } from "./restarts";
41
+ import {
42
+ type ApiRoute,
43
+ answer,
44
+ type Destination,
45
+ routeDestination,
46
+ } from "./routes";
47
+ import { serverEnvironment, storedCredentials } from "./secrets";
48
+ import {
49
+ createServerSupervisor,
50
+ type ServerSupervisor,
51
+ } from "./server-process";
52
+ import { type AgentState, openState } from "./state";
53
+ import { createWhois, runCommand } from "./tailscale";
54
+
55
+ export interface AgentOptions {
56
+ /** Releases, the controller's download baseline and the selected target live here. */
57
+ state: string;
58
+ token: string;
59
+ /** A viewer's: the debugger (`/debug/*`), `GET /status` and the dashboard's reading routes. */
60
+ readToken: string | null;
61
+ /** The deployed server's health route; without one a server that stays up 5 s counts as started. */
62
+ serverHealthUrl: string | null;
63
+ /** Where a release's `serverTokenEnv` is read from, and what the deployed server starts with. */
64
+ environment: Environment;
65
+ /**
66
+ * How the deployed server reaches this agent: its URL, and the token that lets the server restart
67
+ * the controller, which the server is started with. Without it the server can't.
68
+ */
69
+ serverAccess: { url: string; token: string } | null;
70
+ /** Experimental: downloads without a baseline import their POUs in one PLCopenXML import. */
71
+ bulkImport: boolean;
72
+ log: (message: string) => void;
73
+ /**
74
+ * Ends this process once `POST /agent/exit` has been answered, after the agent has stopped or
75
+ * left the line's server as asked.
76
+ */
77
+ exit: (exit: AgentExit) => void;
78
+ }
79
+
80
+ /** `GET /status`: the selected controller, the deployed release, and the server's and login's state. */
81
+ const statusRoute = (context: {
82
+ state: AgentState;
83
+ server: ServerSupervisor;
84
+ loginStatus: () => Promise<AgentStatus["login"]>;
85
+ }): ApiRoute => ({
86
+ method: "GET",
87
+ pattern: statusPath,
88
+ role: "viewer",
89
+ handle: async () =>
90
+ Response.json({
91
+ target: await context.state.target(),
92
+ release: await context.state.release(),
93
+ server: context.server.status(),
94
+ login: await context.loginStatus(),
95
+ credentialsStored: (await storedCredentials()) !== null,
96
+ } satisfies AgentStatus),
97
+ });
98
+
99
+ /** `POST /releases/compare`: which of a release's buckets the stored releases lack. */
100
+ export const compareRoute = (context: {
101
+ state: AgentState;
102
+ releases: ReleaseStore;
103
+ }): ApiRoute => ({
104
+ method: "POST",
105
+ pattern: "/releases/compare",
106
+ role: "admin",
107
+ handle: async (request) => {
108
+ const { buckets } = compareRequestSchema.parse(await request.json());
109
+ const comparison = await context.releases.compare(
110
+ buckets,
111
+ (await context.state.release())?.id ?? null,
112
+ );
113
+ // The answer lists every stored path in the differing buckets, which compresses tenfold; fetch inflates it.
114
+ return new Response(Bun.gzipSync(JSON.stringify(comparison)), {
115
+ headers: {
116
+ "Content-Type": "application/json",
117
+ "Content-Encoding": "gzip",
118
+ },
119
+ });
120
+ },
121
+ });
122
+
123
+ /** The routes a browser calls: the dashboard's API, and the status it shows too. */
124
+ export const createBrowserRoutes = (
125
+ context: Parameters<typeof statusRoute>[0] &
126
+ Parameters<typeof createDeploymentRoutes>[0] &
127
+ Parameters<typeof createEnvironment>[0] &
128
+ Parameters<typeof createRestartRoutes>[0] & {
129
+ access: { routes: ApiRoute[] };
130
+ },
131
+ ): ApiRoute[] => [
132
+ statusRoute(context),
133
+ ...createDeploymentRoutes(context),
134
+ ...context.access.routes,
135
+ ...createEnvironment(context).routes,
136
+ ...createRestartRoutes(context),
137
+ ...context.audit.routes,
138
+ ];
139
+
140
+ /** Answers a dashboard page, a step of signing in, or the route `destination` finds, as whoever `request` is. */
141
+ export const answerRequest = async (
142
+ request: Request,
143
+ peer: Peer | null,
144
+ context: {
145
+ dashboard: ReturnType<typeof createDashboard>;
146
+ access: ReturnType<typeof createAccess>;
147
+ destination: (request: Request) => Destination | undefined;
148
+ log: (message: string) => void;
149
+ },
150
+ ): Promise<Response> => {
151
+ // The dashboard's pages hold no data; what they show comes from `/api` as whoever is signed in.
152
+ const page = await context.dashboard.handle(request);
153
+ if (page) {
154
+ return page;
155
+ }
156
+ const signing = await context.access.handle(request);
157
+ if (signing) {
158
+ return signing;
159
+ }
160
+ const target = context.destination(request);
161
+ const identity = await context.access.identify(request, peer, {
162
+ // An unknown route is taken as the dashboard's under `/api` and as the CLI's elsewhere.
163
+ browser:
164
+ target?.browser ?? new URL(request.url).pathname.startsWith("/api/"),
165
+ });
166
+ if (identity instanceof Response) {
167
+ return identity;
168
+ }
169
+ return answer(request, target, identity, context.log);
170
+ };
171
+
172
+ /** The debugger's own path for `pathname` under `debuggerMount`, from its leading slash. */
173
+ const debugRoute = (pathname: string) =>
174
+ pathname.slice(debuggerMount.length - 1);
175
+
176
+ /** The plant agent's routes. It runs one deployment or login operation at a time. */
177
+ export const createAgent = async (options: AgentOptions) => {
178
+ const { log } = options;
179
+ const state = await openState(options.state);
180
+ const server = createServerSupervisor({
181
+ healthUrl: options.serverHealthUrl,
182
+ record: state.paths.server,
183
+ output: state.paths.serverLog,
184
+ // The agent's own address and token for the server win over anything a release sets.
185
+ environment: async (executable) => ({
186
+ ...(await serverEnvironment(
187
+ await storedReleaseOf(state.paths.releases, executable),
188
+ options.environment,
189
+ )),
190
+ ...(options.serverAccess && {
191
+ [plantAgentEnv.url]: options.serverAccess.url,
192
+ [plantAgentEnv.token]: options.serverAccess.token,
193
+ }),
194
+ }),
195
+ log,
196
+ });
197
+ const deployed = await state.release();
198
+ if (deployed?.server) {
199
+ await server.resume(
200
+ releaseServerFile(state.paths.releases, deployed.server),
201
+ );
202
+ }
203
+ // Whether deployments can run, said once at start; each deployment and login checks again.
204
+ void describeBuilder().then(log, (error: unknown) =>
205
+ log(`Can't check the CODESYS builder image yet: ${errorMessage(error)}`),
206
+ );
207
+ const operations = createOperations(log);
208
+ const codesys: CodesysSettings = { bulkImport: options.bulkImport };
209
+ const releases = createReleaseStore(state.paths.releases);
210
+ const audit = createAudit({
211
+ file: state.paths.audit,
212
+ onRecord: (entry) => debugging.record(entry),
213
+ });
214
+ const login = createLogin({ state, operations, codesys, audit, log });
215
+ const debugging = createDebugging({
216
+ state,
217
+ readLogin: login.read,
218
+ loginStatus: login.status,
219
+ serverHealthUrl: options.serverHealthUrl,
220
+ environment: options.environment,
221
+ log,
222
+ });
223
+ const deployments = await createDeployments({
224
+ state,
225
+ operations,
226
+ codesys,
227
+ server,
228
+ debugging,
229
+ login,
230
+ now: () => new Date(),
231
+ log,
232
+ });
233
+ const access = createAccess({
234
+ token: options.token,
235
+ readToken: options.readToken,
236
+ serverToken: options.serverAccess?.token ?? null,
237
+ file: state.paths.access,
238
+ whois: createWhois({ run: runCommand, now: Date.now, log }),
239
+ audit,
240
+ now: Date.now,
241
+ log,
242
+ });
243
+ const dashboard = createDashboard();
244
+
245
+ /** Stops the debugger and the supervised server; a login container keeps running for the next agent. */
246
+ const stop = async () => {
247
+ await debugging.close();
248
+ await server.stop();
249
+ };
250
+ /** Stops the debugger and leaves the server running for the agent that replaces this one. */
251
+ const leave = async () => {
252
+ await debugging.close();
253
+ server.leave();
254
+ };
255
+
256
+ const browserRoutes = createBrowserRoutes({
257
+ state,
258
+ server,
259
+ loginStatus: login.status,
260
+ runner: deployments.runner,
261
+ releases,
262
+ access,
263
+ restartController: deployments.restart,
264
+ operations,
265
+ audit,
266
+ log,
267
+ });
268
+
269
+ /** The CLI's routes, which only an admin's token reaches. */
270
+ const cliRoutes: ApiRoute[] = [
271
+ {
272
+ method: "GET",
273
+ pattern: "/interfaces",
274
+ role: "admin",
275
+ handle: async () => Response.json(networkInterfaces()),
276
+ },
277
+ {
278
+ method: "POST",
279
+ pattern: "/discover",
280
+ role: "admin",
281
+ handle: async (request) => {
282
+ const { name } = discoverSchema.parse(await request.json());
283
+ const selected = networkInterfaces().find(
284
+ (network) => network.name === name,
285
+ );
286
+ if (!selected) {
287
+ throw new AgentError(`No IPv4 interface named ${name}`, 404);
288
+ }
289
+ return Response.json(await discoverControllers(selected, runtimePort));
290
+ },
291
+ },
292
+ {
293
+ method: "PUT",
294
+ pattern: "/target",
295
+ role: "admin",
296
+ handle: async (request) => {
297
+ const target = targetSchema.parse(await request.json());
298
+ await state.setTarget(target);
299
+ return Response.json(target);
300
+ },
301
+ },
302
+ {
303
+ method: "GET",
304
+ pattern: "/variables",
305
+ role: "admin",
306
+ handle: async () =>
307
+ Response.json((await state.requireRelease()).manifest.variables),
308
+ },
309
+ compareRoute({ state, releases }),
310
+ {
311
+ method: "POST",
312
+ pattern: "/deploy",
313
+ role: "admin",
314
+ handle: async (request, { identity }) =>
315
+ deployments.deploy(
316
+ () => readDeployRequest(releases, request),
317
+ identity,
318
+ clientIdentity(request),
319
+ clientRelease(request),
320
+ ),
321
+ },
322
+ {
323
+ method: "POST",
324
+ pattern: "/login",
325
+ role: "admin",
326
+ handle: async (request) =>
327
+ login.open(
328
+ controllerCredentialsSchema.nullable().parse(await request.json()),
329
+ ),
330
+ },
331
+ {
332
+ method: "POST",
333
+ pattern: "/login/command",
334
+ role: "admin",
335
+ handle: async (request) =>
336
+ Response.json(
337
+ await login.command(
338
+ loginCommandSchema.parse(await request.json()),
339
+ clientIdentity(request),
340
+ ),
341
+ ),
342
+ },
343
+ {
344
+ method: "DELETE",
345
+ pattern: "/login",
346
+ role: "admin",
347
+ handle: async () => Response.json(await login.logout()),
348
+ },
349
+ {
350
+ method: "POST",
351
+ pattern: agentHoldPath,
352
+ role: "admin",
353
+ handle: async () => {
354
+ operations.hold();
355
+ try {
356
+ // A login's container outlives the agent and runs the code it started with.
357
+ if (await login.isOpen()) {
358
+ throw new AgentError(
359
+ "A login is open; log out before upgrading the agent: tsplc logout",
360
+ 409,
361
+ );
362
+ }
363
+ await deployments.retire();
364
+ } catch (error) {
365
+ operations.release();
366
+ throw error;
367
+ }
368
+ return Response.json({ held: true });
369
+ },
370
+ },
371
+ {
372
+ method: "DELETE",
373
+ pattern: agentHoldPath,
374
+ role: "admin",
375
+ handle: async () => {
376
+ operations.release();
377
+ return Response.json({ held: false });
378
+ },
379
+ },
380
+ {
381
+ method: "POST",
382
+ pattern: agentExitPath,
383
+ role: "admin",
384
+ handle: async (request) => {
385
+ const exit = exitSchema.parse(await request.json());
386
+ if (!operations.held()) {
387
+ throw new AgentError(
388
+ "Hold the agent before it exits, so no operation is cut short",
389
+ 409,
390
+ );
391
+ }
392
+ // Answered first: the caller waits for this process to end.
393
+ setTimeout(() => {
394
+ void (exit.server === "leave" ? leave() : stop()).then(() =>
395
+ options.exit(exit),
396
+ );
397
+ }, 100);
398
+ return Response.json({ exiting: true });
399
+ },
400
+ },
401
+ ];
402
+
403
+ const destination = (request: Request): Destination | undefined => {
404
+ const { pathname } = new URL(request.url);
405
+ if (pathname.startsWith(debuggerMount)) {
406
+ return {
407
+ browser: true,
408
+ role: "viewer",
409
+ handle: () => debugging.handle(request, debugRoute(pathname)),
410
+ };
411
+ }
412
+ return (
413
+ routeDestination(request, { routes: browserRoutes, browser: true }) ??
414
+ routeDestination(request, { routes: cliRoutes, browser: false })
415
+ );
416
+ };
417
+
418
+ const respond = async (
419
+ request: Request,
420
+ peer: Peer | null,
421
+ ): Promise<Response> => {
422
+ const { pathname, search } = new URL(request.url);
423
+ // The UI's relative links need the trailing slash.
424
+ if (pathname === debuggerMount.slice(0, -1)) {
425
+ return new Response(null, {
426
+ status: 308,
427
+ headers: { Location: `${debuggerMount}${search}` },
428
+ });
429
+ }
430
+ // The page and its script hold no data, and a browser loads the script without the token.
431
+ if (
432
+ request.method === "GET" &&
433
+ (pathname === debuggerMount || pathname === `${debuggerMount}ui.js`)
434
+ ) {
435
+ return debugging.handle(request, debugRoute(pathname));
436
+ }
437
+ return answerRequest(request, peer, {
438
+ dashboard,
439
+ access,
440
+ destination,
441
+ log,
442
+ });
443
+ };
444
+
445
+ return {
446
+ /** Answers `request`, naming the agent's tsPLC version so a client can refuse a mismatched agent. */
447
+ fetch: async (request: Request, peer: Peer | null = null) => {
448
+ const response = await respond(request, peer);
449
+ // A proxied debugger response's headers are immutable.
450
+ const headers = new Headers(response.headers);
451
+ headers.set(agentVersionHeader, tsplcVersion);
452
+ return new Response(response.body, {
453
+ status: response.status,
454
+ statusText: response.statusText,
455
+ headers,
456
+ });
457
+ },
458
+ stop,
459
+ leave,
460
+ };
461
+ };
package/src/audit.ts ADDED
@@ -0,0 +1,74 @@
1
+ import { z } from "zod";
2
+ import { appendJsonl, readJsonl } from "./logs";
3
+ import { type Audit, auditSchema, type Identity } from "./protocol";
4
+ import type { ApiRoute } from "./routes";
5
+
6
+ /** How many entries `GET /api/audit` answers without `?limit=`, and at most. */
7
+ export const auditLimits = { default: 100, max: 1000 } as const;
8
+
9
+ const auditQuerySchema = z.object({
10
+ limit: z.coerce
11
+ .number()
12
+ .int()
13
+ .positive()
14
+ .max(auditLimits.max)
15
+ .default(auditLimits.default),
16
+ });
17
+
18
+ /**
19
+ * Who an entry names: a dashboard user by their login or name, or, for a login command, the user
20
+ * and host its client reports and the release it ran against.
21
+ */
22
+ type Author = Pick<Audit, "user" | "host" | "release">;
23
+
24
+ /** How the audit log names whoever a request identifies. */
25
+ export const authorOf = (identity: Identity): Author => ({
26
+ user: identity.login ?? identity.name,
27
+ });
28
+
29
+ /**
30
+ * The agent's `audit.jsonl`: login commands that changed the controller, and the dashboard's
31
+ * changes to access, the environment and the server, by who made them.
32
+ */
33
+ export const createAudit = (context: {
34
+ file: string;
35
+ onRecord: (entry: Audit) => Promise<void>;
36
+ }) => {
37
+ const record = async (change: {
38
+ by: Author;
39
+ /** What was done, such as `environment set API_TOKEN`. */
40
+ command: string;
41
+ values: Audit["values"];
42
+ previous: Audit["previous"] | null;
43
+ error: string | null;
44
+ }) => {
45
+ const entry: Audit = {
46
+ at: new Date().toISOString(),
47
+ command: change.command,
48
+ values: change.values,
49
+ ...(change.previous && { previous: change.previous }),
50
+ ...change.by,
51
+ ...(change.error !== null && { error: change.error }),
52
+ };
53
+ await appendJsonl(context.file, entry);
54
+ await context.onRecord(entry);
55
+ };
56
+
57
+ const routes: ApiRoute[] = [
58
+ {
59
+ method: "GET",
60
+ pattern: "/api/audit",
61
+ role: "viewer",
62
+ handle: async (request) => {
63
+ const { limit } = auditQuerySchema.parse(
64
+ Object.fromEntries(new URL(request.url).searchParams),
65
+ );
66
+ return Response.json(
67
+ (await readJsonl(context.file, auditSchema, limit)).reverse(),
68
+ );
69
+ },
70
+ },
71
+ ];
72
+ return { record, routes };
73
+ };
74
+ export type AuditLog = ReturnType<typeof createAudit>;