@tsplc/tmp-agent 0.0.0-stage → 0.6.2

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
@@ -0,0 +1,209 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { existsSync } from "node:fs";
3
+ import { mkdir, readdir, readFile, rm } from "node:fs/promises";
4
+ import { join } from "node:path";
5
+ import { AgentError, errorMessage } from "../errors";
6
+ import { appendJsonLine, parsesAsJson } from "../logs";
7
+ import {
8
+ type DeploymentEvent,
9
+ type DeploymentLogLine,
10
+ type DeploymentRecord,
11
+ deploymentLogLineSchema,
12
+ deploymentRecordSchema,
13
+ finalStates,
14
+ } from "../protocol";
15
+ import { readJsonFileIfValid, writeJsonFile } from "../state";
16
+
17
+ export const isFinished = (record: DeploymentRecord) =>
18
+ finalStates.includes(record.state);
19
+
20
+ /**
21
+ * The deployment running on the line, which no other has replaced yet, and the healthy one that
22
+ * ran last.
23
+ */
24
+ export const activeDeployments = (records: readonly DeploymentRecord[]) => {
25
+ type Activated = DeploymentRecord & { activeFrom: string };
26
+ const running = records.filter(
27
+ (record): record is Activated => record.activeFrom !== null,
28
+ );
29
+ const newest = (candidates: Activated[]) =>
30
+ candidates.reduce<Activated | null>(
31
+ (best, record) =>
32
+ best && best.activeFrom >= record.activeFrom ? best : record,
33
+ null,
34
+ )?.id ?? null;
35
+ return {
36
+ current: newest(running.filter((record) => record.activeUntil === null)),
37
+ lastGood: newest(running.filter((record) => record.state === "ready")),
38
+ };
39
+ };
40
+
41
+ const newId = () =>
42
+ `dpl_${[...randomBytes(20)].map((byte) => (byte % 36).toString(36)).join("")}`;
43
+
44
+ /**
45
+ * Deployment records and logs under `directory`: `<id>/record.json`, rewritten whole through a
46
+ * temporary file, and `<id>/log.jsonl`, appended. Records are held in memory too, so reading one
47
+ * never waits on the disk; each deployment's writes happen in the order they were made.
48
+ */
49
+ export const openDeploymentStore = async (options: {
50
+ directory: string;
51
+ now: () => Date;
52
+ log: (message: string) => void;
53
+ }) => {
54
+ const { directory } = options;
55
+ const records = new Map<string, DeploymentRecord>();
56
+ /** The last log line's `seq` for each deployment whose log has been read or written. */
57
+ const sequences = new Map<string, number>();
58
+ const writes = new Map<string, Promise<void>>();
59
+ const listeners = new Map<string, Set<(event: DeploymentEvent) => void>>();
60
+
61
+ await mkdir(directory, { recursive: true });
62
+ for (const entry of await readdir(directory, { withFileTypes: true })) {
63
+ const file = join(directory, entry.name, "record.json");
64
+ if (!entry.isDirectory() || !existsSync(file)) {
65
+ continue;
66
+ }
67
+ const record = await readJsonFileIfValid(file, deploymentRecordSchema);
68
+ if (record?.id === entry.name) {
69
+ records.set(record.id, record);
70
+ } else {
71
+ options.log(`Skipping the unreadable deployment record ${file}`);
72
+ }
73
+ }
74
+
75
+ const recordDirectory = (id: string) => join(directory, id);
76
+ const logFile = (id: string) => join(recordDirectory(id), "log.jsonl");
77
+
78
+ /** Runs `write` after the deployment's earlier writes, whether or not they failed. */
79
+ const inTurn = <Result>(id: string, write: () => Promise<Result>) => {
80
+ const next = (writes.get(id) ?? Promise.resolve()).then(write);
81
+ writes.set(
82
+ id,
83
+ next.then(
84
+ () => undefined,
85
+ (error: unknown) =>
86
+ options.log(
87
+ `Writing deployment ${id} failed: ${errorMessage(error)}`,
88
+ ),
89
+ ),
90
+ );
91
+ return next;
92
+ };
93
+
94
+ const emit = (id: string, event: DeploymentEvent) => {
95
+ for (const listener of listeners.get(id) ?? []) {
96
+ listener(event);
97
+ }
98
+ };
99
+
100
+ const readLines = async (id: string) => {
101
+ const file = logFile(id);
102
+ if (!existsSync(file)) {
103
+ return [];
104
+ }
105
+ return (await readFile(file, "utf8"))
106
+ .split("\n")
107
+ .filter(Boolean)
108
+ .flatMap((line) => {
109
+ // A crash can leave the last line half written; it is skipped.
110
+ const parsed = deploymentLogLineSchema.safeParse(
111
+ parsesAsJson(line)?.json,
112
+ );
113
+ return parsed.success ? [parsed.data] : [];
114
+ });
115
+ };
116
+
117
+ const writeRecord = (record: DeploymentRecord) =>
118
+ inTurn(record.id, async () => {
119
+ // The newest state is written, which may already include later changes.
120
+ const latest = records.get(record.id);
121
+ if (!latest) {
122
+ return;
123
+ }
124
+ await mkdir(recordDirectory(record.id), { recursive: true });
125
+ writeJsonFile(join(recordDirectory(record.id), "record.json"), latest);
126
+ });
127
+
128
+ const get = (id: string) => {
129
+ const record = records.get(id);
130
+ if (!record) {
131
+ throw new AgentError(`No deployment ${id}`, 404);
132
+ }
133
+ return record;
134
+ };
135
+
136
+ return {
137
+ newId,
138
+ get,
139
+ /** Every deployment, newest first. */
140
+ list: () =>
141
+ [...records.values()].sort((left, right) =>
142
+ right.createdAt.localeCompare(left.createdAt),
143
+ ),
144
+ create: async (record: DeploymentRecord) => {
145
+ records.set(record.id, record);
146
+ sequences.set(record.id, 0);
147
+ await writeRecord(record);
148
+ return record;
149
+ },
150
+ /** Applies `change` to the deployment's record, stamping `updatedAt`, and writes it. */
151
+ update: async (
152
+ id: string,
153
+ change: (record: DeploymentRecord) => DeploymentRecord,
154
+ ) => {
155
+ const record = {
156
+ ...change(get(id)),
157
+ updatedAt: options.now().toISOString(),
158
+ };
159
+ records.set(id, record);
160
+ emit(id, { kind: "record", record });
161
+ await writeRecord(record);
162
+ return record;
163
+ },
164
+ /** Appends a line to the deployment's log; subscribers hear it once it is on disk. */
165
+ log: (id: string, entry: Omit<DeploymentLogLine, "seq" | "at">) =>
166
+ inTurn(id, async () => {
167
+ const last =
168
+ sequences.get(id) ??
169
+ (await readLines(id)).reduce(
170
+ (highest, line) => Math.max(highest, line.seq),
171
+ 0,
172
+ );
173
+ const line: DeploymentLogLine = {
174
+ seq: last + 1,
175
+ at: options.now().toISOString(),
176
+ ...entry,
177
+ };
178
+ sequences.set(id, line.seq);
179
+ await mkdir(recordDirectory(id), { recursive: true });
180
+ await appendJsonLine(logFile(id), line);
181
+ emit(id, { kind: "log", line });
182
+ return line;
183
+ }),
184
+ /** Waits until the deployment's changes so far are on disk and heard. */
185
+ flush: async (id: string) => {
186
+ await writes.get(id);
187
+ },
188
+ /** The deployment's log lines after `seq` `after`. */
189
+ lines: async (id: string, after: number) => {
190
+ await writes.get(id);
191
+ return (await readLines(id)).filter((line) => line.seq > after);
192
+ },
193
+ subscribe: (id: string, listener: (event: DeploymentEvent) => void) => {
194
+ const subscribed = listeners.get(id) ?? new Set();
195
+ subscribed.add(listener);
196
+ listeners.set(id, subscribed);
197
+ return () => {
198
+ subscribed.delete(listener);
199
+ };
200
+ },
201
+ remove: (id: string) =>
202
+ inTurn(id, async () => {
203
+ records.delete(id);
204
+ sequences.delete(id);
205
+ await rm(recordDirectory(id), { recursive: true, force: true });
206
+ }),
207
+ };
208
+ };
209
+ export type DeploymentStore = Awaited<ReturnType<typeof openDeploymentStore>>;
@@ -0,0 +1,78 @@
1
+ import { workerScriptsDigest } from "@tsplc/build";
2
+ import { AgentError } from "../errors";
3
+ import {
4
+ type ClientIdentity,
5
+ type ClientRelease,
6
+ type Credentials,
7
+ type DeployOptions,
8
+ type Identity,
9
+ tsplcVersion,
10
+ versionMismatch,
11
+ } from "../protocol";
12
+ import { controllerCredentials } from "../secrets";
13
+ import type { AgentState } from "../state";
14
+ import type { Submission } from "./runner";
15
+
16
+ /**
17
+ * Refuses a client of another tsPLC version, which compiles for scripts this agent doesn't run,
18
+ * and returns what to warn the deployment about. A client from before version checks reports none
19
+ * and is only warned, so it can still deploy.
20
+ */
21
+ export const clientWarnings = async (clientTsplc: ClientRelease) => {
22
+ if (clientTsplc.version === undefined) {
23
+ return [
24
+ `the deploying tsPLC predates version checks, while this plant agent runs tsPLC ${tsplcVersion}; update the client to ${tsplcVersion}`,
25
+ ];
26
+ }
27
+ if (clientTsplc.version !== tsplcVersion) {
28
+ throw new AgentError(
29
+ versionMismatch({
30
+ agent: tsplcVersion,
31
+ client: clientTsplc.version,
32
+ agentUpgrades: true,
33
+ }),
34
+ 409,
35
+ );
36
+ }
37
+ if (
38
+ clientTsplc.scripts !== undefined &&
39
+ clientTsplc.scripts !== (await workerScriptsDigest())
40
+ ) {
41
+ return [
42
+ `the plant agent's CODESYS scripts differ from the deploying tsPLC's, though both are ${tsplcVersion}, so one is a local build. The deployment runs the agent's scripts: update the plant agent to run the client's`,
43
+ ];
44
+ }
45
+ return [];
46
+ };
47
+
48
+ /** Who asked for a deployment: the identity behind the request, and the deploying machine's user and host. */
49
+ export const requester = (identity: Identity, client: ClientIdentity) => ({
50
+ identity: { login: identity.login, name: identity.name, via: identity.via },
51
+ user: client.user ?? null,
52
+ host: client.host ?? null,
53
+ });
54
+
55
+ /** The deployment an upload's `settings` ask for. */
56
+ export const submissionFrom = (
57
+ settings: DeployOptions,
58
+ identity: Identity,
59
+ client: ClientIdentity,
60
+ warnings: string[],
61
+ ): Submission => ({
62
+ git: settings.deployment?.git ?? null,
63
+ requestedBy: requester(identity, client),
64
+ mode: settings.deployment?.mode ?? "apply",
65
+ download: settings.download,
66
+ credentials: settings.credentials,
67
+ initializeUser: settings.initializeUser,
68
+ warnings,
69
+ });
70
+
71
+ /** Refuses what would fail anyway before a deployment starts: no controller selected, or no controller user. */
72
+ export const checkSubmission = async (
73
+ state: AgentState,
74
+ credentials: Credentials | null,
75
+ ) => {
76
+ await state.requireTarget();
77
+ await controllerCredentials(credentials);
78
+ };
@@ -0,0 +1,90 @@
1
+ import { Resolver } from "node:dns/promises";
2
+ import { createConnection } from "node:net";
3
+ import { networkInterfaces as osInterfaces } from "node:os";
4
+ import type { DiscoveredController, NetworkInterface } from "./protocol";
5
+
6
+ /** A /22 is 1022 hosts: a sweep at 128 probes a time takes a few seconds. */
7
+ const largestPrefix = 22;
8
+ const probeTimeoutMs = 500;
9
+ const probesAtOnce = 128;
10
+
11
+ /** The machine's IPv4 networks, which `discoverControllers` scans one at a time. */
12
+ export const networkInterfaces = (): NetworkInterface[] =>
13
+ Object.entries(osInterfaces()).flatMap(([name, addresses]) =>
14
+ (addresses ?? [])
15
+ .filter((address) => address.family === "IPv4" && !address.internal)
16
+ .map((address) => ({
17
+ name,
18
+ address: address.address,
19
+ prefixLength: address.netmask
20
+ .split(".")
21
+ .reduce(
22
+ (bits, octet) =>
23
+ bits + Number(octet).toString(2).replaceAll("0", "").length,
24
+ 0,
25
+ ),
26
+ })),
27
+ );
28
+
29
+ const toNumber = (address: string) =>
30
+ address.split(".").reduce((value, octet) => value * 256 + Number(octet), 0);
31
+ const toAddress = (value: number) =>
32
+ [24, 16, 8, 0].map((shift) => Math.floor(value / 2 ** shift) % 256).join(".");
33
+
34
+ /** Every host address on the interface's subnet, except the interface's own. */
35
+ export const subnetHosts = ({ address, prefixLength }: NetworkInterface) => {
36
+ if (prefixLength < largestPrefix) {
37
+ throw new Error(
38
+ `The /${prefixLength} network is too large to scan; the limit is /${largestPrefix}.`,
39
+ );
40
+ }
41
+ const size = 2 ** (32 - prefixLength);
42
+ const network = toNumber(address) - (toNumber(address) % size);
43
+ // /31 and /32 networks have no network or broadcast address to skip.
44
+ const hosts =
45
+ size <= 2
46
+ ? Array.from({ length: size }, (_, index) => network + index)
47
+ : Array.from({ length: size - 2 }, (_, index) => network + index + 1);
48
+ return hosts.map(toAddress).filter((host) => host !== address);
49
+ };
50
+
51
+ const accepts = (host: string, port: number) =>
52
+ new Promise<boolean>((resolve) => {
53
+ const socket = createConnection({ host, port });
54
+ // A silent host leaves the connection pending for the OS's own timeout, which is minutes.
55
+ const timer = setTimeout(() => finish(false), probeTimeoutMs);
56
+ const finish = (open: boolean) => {
57
+ clearTimeout(timer);
58
+ socket.destroy();
59
+ resolve(open);
60
+ };
61
+ socket.once("connect", () => finish(true));
62
+ socket.once("error", () => finish(false));
63
+ });
64
+
65
+ const resolver = new Resolver({ timeout: 1000, tries: 1 });
66
+ const hostname = (address: string) =>
67
+ resolver.reverse(address).then(
68
+ (names) => names[0] ?? null,
69
+ // Plant networks rarely have reverse DNS; the address alone identifies the controller.
70
+ () => null,
71
+ );
72
+
73
+ /** Finds the hosts on `network` that accept connections on `port`, such as CODESYS runtimes'. */
74
+ export const discoverControllers = async (
75
+ network: NetworkInterface,
76
+ port: number,
77
+ ): Promise<DiscoveredController[]> => {
78
+ const hosts = subnetHosts(network);
79
+ const found: DiscoveredController[] = [];
80
+ for (let start = 0; start < hosts.length; start += probesAtOnce) {
81
+ const batch = hosts.slice(start, start + probesAtOnce);
82
+ const open = await Promise.all(batch.map((host) => accepts(host, port)));
83
+ for (const [index, host] of batch.entries()) {
84
+ if (open[index]) {
85
+ found.push({ address: host, port, hostname: await hostname(host) });
86
+ }
87
+ }
88
+ }
89
+ return found;
90
+ };
@@ -0,0 +1,214 @@
1
+ import type { PlantVariables } from "@tsplc/config";
2
+ import { envName } from "@tsplc/config/build";
3
+ import { z } from "zod";
4
+ import { type AuditLog, authorOf } from "./audit";
5
+ import { AgentError } from "./errors";
6
+ import {
7
+ type EnvironmentEntry,
8
+ type EnvironmentListing,
9
+ environmentValueSchema,
10
+ type Identity,
11
+ } from "./protocol";
12
+ import { loadRelease } from "./releases";
13
+ import type { ApiRoute } from "./routes";
14
+ import { environmentService } from "./secrets";
15
+ import { type AgentState, readJsonFile, writeJsonFile } from "./state";
16
+
17
+ const storedNamesSchema = z.record(z.string(), z.array(envName));
18
+
19
+ const storedVariablesSchema = z.record(envName, z.string());
20
+
21
+ /**
22
+ * The plant PC's variables: plain ones, shown and edited here, and secrets, set and replaced but
23
+ * never read back; and what the running release was built with. `tsplc deploy` builds the PLC's
24
+ * program with the plain values and carries them to the server, and the agent fills the secrets
25
+ * in from the Bun.secrets service the release names, so a change reaches both with the next
26
+ * deployment.
27
+ */
28
+ export const createEnvironment = (context: {
29
+ state: AgentState;
30
+ audit: AuditLog;
31
+ }) => {
32
+ const { state, audit } = context;
33
+ const { paths } = state;
34
+
35
+ const storedNames = async () =>
36
+ (await readJsonFile(paths.environment, storedNamesSchema)) ?? {};
37
+ const writeStoredNames = async (
38
+ service: string,
39
+ update: (names: string[]) => string[],
40
+ ) => {
41
+ const stored = await storedNames();
42
+ writeJsonFile(paths.environment, {
43
+ ...stored,
44
+ [service]: update(stored[service] ?? []),
45
+ });
46
+ };
47
+ const storedVariables = async () =>
48
+ (await readJsonFile(paths.variables, storedVariablesSchema)) ?? {};
49
+
50
+ const deployedManifest = async () => {
51
+ const release = await state.release();
52
+ return release
53
+ ? (await loadRelease(state.paths.releases, release.id)).manifest
54
+ : undefined;
55
+ };
56
+
57
+ /** The service the deployed release keeps its secrets in, and the names it reads. */
58
+ const declared = async () =>
59
+ (await deployedManifest())?.secrets ?? {
60
+ service: environmentService,
61
+ names: [],
62
+ };
63
+
64
+ const isSet = async (service: string, name: string) =>
65
+ (await Bun.secrets.get({ service, name })) !== null;
66
+
67
+ const entries = async (): Promise<EnvironmentEntry[]> => {
68
+ const { service, names } = await declared();
69
+ const stored = ((await storedNames())[service] ?? []).filter(
70
+ (name) => !names.includes(name),
71
+ );
72
+ const undeclared = await Promise.all(
73
+ stored.map(async (name) => ({
74
+ name,
75
+ declared: false,
76
+ set: await isSet(service, name),
77
+ })),
78
+ );
79
+ return [
80
+ ...(await Promise.all(
81
+ names.map(async (name) => ({
82
+ name,
83
+ declared: true,
84
+ set: await isSet(service, name),
85
+ })),
86
+ )),
87
+ // A name deleted outside the dashboard is gone.
88
+ ...undeclared.filter(({ set }) => set),
89
+ ];
90
+ };
91
+
92
+ const listing = async (): Promise<EnvironmentListing> => ({
93
+ values: (await deployedManifest())?.values ?? {},
94
+ variables: await storedVariables(),
95
+ secrets: await entries(),
96
+ });
97
+
98
+ /** What `tsplc deploy` builds with: the plain values, and the secrets set in `service`. */
99
+ const forRelease = async (service: string): Promise<PlantVariables> => {
100
+ const held = (await storedNames())[service] ?? [];
101
+ const set = await Promise.all(
102
+ held.map(async (name) => ((await isSet(service, name)) ? [name] : [])),
103
+ );
104
+ return { service, values: await storedVariables(), secrets: set.flat() };
105
+ };
106
+
107
+ /** Records a change by the variable's name, with a plain one's value; never a secret's. */
108
+ const record = (
109
+ identity: Identity,
110
+ command: string,
111
+ change: {
112
+ values: Record<string, string>;
113
+ previous: Record<string, string> | null;
114
+ },
115
+ ) =>
116
+ audit.record({
117
+ by: authorOf(identity),
118
+ command,
119
+ values: change.values,
120
+ previous: change.previous,
121
+ error: null,
122
+ });
123
+ /** A secret's change: its name alone. */
124
+ const nameOnly = { values: {}, previous: null };
125
+
126
+ const withoutVariable = async (name: string) => {
127
+ const { [name]: removed, ...rest } = await storedVariables();
128
+ if (removed !== undefined) {
129
+ writeJsonFile(paths.variables, rest);
130
+ }
131
+ return removed;
132
+ };
133
+
134
+ const routes: ApiRoute[] = [
135
+ {
136
+ method: "GET",
137
+ pattern: "/api/environment",
138
+ role: "viewer",
139
+ handle: async () => Response.json(await listing()),
140
+ },
141
+ {
142
+ method: "GET",
143
+ pattern: "/api/environment/release",
144
+ role: "deployer",
145
+ handle: async (request) =>
146
+ Response.json(
147
+ await forRelease(
148
+ new URL(request.url).searchParams.get("service") ||
149
+ environmentService,
150
+ ),
151
+ ),
152
+ },
153
+ {
154
+ method: "PUT",
155
+ pattern: "/api/environment/:name",
156
+ role: "admin",
157
+ handle: async (request, { identity, params }) => {
158
+ const name = envName.parse(params.name);
159
+ const change = environmentValueSchema.parse(await request.json());
160
+ const { service } = await declared();
161
+ if (change.secret) {
162
+ await Bun.secrets.set({ service, name, value: change.value });
163
+ await writeStoredNames(service, (stored) => [
164
+ ...stored.filter((other) => other !== name),
165
+ name,
166
+ ]);
167
+ await withoutVariable(name);
168
+ await record(identity, `environment set ${name}`, nameOnly);
169
+ return Response.json(await listing());
170
+ }
171
+ const variables = await storedVariables();
172
+ const previous = variables[name];
173
+ writeJsonFile(paths.variables, { ...variables, [name]: change.value });
174
+ // A name is a plain variable or a secret, never both.
175
+ if (await Bun.secrets.delete({ service, name })) {
176
+ await writeStoredNames(service, (stored) =>
177
+ stored.filter((other) => other !== name),
178
+ );
179
+ }
180
+ await record(identity, `environment set ${name}`, {
181
+ values: { [name]: change.value },
182
+ previous: previous === undefined ? null : { [name]: previous },
183
+ });
184
+ return Response.json(await listing());
185
+ },
186
+ },
187
+ {
188
+ method: "DELETE",
189
+ pattern: "/api/environment/:name",
190
+ role: "admin",
191
+ handle: async (_request, { identity, params }) => {
192
+ const name = envName.parse(params.name);
193
+ const removed = await withoutVariable(name);
194
+ if (removed !== undefined) {
195
+ await record(identity, `environment delete ${name}`, {
196
+ values: {},
197
+ previous: { [name]: removed },
198
+ });
199
+ return Response.json(await listing());
200
+ }
201
+ const { service } = await declared();
202
+ if (!(await Bun.secrets.delete({ service, name }))) {
203
+ throw new AgentError(`${name} isn't set`, 404);
204
+ }
205
+ await writeStoredNames(service, (stored) =>
206
+ stored.filter((other) => other !== name),
207
+ );
208
+ await record(identity, `environment delete ${name}`, nameOnly);
209
+ return Response.json(await listing());
210
+ },
211
+ },
212
+ ];
213
+ return { routes };
214
+ };
package/src/errors.ts ADDED
@@ -0,0 +1,12 @@
1
+ /** A request the agent refuses, answered with `status` and the message. */
2
+ export class AgentError extends Error {
3
+ constructor(
4
+ message: string,
5
+ readonly status: number,
6
+ ) {
7
+ super(message);
8
+ }
9
+ }
10
+
11
+ export const errorMessage = (error: unknown) =>
12
+ error instanceof Error ? error.message : String(error);
package/src/index.ts ADDED
@@ -0,0 +1,36 @@
1
+ export { controllerCredentialsSchema as credentialsSchema } from "@tsplc/build";
2
+ export { type AgentOptions, createAgent } from "./agent";
3
+ export { agentDockerResources } from "./codesys";
4
+ export {
5
+ type AgentEvent,
6
+ type AgentStatus,
7
+ type Audit,
8
+ agentVersionHeader,
9
+ auditSchema,
10
+ type Credentials,
11
+ clientHeaders,
12
+ type Deployment,
13
+ type DeploymentMode,
14
+ type DeploymentRecord,
15
+ type DeployOptions,
16
+ type DiscoveredController,
17
+ deploymentSchema,
18
+ deployOptionsSchema,
19
+ discoveredControllerSchema as controllerSchema,
20
+ eventSchema,
21
+ type GitSource,
22
+ logoutSchema,
23
+ type NetworkInterface,
24
+ networkInterfaceSchema,
25
+ type Release,
26
+ type ReleaseManifest,
27
+ releaseManifestSchema,
28
+ releaseSchema,
29
+ statusSchema,
30
+ type Target,
31
+ targetSchema,
32
+ uploadEncoding,
33
+ type Variable,
34
+ variableSchema,
35
+ } from "./protocol";
36
+ export { ask, askCredentials, askSecret } from "./terminal";
@@ -0,0 +1,51 @@
1
+ import { rm } from "node:fs/promises";
2
+ import { z } from "zod";
3
+ import type { AgentClient } from "./client";
4
+ import { processAlive } from "./processes";
5
+ import { agentVersionHeader, statusPath } from "./protocol";
6
+ import { readJsonFileIfValid } from "./state";
7
+
8
+ /**
9
+ * The running agent, as `serve` records it in its state directory, so that `upgrade` and
10
+ * `service` on the same PC can reach it and start it again the same way.
11
+ */
12
+ export const instanceSchema = z.strictObject({
13
+ pid: z.int().positive(),
14
+ version: z.string(),
15
+ url: z.url(),
16
+ /** The arguments after `serve` it was started with. */
17
+ serve: z.array(z.string()),
18
+ /** Started by `tsplc-agent service run`, which starts it again when it exits. */
19
+ supervised: z.boolean(),
20
+ startedAt: z.iso.datetime(),
21
+ });
22
+ export type Instance = z.infer<typeof instanceSchema>;
23
+
24
+ /** The exit status of an agent that exits to be started again, such as after an upgrade. */
25
+ export const restartStatus = 75;
26
+
27
+ /** Removes the record, unless another agent has replaced it since. */
28
+ export const removeInstance = async (file: string, pid: number) => {
29
+ if ((await readInstance(file))?.pid === pid) {
30
+ await rm(file, { force: true });
31
+ }
32
+ };
33
+
34
+ const readInstance = (file: string) =>
35
+ readJsonFileIfValid(file, instanceSchema);
36
+
37
+ /** The agent recorded in `file`, when its process still runs, or null. */
38
+ export const runningAgent = async (file: string) => {
39
+ const instance = await readInstance(file);
40
+ return instance && processAlive(instance.pid) ? instance : null;
41
+ };
42
+
43
+ /** The tsPLC version the agent at `url` answers with, which it names even to a request without its token, or null. */
44
+ export const answeringVersion = (url: string) =>
45
+ fetch(new URL(statusPath, url), { signal: AbortSignal.timeout(5000) }).then(
46
+ (response) => response.headers.get(agentVersionHeader),
47
+ () => null,
48
+ );
49
+
50
+ /** The routes that hold a running agent for an upgrade and make it exit. */
51
+ export type AgentControl = Pick<AgentClient, "hold" | "releaseHold" | "exit">;