@tsplc/agent 0.2.14 → 0.2.17
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +292 -29
- package/dist/cli.js.map +7 -6
- package/dist/client.js +29 -4
- package/dist/client.js.map +4 -4
- package/dist/index.js +292 -28
- package/dist/index.js.map +6 -5
- package/package.json +4 -3
- package/src/agent.ts +267 -17
- package/src/cli.ts +9 -1
- package/src/client.ts +7 -2
- package/src/logs.ts +39 -0
- package/src/protocol.ts +39 -0
package/src/agent.ts
CHANGED
|
@@ -6,29 +6,47 @@ import { join } from "node:path";
|
|
|
6
6
|
import { setTimeout as delay } from "node:timers/promises";
|
|
7
7
|
import { promisify } from "node:util";
|
|
8
8
|
import {
|
|
9
|
+
type ControllerLogin,
|
|
9
10
|
explicitDownload,
|
|
10
11
|
failureReason,
|
|
11
12
|
findControllerLogin,
|
|
12
13
|
gatewayImage,
|
|
14
|
+
type LoginCommand,
|
|
13
15
|
loginCommandSchema,
|
|
14
16
|
openControllerLogin,
|
|
15
17
|
resolveConfig,
|
|
16
18
|
startWarmController,
|
|
17
19
|
updateWarmController,
|
|
18
20
|
} from "@tsplc/build";
|
|
21
|
+
import {
|
|
22
|
+
createDebugger,
|
|
23
|
+
createDebugHandler,
|
|
24
|
+
createLoginAdapter,
|
|
25
|
+
type Debugger,
|
|
26
|
+
loadManifest,
|
|
27
|
+
LoginUnavailable,
|
|
28
|
+
noLogin,
|
|
29
|
+
timelineEntries,
|
|
30
|
+
} from "@tsplc/debug";
|
|
19
31
|
import { z } from "zod";
|
|
20
32
|
import { discoverControllers, networkInterfaces } from "./discovery";
|
|
21
33
|
import {
|
|
22
34
|
type AgentEvent,
|
|
23
35
|
type AgentStatus,
|
|
36
|
+
type Audit,
|
|
37
|
+
auditSchema,
|
|
38
|
+
clientHeaders,
|
|
24
39
|
type Credentials,
|
|
25
40
|
credentialsSchema,
|
|
41
|
+
type Deployment,
|
|
42
|
+
deploymentSchema,
|
|
26
43
|
deployOptionsSchema,
|
|
27
44
|
type Release,
|
|
28
45
|
releaseSchema,
|
|
29
46
|
type Target,
|
|
30
47
|
targetSchema,
|
|
31
48
|
} from "./protocol";
|
|
49
|
+
import { appendJsonl, readJsonl } from "./logs";
|
|
32
50
|
import { loadRelease, readUpload, saveRelease } from "./releases";
|
|
33
51
|
import { createServerSupervisor } from "./server-process";
|
|
34
52
|
|
|
@@ -64,6 +82,49 @@ class AgentError extends Error {
|
|
|
64
82
|
|
|
65
83
|
const json = (body: unknown, status = 200) => Response.json(body, { status });
|
|
66
84
|
|
|
85
|
+
const message = (error: unknown) => (error instanceof Error ? error.message : String(error));
|
|
86
|
+
|
|
87
|
+
/** A login's state comes back within a second; one that takes this long waits on a hung worker. */
|
|
88
|
+
const loginStateTimeout = 30_000;
|
|
89
|
+
const stoppedAnswering = { error: "The login stopped answering" };
|
|
90
|
+
|
|
91
|
+
/** Log entries a new debugger starts its timeline with. */
|
|
92
|
+
const recentEntries = 500;
|
|
93
|
+
|
|
94
|
+
/** Who sent a request, as the client reports it. */
|
|
95
|
+
const clientOf = (request: Request) => {
|
|
96
|
+
const header = (name: string) => request.headers.get(name)?.slice(0, 200) || undefined;
|
|
97
|
+
return { user: header(clientHeaders.user), host: header(clientHeaders.host) };
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
/** How an audited login command reads in the log, or nothing for commands that only read. */
|
|
101
|
+
const auditOf = (command: LoginCommand) => {
|
|
102
|
+
switch (command.command) {
|
|
103
|
+
case "write":
|
|
104
|
+
case "force":
|
|
105
|
+
return { command: command.command, values: command.values };
|
|
106
|
+
case "unforce":
|
|
107
|
+
return {
|
|
108
|
+
command: command.restore ? "unforce --restore" : "unforce",
|
|
109
|
+
values: Object.fromEntries(command.expressions.map((expression) => [expression, ""])),
|
|
110
|
+
};
|
|
111
|
+
case "start":
|
|
112
|
+
case "stop":
|
|
113
|
+
return { command: command.command, values: {} };
|
|
114
|
+
case "reset":
|
|
115
|
+
return { command: `reset ${command.kind.toLowerCase()}`, values: {} };
|
|
116
|
+
case "state":
|
|
117
|
+
case "read":
|
|
118
|
+
return undefined;
|
|
119
|
+
}
|
|
120
|
+
};
|
|
121
|
+
|
|
122
|
+
const matches = (presented: string, token: string) => {
|
|
123
|
+
const actual = Buffer.from(presented);
|
|
124
|
+
const expected = Buffer.from(token);
|
|
125
|
+
return actual.length === expected.length && timingSafeEqual(actual, expected);
|
|
126
|
+
};
|
|
127
|
+
|
|
67
128
|
const readJson = async <T>(path: string, schema: z.ZodType<T>) =>
|
|
68
129
|
existsSync(path) ? schema.parse(JSON.parse(await readFile(path, "utf8"))) : null;
|
|
69
130
|
|
|
@@ -150,6 +211,8 @@ export interface AgentOptions {
|
|
|
150
211
|
/** Releases, the controller's download baseline and the selected target live here. */
|
|
151
212
|
state: string;
|
|
152
213
|
token: string;
|
|
214
|
+
/** Accepted only for the debugger (`/debug/*`) and `GET /status`. */
|
|
215
|
+
readToken?: string;
|
|
153
216
|
/** The deployed server's health route; without it a server that stays up 5 s counts as started. */
|
|
154
217
|
serverHealthUrl?: string;
|
|
155
218
|
log: (message: string) => void;
|
|
@@ -162,6 +225,9 @@ export const createAgent = async (options: AgentOptions) => {
|
|
|
162
225
|
controller: join(options.state, "controller"),
|
|
163
226
|
release: join(options.state, "release.json"),
|
|
164
227
|
target: join(options.state, "target.json"),
|
|
228
|
+
deployments: join(options.state, "deployments.jsonl"),
|
|
229
|
+
audit: join(options.state, "audit.jsonl"),
|
|
230
|
+
debug: join(options.state, "debug"),
|
|
165
231
|
};
|
|
166
232
|
await mkdir(options.state, { recursive: true });
|
|
167
233
|
const server = createServerSupervisor({ healthUrl: options.serverHealthUrl, log: options.log });
|
|
@@ -207,6 +273,88 @@ export const createAgent = async (options: AgentOptions) => {
|
|
|
207
273
|
);
|
|
208
274
|
});
|
|
209
275
|
|
|
276
|
+
/** Login commands, the debugger's reads among them, run one at a time. */
|
|
277
|
+
let loginGeneration = 0;
|
|
278
|
+
let commands: Promise<unknown> = Promise.resolve();
|
|
279
|
+
const enqueue = <Result>(run: () => Promise<Result>) => {
|
|
280
|
+
const generation = loginGeneration;
|
|
281
|
+
const sent = commands.then(() => {
|
|
282
|
+
if (generation !== loginGeneration) throw new AgentError("The login was closed", 409);
|
|
283
|
+
return run();
|
|
284
|
+
});
|
|
285
|
+
commands = sent.catch(() => undefined);
|
|
286
|
+
return sent;
|
|
287
|
+
};
|
|
288
|
+
const send = (login: ControllerLogin, loginCommand: LoginCommand) =>
|
|
289
|
+
enqueue(() => login.send(loginCommand));
|
|
290
|
+
|
|
291
|
+
/** What the debugger reads through: the open login, which it never opens itself. */
|
|
292
|
+
const readLogin = async ([first, ...rest]: string[]) => {
|
|
293
|
+
if (busy === "a login")
|
|
294
|
+
throw new LoginUnavailable("The engineering login is opening", { state: "connecting" });
|
|
295
|
+
if (busy) throw new LoginUnavailable(`Live values pause during ${busy}`);
|
|
296
|
+
const login = await findControllerLogin(loginContainer);
|
|
297
|
+
if (!login) throw new LoginUnavailable(noLogin);
|
|
298
|
+
if (!first) return {};
|
|
299
|
+
const result = await send(login, { command: "read", expressions: [first, ...rest] });
|
|
300
|
+
if (!("values" in result)) throw new Error("The login answered a read without values");
|
|
301
|
+
return result.values;
|
|
302
|
+
};
|
|
303
|
+
|
|
304
|
+
/**
|
|
305
|
+
* The deployed release's debugger, when it has a debug manifest. It reads the controller
|
|
306
|
+
* through the agent's engineering login, and the server's telemetry and requests through the
|
|
307
|
+
* server's health origin.
|
|
308
|
+
*/
|
|
309
|
+
const startDebugger = async () => {
|
|
310
|
+
const release = await readJson(paths.release, releaseSchema);
|
|
311
|
+
if (!release) return null;
|
|
312
|
+
const { directory, manifest: releaseManifest } = await loadRelease(paths.releases, release.id);
|
|
313
|
+
const manifestFile = join(directory, "debug.json");
|
|
314
|
+
if (!existsSync(manifestFile)) return null;
|
|
315
|
+
const manifest = await loadManifest(manifestFile);
|
|
316
|
+
const serverToken =
|
|
317
|
+
releaseManifest.serverTokenEnv && process.env[releaseManifest.serverTokenEnv];
|
|
318
|
+
const debug = await createDebugger({
|
|
319
|
+
manifest,
|
|
320
|
+
adapter: createLoginAdapter({
|
|
321
|
+
read: readLogin,
|
|
322
|
+
probe: manifest.build.target,
|
|
323
|
+
endpoint: "the agent's login",
|
|
324
|
+
}),
|
|
325
|
+
stateDirectory: paths.debug,
|
|
326
|
+
watch: releaseManifest.debug?.watch ?? {},
|
|
327
|
+
...(options.serverHealthUrl &&
|
|
328
|
+
serverToken && {
|
|
329
|
+
server: { url: new URL(options.serverHealthUrl).origin, token: serverToken },
|
|
330
|
+
}),
|
|
331
|
+
release: { id: release.id, deployedAt: release.deployedAt, operation: release.operation },
|
|
332
|
+
timeline: [
|
|
333
|
+
...(await readJsonl(paths.deployments, deploymentSchema, recentEntries)).map(
|
|
334
|
+
({ at, ...deployment }) => timelineEntries.deploy(at, deployment),
|
|
335
|
+
),
|
|
336
|
+
...(await readJsonl(paths.audit, auditSchema, recentEntries)).map(({ at, ...audit }) =>
|
|
337
|
+
timelineEntries.audit(at, audit),
|
|
338
|
+
),
|
|
339
|
+
],
|
|
340
|
+
log: options.log,
|
|
341
|
+
});
|
|
342
|
+
return { debug, handle: createDebugHandler(debug, options.log) };
|
|
343
|
+
};
|
|
344
|
+
type Debugging = { debug: Debugger; handle: ReturnType<typeof createDebugHandler> } | null;
|
|
345
|
+
const debuggerFailed = (error: unknown): Debugging => {
|
|
346
|
+
options.log(`Starting the debugger failed: ${message(error)}`);
|
|
347
|
+
return null;
|
|
348
|
+
};
|
|
349
|
+
let debugging: Promise<Debugging> = startDebugger().catch(debuggerFailed);
|
|
350
|
+
/** Replaces the debugger after the release changes. */
|
|
351
|
+
const restartDebugger = () => {
|
|
352
|
+
debugging = debugging.then(async (current) => {
|
|
353
|
+
await current?.debug.close();
|
|
354
|
+
return startDebugger().catch(debuggerFailed);
|
|
355
|
+
});
|
|
356
|
+
};
|
|
357
|
+
|
|
210
358
|
/** Streams one exclusive operation's events, then its result, as newline-delimited JSON. */
|
|
211
359
|
const operation = (
|
|
212
360
|
name: string,
|
|
@@ -251,7 +399,7 @@ export const createAgent = async (options: AgentOptions) => {
|
|
|
251
399
|
);
|
|
252
400
|
};
|
|
253
401
|
|
|
254
|
-
const deploy = async (form: FormData) => {
|
|
402
|
+
const deploy = async (form: FormData, client: ReturnType<typeof clientOf>) => {
|
|
255
403
|
const settings = deployOptionsSchema.parse(JSON.parse(z.string().parse(form.get("options"))));
|
|
256
404
|
const upload = await readUpload(form);
|
|
257
405
|
const target = await requireTarget();
|
|
@@ -304,6 +452,16 @@ export const createAgent = async (options: AgentOptions) => {
|
|
|
304
452
|
server: serverPath ?? previous?.server,
|
|
305
453
|
};
|
|
306
454
|
await writeFile(paths.release, JSON.stringify(deployedRelease, null, 2));
|
|
455
|
+
const debugManifest = join(release.directory, "debug.json");
|
|
456
|
+
const deployment: Deployment = {
|
|
457
|
+
at: deployedRelease.deployedAt,
|
|
458
|
+
release: release.id,
|
|
459
|
+
...(existsSync(debugManifest) && { build: (await loadManifest(debugManifest)).build.id }),
|
|
460
|
+
operation: kind,
|
|
461
|
+
...client,
|
|
462
|
+
};
|
|
463
|
+
await appendJsonl(paths.deployments, deployment);
|
|
464
|
+
restartDebugger();
|
|
307
465
|
return deployedRelease;
|
|
308
466
|
});
|
|
309
467
|
};
|
|
@@ -319,25 +477,76 @@ export const createAgent = async (options: AgentOptions) => {
|
|
|
319
477
|
const login = await withCredentials(credentials, () =>
|
|
320
478
|
openControllerLogin(config, loginContainer),
|
|
321
479
|
);
|
|
322
|
-
return
|
|
480
|
+
return send(login, { command: "state" });
|
|
323
481
|
});
|
|
324
482
|
};
|
|
325
483
|
|
|
326
484
|
const requireLogin = async () => {
|
|
485
|
+
if (busy) throw new AgentError(`The agent is busy with ${busy}`, 409);
|
|
486
|
+
const generation = loginGeneration;
|
|
327
487
|
const login = await findControllerLogin(loginContainer);
|
|
488
|
+
if (generation !== loginGeneration) throw new AgentError("The login was closed", 409);
|
|
489
|
+
if (busy) throw new AgentError(`The agent is busy with ${busy}`, 409);
|
|
328
490
|
if (!login) throw new AgentError("No login is open: tsplc login", 409);
|
|
329
491
|
return login;
|
|
330
492
|
};
|
|
331
493
|
|
|
494
|
+
/** Runs a login command; one that changes the controller goes to the audit log, with the values it replaces. */
|
|
495
|
+
const command = async (loginCommand: LoginCommand, client: ReturnType<typeof clientOf>) => {
|
|
496
|
+
const login = await requireLogin();
|
|
497
|
+
const change = auditOf(loginCommand);
|
|
498
|
+
if (!change) return send(login, loginCommand);
|
|
499
|
+
return enqueue(async () => {
|
|
500
|
+
const [first, ...rest] = Object.keys(change.values);
|
|
501
|
+
// Without the old values the command is still worth running and recording.
|
|
502
|
+
const previous = first
|
|
503
|
+
? await login
|
|
504
|
+
.send({ command: "read", expressions: [first, ...rest] })
|
|
505
|
+
.then((result) => ("values" in result ? result.values : undefined))
|
|
506
|
+
.catch(() => undefined)
|
|
507
|
+
: undefined;
|
|
508
|
+
const audit = async (error?: unknown) => {
|
|
509
|
+
const entry: Audit = {
|
|
510
|
+
at: new Date().toISOString(),
|
|
511
|
+
...change,
|
|
512
|
+
...(previous && { previous }),
|
|
513
|
+
...client,
|
|
514
|
+
release: (await readJson(paths.release, releaseSchema))?.id,
|
|
515
|
+
...(error !== undefined && { error: message(error) }),
|
|
516
|
+
};
|
|
517
|
+
await appendJsonl(paths.audit, entry);
|
|
518
|
+
const { at, ...details } = entry;
|
|
519
|
+
(await debugging)?.debug.record(timelineEntries.audit(at, details));
|
|
520
|
+
};
|
|
521
|
+
try {
|
|
522
|
+
const result = await login.send(loginCommand);
|
|
523
|
+
await audit();
|
|
524
|
+
return result;
|
|
525
|
+
} catch (error) {
|
|
526
|
+
await audit(error);
|
|
527
|
+
throw error;
|
|
528
|
+
}
|
|
529
|
+
});
|
|
530
|
+
};
|
|
531
|
+
|
|
532
|
+
/**
|
|
533
|
+
* The open login's state. A login that lost the controller, or whose worker died or hangs, is
|
|
534
|
+
* reported as failed, so the CLI can log it out and open a new one.
|
|
535
|
+
*/
|
|
332
536
|
const loginStatus = async (): Promise<AgentStatus["login"]> => {
|
|
333
537
|
const login = await findControllerLogin(loginContainer);
|
|
334
|
-
|
|
335
|
-
if (!
|
|
538
|
+
if (!login) return null;
|
|
539
|
+
if (!(await login.ready()))
|
|
540
|
+
// A login still opening has its container but doesn't answer yet.
|
|
541
|
+
return busy === "a login" ? null : stoppedAnswering;
|
|
336
542
|
try {
|
|
337
|
-
const state = await
|
|
543
|
+
const state = await Promise.race([
|
|
544
|
+
send(login, { command: "state" }),
|
|
545
|
+
delay(loginStateTimeout, null),
|
|
546
|
+
]);
|
|
547
|
+
if (!state) return stoppedAnswering;
|
|
338
548
|
return "state" in state ? state : null;
|
|
339
549
|
} catch (error) {
|
|
340
|
-
// A login that lost the controller fails every command; reporting it keeps logout reachable.
|
|
341
550
|
return { error: failureReason(error) };
|
|
342
551
|
}
|
|
343
552
|
};
|
|
@@ -371,28 +580,66 @@ export const createAgent = async (options: AgentOptions) => {
|
|
|
371
580
|
case "GET /variables":
|
|
372
581
|
return json((await currentRelease()).manifest.variables);
|
|
373
582
|
case "POST /deploy":
|
|
374
|
-
return deploy(await request.formData());
|
|
583
|
+
return deploy(await request.formData(), clientOf(request));
|
|
375
584
|
case "POST /login":
|
|
376
585
|
return openLogin(credentialsSchema.parse(await request.json()));
|
|
377
586
|
case "POST /login/command":
|
|
378
587
|
return json(
|
|
379
|
-
await (
|
|
588
|
+
await command(loginCommandSchema.parse(await request.json()), clientOf(request)),
|
|
380
589
|
);
|
|
381
|
-
case "DELETE /login":
|
|
382
|
-
|
|
383
|
-
|
|
590
|
+
case "DELETE /login": {
|
|
591
|
+
const login = await requireLogin();
|
|
592
|
+
busy = "a logout";
|
|
593
|
+
loginGeneration++;
|
|
594
|
+
try {
|
|
595
|
+
const failure = await login.close();
|
|
596
|
+
commands = Promise.resolve();
|
|
597
|
+
if (failure)
|
|
598
|
+
options.log(`The login couldn't log out (${failure}); its container was removed`);
|
|
599
|
+
return json(failure ? { failure } : {});
|
|
600
|
+
} finally {
|
|
601
|
+
busy = undefined;
|
|
602
|
+
}
|
|
603
|
+
}
|
|
384
604
|
default:
|
|
385
605
|
return json({ error: `No route ${key}` }, 404);
|
|
386
606
|
}
|
|
387
607
|
};
|
|
388
608
|
|
|
389
|
-
|
|
609
|
+
/** The debugger's UI and API under `/debug`. */
|
|
610
|
+
const debugRoute = async (request: Request, route: string) => {
|
|
611
|
+
const current = await debugging;
|
|
612
|
+
if (!current)
|
|
613
|
+
return json(
|
|
614
|
+
{ error: "The deployed release has no debug manifest, or the debugger failed to start" },
|
|
615
|
+
503,
|
|
616
|
+
);
|
|
617
|
+
return current.handle(request, route);
|
|
618
|
+
};
|
|
619
|
+
|
|
390
620
|
return {
|
|
391
621
|
fetch: async (request: Request) => {
|
|
392
|
-
const
|
|
393
|
-
|
|
394
|
-
|
|
622
|
+
const { pathname, search, searchParams } = new URL(request.url);
|
|
623
|
+
const debugPath = pathname.startsWith("/debug/");
|
|
624
|
+
// The UI's relative links need the trailing slash.
|
|
625
|
+
if (pathname === "/debug")
|
|
626
|
+
return new Response(null, { status: 308, headers: { Location: `/debug/${search}` } });
|
|
627
|
+
// The page and its script hold no data, and a browser loads the script without the token.
|
|
628
|
+
if (request.method === "GET" && (pathname === "/debug/" || pathname === "/debug/ui.js"))
|
|
629
|
+
return debugRoute(request, pathname.slice("/debug".length));
|
|
630
|
+
// EventSource can't send headers, so the debugger also takes `?token=`.
|
|
631
|
+
const presented =
|
|
632
|
+
/^Bearer (.+)$/.exec(request.headers.get("authorization") ?? "")?.[1] ??
|
|
633
|
+
(debugPath ? searchParams.get("token") : null) ??
|
|
634
|
+
"";
|
|
635
|
+
const full = matches(presented, options.token);
|
|
636
|
+
const read =
|
|
637
|
+
options.readToken !== undefined &&
|
|
638
|
+
matches(presented, options.readToken) &&
|
|
639
|
+
(debugPath || (request.method === "GET" && pathname === "/status"));
|
|
640
|
+
if (!full && !read) return json({ error: "Unauthorized" }, 401);
|
|
395
641
|
try {
|
|
642
|
+
if (debugPath) return await debugRoute(request, pathname.slice("/debug".length));
|
|
396
643
|
return await route(request);
|
|
397
644
|
} catch (error) {
|
|
398
645
|
if (error instanceof AgentError) return json({ error: error.message }, error.status);
|
|
@@ -403,7 +650,10 @@ export const createAgent = async (options: AgentOptions) => {
|
|
|
403
650
|
return json({ error: error instanceof Error ? error.message : String(error) }, 500);
|
|
404
651
|
}
|
|
405
652
|
},
|
|
406
|
-
/** Stops the supervised server; a login container keeps running for the next agent. */
|
|
407
|
-
stop: () =>
|
|
653
|
+
/** Stops the debugger and the supervised server; a login container keeps running for the next agent. */
|
|
654
|
+
stop: async () => {
|
|
655
|
+
await (await debugging)?.debug.close();
|
|
656
|
+
await server.stop();
|
|
657
|
+
},
|
|
408
658
|
};
|
|
409
659
|
};
|
package/src/cli.ts
CHANGED
|
@@ -11,7 +11,8 @@ const usage = `tsplc-agent setup|serve [--listen host:port] [--state directory]
|
|
|
11
11
|
setup Builds the CODESYS builder and gateway images. Run it once, and after updating tsPLC.
|
|
12
12
|
serve Serves deployments and logins. --listen is required: use the machine's Tailscale
|
|
13
13
|
address, such as 100.101.102.103:4850. TSPLC_AGENT_TOKEN must hold a shared secret of
|
|
14
|
-
at least 32 characters, such as one from \`openssl rand -hex 32
|
|
14
|
+
at least 32 characters, such as one from \`openssl rand -hex 32\`. An optional
|
|
15
|
+
TSPLC_AGENT_READ_TOKEN, as long, only opens the debugger at /debug and GET /status.`;
|
|
15
16
|
|
|
16
17
|
const { values, positionals } = parseArgs({
|
|
17
18
|
allowPositionals: true,
|
|
@@ -38,9 +39,16 @@ if (command === "setup") {
|
|
|
38
39
|
.string({ error: "Set TSPLC_AGENT_TOKEN" })
|
|
39
40
|
.min(32, "TSPLC_AGENT_TOKEN must be at least 32 characters")
|
|
40
41
|
.parse(process.env["TSPLC_AGENT_TOKEN"]);
|
|
42
|
+
const readToken = z
|
|
43
|
+
.string()
|
|
44
|
+
.min(32, "TSPLC_AGENT_READ_TOKEN must be at least 32 characters")
|
|
45
|
+
.refine((value) => value !== token, "TSPLC_AGENT_READ_TOKEN must differ from TSPLC_AGENT_TOKEN")
|
|
46
|
+
.optional()
|
|
47
|
+
.parse(process.env["TSPLC_AGENT_READ_TOKEN"]);
|
|
41
48
|
const agent = await createAgent({
|
|
42
49
|
state: values.state ?? join(homedir(), ".tsplc-agent"),
|
|
43
50
|
token,
|
|
51
|
+
readToken,
|
|
44
52
|
serverHealthUrl: values["server-health"],
|
|
45
53
|
log: (message) => console.log(`${new Date().toISOString()} ${message}`),
|
|
46
54
|
});
|
package/src/client.ts
CHANGED
|
@@ -1,11 +1,14 @@
|
|
|
1
|
+
import { hostname, userInfo } from "node:os";
|
|
1
2
|
import { type LoginCommand, loginResultSchema } from "@tsplc/build";
|
|
2
3
|
import { z } from "zod";
|
|
3
4
|
import {
|
|
4
5
|
type AgentEvent,
|
|
6
|
+
clientHeaders,
|
|
5
7
|
controllerSchema,
|
|
6
8
|
type Credentials,
|
|
7
9
|
type DeployOptions,
|
|
8
10
|
eventSchema,
|
|
11
|
+
logoutSchema,
|
|
9
12
|
networkInterfaceSchema,
|
|
10
13
|
type ReleaseManifest,
|
|
11
14
|
releaseSchema,
|
|
@@ -34,10 +37,12 @@ export interface ReleaseFile {
|
|
|
34
37
|
|
|
35
38
|
/** Talks to a plant agent at `url`, such as its Tailscale name and port. */
|
|
36
39
|
export const createAgentClient = (options: { url: string; token: string }) => {
|
|
40
|
+
// The agent records who deployed and who changed the controller.
|
|
41
|
+
const identity = { [clientHeaders.user]: userInfo().username, [clientHeaders.host]: hostname() };
|
|
37
42
|
const call = async (path: string, init: RequestInit = {}) => {
|
|
38
43
|
const response = await fetch(new URL(path, options.url), {
|
|
39
44
|
...init,
|
|
40
|
-
headers: { ...init.headers, Authorization: `Bearer ${options.token}` },
|
|
45
|
+
headers: { ...init.headers, ...identity, Authorization: `Bearer ${options.token}` },
|
|
41
46
|
}).catch((cause: unknown) => {
|
|
42
47
|
throw new Error(`Cannot reach the plant agent at ${options.url}`, { cause });
|
|
43
48
|
});
|
|
@@ -121,7 +126,7 @@ export const createAgentClient = (options: { url: string; token: string }) => {
|
|
|
121
126
|
),
|
|
122
127
|
),
|
|
123
128
|
command: (command: LoginCommand) => send("POST", "/login/command", command, loginResultSchema),
|
|
124
|
-
logout: () => send("DELETE", "/login", undefined,
|
|
129
|
+
logout: () => send("DELETE", "/login", undefined, logoutSchema),
|
|
125
130
|
};
|
|
126
131
|
};
|
|
127
132
|
export type AgentClient = ReturnType<typeof createAgentClient>;
|
package/src/logs.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { open, readFile, rename, stat } from "node:fs/promises";
|
|
3
|
+
import type { z } from "zod";
|
|
4
|
+
|
|
5
|
+
/** A log rotates to `<file>.1`, replacing the one before, once it reaches this size. */
|
|
6
|
+
const rotateBytes = 5 * 2 ** 20;
|
|
7
|
+
|
|
8
|
+
/** Appends one JSON line to an append-only log, keeping it and its rotated copy bounded. */
|
|
9
|
+
export const appendJsonl = async (file: string, value: unknown) => {
|
|
10
|
+
if (existsSync(file) && (await stat(file)).size >= rotateBytes) await rename(file, `${file}.1`);
|
|
11
|
+
const log = await open(file, "a+");
|
|
12
|
+
try {
|
|
13
|
+
const { size } = await log.stat();
|
|
14
|
+
const last = Buffer.alloc(1);
|
|
15
|
+
if (size) await log.read(last, 0, 1, size - 1);
|
|
16
|
+
// A crash may leave a partial line; keep the next complete entry separate from it.
|
|
17
|
+
const separator = size && last[0] !== 10 ? "\n" : "";
|
|
18
|
+
await log.writeFile(`${separator}${JSON.stringify(value)}\n`);
|
|
19
|
+
} finally {
|
|
20
|
+
await log.close();
|
|
21
|
+
}
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
/** The newest `limit` lines of a log, oldest first. */
|
|
25
|
+
export const readJsonl = async <T>(file: string, schema: z.ZodType<T>, limit: number) => {
|
|
26
|
+
if (!existsSync(file)) return [];
|
|
27
|
+
return (await readFile(file, "utf8"))
|
|
28
|
+
.split("\n")
|
|
29
|
+
.filter(Boolean)
|
|
30
|
+
.slice(-limit)
|
|
31
|
+
.flatMap((line) => {
|
|
32
|
+
// A crash can leave the last line half written; it is skipped.
|
|
33
|
+
try {
|
|
34
|
+
return [schema.parse(JSON.parse(line))];
|
|
35
|
+
} catch {
|
|
36
|
+
return [];
|
|
37
|
+
}
|
|
38
|
+
});
|
|
39
|
+
};
|
package/src/protocol.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { tsplcConfigSchema } from "@tsplc/config";
|
|
1
2
|
import { z } from "zod";
|
|
2
3
|
|
|
3
4
|
/** The controller the agent deploys to, as its runtime's TCP block driver address. */
|
|
@@ -42,6 +43,10 @@ export const releaseManifestSchema = z.strictObject({
|
|
|
42
43
|
variables: z.array(variableSchema),
|
|
43
44
|
/** The server executable's path in the release, when the project builds one. */
|
|
44
45
|
server: z.string().nonempty().optional(),
|
|
46
|
+
/** The project's `debug` section; the program's debug manifest is the release's `debug.json`. */
|
|
47
|
+
debug: tsplcConfigSchema.shape.debug,
|
|
48
|
+
/** The variable in the agent's environment holding the server's bearer token, for its telemetry and request trace. */
|
|
49
|
+
serverTokenEnv: z.string().nonempty().optional(),
|
|
45
50
|
});
|
|
46
51
|
export type ReleaseManifest = z.infer<typeof releaseManifestSchema>;
|
|
47
52
|
|
|
@@ -92,3 +97,37 @@ export const statusSchema = z.strictObject({
|
|
|
92
97
|
.nullable(),
|
|
93
98
|
});
|
|
94
99
|
export type AgentStatus = z.infer<typeof statusSchema>;
|
|
100
|
+
|
|
101
|
+
/** A logout's result: why the login couldn't log out, when its container had to be removed instead. */
|
|
102
|
+
export const logoutSchema = z.strictObject({ failure: z.string().optional() });
|
|
103
|
+
|
|
104
|
+
/** Who ran a command, as the client reports it in these headers. */
|
|
105
|
+
export const clientHeaders = { user: "x-tsplc-user", host: "x-tsplc-host" } as const;
|
|
106
|
+
|
|
107
|
+
/** A line of the agent's `deployments.jsonl`. */
|
|
108
|
+
export const deploymentSchema = z.strictObject({
|
|
109
|
+
at: z.iso.datetime(),
|
|
110
|
+
release: z.string(),
|
|
111
|
+
/** The debug manifest's build id, when the release has one. */
|
|
112
|
+
build: z.string().optional(),
|
|
113
|
+
operation: z.enum(["download", "online-change"]),
|
|
114
|
+
user: z.string().optional(),
|
|
115
|
+
host: z.string().optional(),
|
|
116
|
+
});
|
|
117
|
+
export type Deployment = z.infer<typeof deploymentSchema>;
|
|
118
|
+
|
|
119
|
+
/** A line of the agent's `audit.jsonl`: a login command that changed the controller. */
|
|
120
|
+
export const auditSchema = z.strictObject({
|
|
121
|
+
at: z.iso.datetime(),
|
|
122
|
+
/** As typed after `tsplc`, such as `force` or `reset cold`. */
|
|
123
|
+
command: z.string(),
|
|
124
|
+
/** Expressions written or forced, with their values; unforced expressions map to "". */
|
|
125
|
+
values: z.record(z.string(), z.string()),
|
|
126
|
+
/** The values read just before the command, when the read succeeded. */
|
|
127
|
+
previous: z.record(z.string(), z.string()).optional(),
|
|
128
|
+
user: z.string().optional(),
|
|
129
|
+
host: z.string().optional(),
|
|
130
|
+
release: z.string().optional(),
|
|
131
|
+
error: z.string().optional(),
|
|
132
|
+
});
|
|
133
|
+
export type Audit = z.infer<typeof auditSchema>;
|