@tsplc/agent 0.5.9 → 0.5.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/dist/cli.js +2462 -533
  2. package/dist/cli.js.map +30 -17
  3. package/dist/client.js +238 -36
  4. package/dist/client.js.map +4 -4
  5. package/dist/index.js +2162 -416
  6. package/dist/index.js.map +25 -13
  7. package/package.json +5 -5
  8. package/src/access.ts +257 -0
  9. package/src/agent.ts +101 -29
  10. package/src/audit.ts +64 -0
  11. package/src/cli.ts +58 -4
  12. package/src/client.ts +181 -36
  13. package/src/dashboard/index.ts +116 -0
  14. package/src/dashboard/ui/access.ts +192 -0
  15. package/src/dashboard/ui/actions.ts +142 -0
  16. package/src/dashboard/ui/api.ts +147 -0
  17. package/src/dashboard/ui/app.ts +41 -0
  18. package/src/dashboard/ui/approval.ts +132 -0
  19. package/src/dashboard/ui/audit.ts +115 -0
  20. package/src/dashboard/ui/contract.ts +16 -0
  21. package/src/dashboard/ui/dashboard.css +1332 -0
  22. package/src/dashboard/ui/deployment.ts +432 -0
  23. package/src/dashboard/ui/deployments.ts +317 -0
  24. package/src/dashboard/ui/details.ts +240 -0
  25. package/src/dashboard/ui/dom.ts +91 -0
  26. package/src/dashboard/ui/environment.ts +224 -0
  27. package/src/dashboard/ui/format.ts +118 -0
  28. package/src/dashboard/ui/logs.ts +127 -0
  29. package/src/dashboard/ui/main.ts +86 -0
  30. package/src/dashboard/ui/overlay.ts +146 -0
  31. package/src/dashboard/ui/shell.ts +171 -0
  32. package/src/dashboard/ui/source.ts +144 -0
  33. package/src/deploy.ts +138 -144
  34. package/src/deployments/health.ts +80 -0
  35. package/src/deployments/retention.ts +45 -0
  36. package/src/deployments/routes.ts +273 -0
  37. package/src/deployments/runner.ts +877 -0
  38. package/src/deployments/store.ts +233 -0
  39. package/src/environment.ts +205 -0
  40. package/src/index.ts +4 -0
  41. package/src/operations.ts +5 -1
  42. package/src/protocol.ts +218 -2
  43. package/src/releases.ts +73 -1
  44. package/src/routes.ts +52 -0
  45. package/src/secrets.ts +43 -2
  46. package/src/server-process.ts +33 -16
  47. package/src/sessions.ts +58 -0
  48. package/src/state.ts +2 -0
  49. package/src/tailscale.ts +112 -0
@@ -0,0 +1,233 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { existsSync } from "node:fs";
3
+ import {
4
+ appendFile,
5
+ mkdir,
6
+ readdir,
7
+ readFile,
8
+ rename,
9
+ rm,
10
+ writeFile,
11
+ } from "node:fs/promises";
12
+ import { join } from "node:path";
13
+ import { errorMessage } from "../errors";
14
+ import {
15
+ type DeploymentLogLine,
16
+ type DeploymentRecord,
17
+ type DeploymentState,
18
+ deploymentLogLineSchema,
19
+ deploymentRecordSchema,
20
+ } from "../protocol";
21
+
22
+ /** A change to a deployment, as its subscribers hear it. */
23
+ export type DeploymentEvent =
24
+ | { kind: "record"; record: DeploymentRecord }
25
+ | { kind: "log"; line: DeploymentLogLine };
26
+
27
+ /** States a deployment never leaves. */
28
+ const finalStates: readonly DeploymentState[] = ["ready", "error", "canceled"];
29
+
30
+ export const isFinished = (record: DeploymentRecord) =>
31
+ finalStates.includes(record.state);
32
+
33
+ /**
34
+ * The deployment running on the line, which no other has replaced yet, and the healthy one that
35
+ * ran last.
36
+ */
37
+ export const activeDeployments = (records: readonly DeploymentRecord[]) => {
38
+ const running = records.filter((record) => record.activeFrom !== null);
39
+ const newest = (candidates: DeploymentRecord[]) =>
40
+ candidates.reduce<DeploymentRecord | null>(
41
+ (best, record) =>
42
+ best && (best.activeFrom ?? "") >= (record.activeFrom ?? "")
43
+ ? best
44
+ : record,
45
+ null,
46
+ )?.id ?? null;
47
+ return {
48
+ current: newest(running.filter((record) => record.activeUntil === null)),
49
+ lastGood: newest(running.filter((record) => record.state === "ready")),
50
+ };
51
+ };
52
+
53
+ const parseJson = (text: string): unknown => {
54
+ try {
55
+ return JSON.parse(text);
56
+ } catch {
57
+ return undefined;
58
+ }
59
+ };
60
+
61
+ /** 20 lowercase letters and digits after `dpl_`. */
62
+ const newId = () =>
63
+ `dpl_${[...randomBytes(20)].map((byte) => (byte % 36).toString(36)).join("")}`;
64
+
65
+ /**
66
+ * Deployment records and logs under `directory`: `<id>/record.json`, rewritten whole through a
67
+ * temporary file, and `<id>/log.jsonl`, appended. Records are held in memory too, so reading one
68
+ * never waits on the disk; each deployment's writes happen in the order they were made.
69
+ */
70
+ export const openDeploymentStore = async (options: {
71
+ directory: string;
72
+ now: () => Date;
73
+ log: (message: string) => void;
74
+ }) => {
75
+ const { directory } = options;
76
+ const records = new Map<string, DeploymentRecord>();
77
+ /** The last log line's `seq` for each deployment whose log has been read or written. */
78
+ const sequences = new Map<string, number>();
79
+ const writes = new Map<string, Promise<void>>();
80
+ const listeners = new Map<string, Set<(event: DeploymentEvent) => void>>();
81
+
82
+ await mkdir(directory, { recursive: true });
83
+ for (const entry of await readdir(directory, { withFileTypes: true })) {
84
+ const file = join(directory, entry.name, "record.json");
85
+ if (!entry.isDirectory() || !existsSync(file)) {
86
+ continue;
87
+ }
88
+ const parsed = deploymentRecordSchema.safeParse(
89
+ parseJson(await readFile(file, "utf8")),
90
+ );
91
+ if (parsed.success && parsed.data.id === entry.name) {
92
+ records.set(parsed.data.id, parsed.data);
93
+ } else {
94
+ options.log(`Skipping the unreadable deployment record ${file}`);
95
+ }
96
+ }
97
+
98
+ const recordDirectory = (id: string) => join(directory, id);
99
+ const logFile = (id: string) => join(recordDirectory(id), "log.jsonl");
100
+
101
+ /** Runs `write` after the deployment's earlier writes, whether or not they failed. */
102
+ const inTurn = <Result>(id: string, write: () => Promise<Result>) => {
103
+ const next = (writes.get(id) ?? Promise.resolve()).then(write);
104
+ writes.set(
105
+ id,
106
+ next.then(
107
+ () => undefined,
108
+ (error: unknown) =>
109
+ options.log(
110
+ `Writing deployment ${id} failed: ${errorMessage(error)}`,
111
+ ),
112
+ ),
113
+ );
114
+ return next;
115
+ };
116
+
117
+ const emit = (id: string, event: DeploymentEvent) => {
118
+ for (const listener of listeners.get(id) ?? []) {
119
+ listener(event);
120
+ }
121
+ };
122
+
123
+ const readLines = async (id: string) => {
124
+ const file = logFile(id);
125
+ if (!existsSync(file)) {
126
+ return [];
127
+ }
128
+ return (await readFile(file, "utf8"))
129
+ .split("\n")
130
+ .filter(Boolean)
131
+ .flatMap((line) => {
132
+ // A crash can leave the last line half written; it is skipped.
133
+ const parsed = deploymentLogLineSchema.safeParse(parseJson(line));
134
+ return parsed.success ? [parsed.data] : [];
135
+ });
136
+ };
137
+
138
+ const writeRecord = (record: DeploymentRecord) =>
139
+ inTurn(record.id, async () => {
140
+ // The newest state is written, which may already include later changes.
141
+ const latest = records.get(record.id);
142
+ if (!latest) {
143
+ return;
144
+ }
145
+ const file = join(recordDirectory(record.id), "record.json");
146
+ const temporary = `${file}.tmp`;
147
+ await mkdir(recordDirectory(record.id), { recursive: true });
148
+ await writeFile(temporary, JSON.stringify(latest, null, 2));
149
+ await rename(temporary, file);
150
+ });
151
+
152
+ const existing = (id: string) => {
153
+ const record = records.get(id);
154
+ if (!record) {
155
+ throw new Error(`No deployment ${id}`);
156
+ }
157
+ return record;
158
+ };
159
+
160
+ return {
161
+ newId,
162
+ get: (id: string) => records.get(id),
163
+ /** Every deployment, newest first. */
164
+ list: () =>
165
+ [...records.values()].sort((left, right) =>
166
+ right.createdAt.localeCompare(left.createdAt),
167
+ ),
168
+ create: async (record: DeploymentRecord) => {
169
+ records.set(record.id, record);
170
+ sequences.set(record.id, 0);
171
+ await writeRecord(record);
172
+ return record;
173
+ },
174
+ /** Applies `change` to the deployment's record, stamping `updatedAt`, and writes it. */
175
+ update: async (
176
+ id: string,
177
+ change: (record: DeploymentRecord) => DeploymentRecord,
178
+ ) => {
179
+ const record = {
180
+ ...change(existing(id)),
181
+ updatedAt: options.now().toISOString(),
182
+ };
183
+ records.set(id, record);
184
+ emit(id, { kind: "record", record });
185
+ await writeRecord(record);
186
+ return record;
187
+ },
188
+ /** Appends a line to the deployment's log; subscribers hear it once it is on disk. */
189
+ log: (id: string, entry: Omit<DeploymentLogLine, "seq" | "at">) =>
190
+ inTurn(id, async () => {
191
+ const last =
192
+ sequences.get(id) ??
193
+ (await readLines(id)).reduce(
194
+ (highest, line) => Math.max(highest, line.seq),
195
+ 0,
196
+ );
197
+ const line: DeploymentLogLine = {
198
+ seq: last + 1,
199
+ at: options.now().toISOString(),
200
+ ...entry,
201
+ };
202
+ sequences.set(id, line.seq);
203
+ await mkdir(recordDirectory(id), { recursive: true });
204
+ await appendFile(logFile(id), `${JSON.stringify(line)}\n`);
205
+ emit(id, { kind: "log", line });
206
+ return line;
207
+ }),
208
+ /** Waits until the deployment's changes so far are on disk and heard. */
209
+ flush: async (id: string) => {
210
+ await writes.get(id);
211
+ },
212
+ /** The deployment's log lines after `seq` `after`. */
213
+ lines: async (id: string, after: number) => {
214
+ await writes.get(id);
215
+ return (await readLines(id)).filter((line) => line.seq > after);
216
+ },
217
+ subscribe: (id: string, listener: (event: DeploymentEvent) => void) => {
218
+ const subscribed = listeners.get(id) ?? new Set();
219
+ subscribed.add(listener);
220
+ listeners.set(id, subscribed);
221
+ return () => {
222
+ subscribed.delete(listener);
223
+ };
224
+ },
225
+ remove: (id: string) =>
226
+ inTurn(id, async () => {
227
+ records.delete(id);
228
+ sequences.delete(id);
229
+ await rm(recordDirectory(id), { recursive: true, force: true });
230
+ }),
231
+ };
232
+ };
233
+ export type DeploymentStore = Awaited<ReturnType<typeof openDeploymentStore>>;
@@ -0,0 +1,205 @@
1
+ import { existsSync } from "node:fs";
2
+ import { readFile, rename, writeFile } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { tsplcConfigSchema } from "@tsplc/config";
5
+ import { z } from "zod";
6
+ import type { AuditLog } from "./audit";
7
+ import { AgentError, errorMessage } from "./errors";
8
+ import type { Operations } from "./operations";
9
+ import {
10
+ type EnvironmentEntry,
11
+ environmentValueSchema,
12
+ type Identity,
13
+ } from "./protocol";
14
+ import { loadRelease } from "./releases";
15
+ import type { ApiRoute } from "./routes";
16
+ import { environmentService } from "./secrets";
17
+ import type { ServerSupervisor } from "./server-process";
18
+ import type { AgentState } from "./state";
19
+
20
+ /** The config's rule for a secret's name: an environment variable's. */
21
+ const secretName = tsplcConfigSchema.shape.secrets.unwrap().shape.names.element;
22
+
23
+ /** `environment.json` in the state directory `state`. */
24
+ export const environmentFile = (state: string) =>
25
+ join(state, "environment.json");
26
+
27
+ /**
28
+ * `environment.json`: the names the dashboard stored by Bun.secrets service, since Bun.secrets
29
+ * can't list a service's names. Never a value.
30
+ */
31
+ const storedNamesSchema = z.record(z.string(), z.array(secretName));
32
+
33
+ /**
34
+ * The deployed release's secrets, set and replaced but never read back, and the server's
35
+ * restart. The release's config names the Bun.secrets service they live in, which its
36
+ * deployments fill the ST from and its server starts with.
37
+ */
38
+ export const createEnvironment = (context: {
39
+ state: AgentState;
40
+ server: ServerSupervisor;
41
+ operations: Operations;
42
+ audit: AuditLog;
43
+ /** `environment.json`. */
44
+ file: string;
45
+ log: (message: string) => void;
46
+ }) => {
47
+ const { state, audit } = context;
48
+
49
+ const storedNames = async () =>
50
+ existsSync(context.file)
51
+ ? storedNamesSchema.parse(
52
+ JSON.parse(await readFile(context.file, "utf8")),
53
+ )
54
+ : {};
55
+ const writeStoredNames = async (
56
+ service: string,
57
+ update: (names: string[]) => string[],
58
+ ) => {
59
+ const stored = await storedNames();
60
+ const names = update(stored[service] ?? []);
61
+ await writeFile(
62
+ `${context.file}.tmp`,
63
+ JSON.stringify({ ...stored, [service]: names }, null, 2),
64
+ );
65
+ await rename(`${context.file}.tmp`, context.file);
66
+ };
67
+
68
+ /** The service the deployed release keeps its secrets in, and the names it declares. */
69
+ const declared = async () => {
70
+ const release = await state.release();
71
+ const secrets =
72
+ release &&
73
+ (await loadRelease(state.paths.releases, release.id)).manifest.secrets;
74
+ return secrets
75
+ ? { service: secrets.service, names: secrets.names }
76
+ : { service: environmentService, names: [] };
77
+ };
78
+
79
+ const isSet = async (service: string, name: string) =>
80
+ (await Bun.secrets.get({ service, name })) !== null;
81
+
82
+ const entries = async (): Promise<EnvironmentEntry[]> => {
83
+ const { service, names } = await declared();
84
+ const stored = ((await storedNames())[service] ?? []).filter(
85
+ (name) => !names.includes(name),
86
+ );
87
+ const undeclared = await Promise.all(
88
+ stored.map(async (name) => ({
89
+ name,
90
+ declared: false,
91
+ set: await isSet(service, name),
92
+ })),
93
+ );
94
+ return [
95
+ ...(await Promise.all(
96
+ names.map(async (name) => ({
97
+ name,
98
+ declared: true,
99
+ set: await isSet(service, name),
100
+ })),
101
+ )),
102
+ // A name deleted outside the dashboard is gone.
103
+ ...undeclared.filter(({ set }) => set),
104
+ ];
105
+ };
106
+
107
+ /** Records a change by the secret's name and who made it, never its value. */
108
+ const record = (identity: Identity, command: string) =>
109
+ audit.record({
110
+ identity,
111
+ command,
112
+ values: {},
113
+ previous: null,
114
+ error: null,
115
+ });
116
+
117
+ const routes: ApiRoute[] = [
118
+ {
119
+ method: "GET",
120
+ pattern: "/api/environment",
121
+ role: "viewer",
122
+ handle: async () => Response.json(await entries()),
123
+ },
124
+ {
125
+ method: "PUT",
126
+ pattern: "/api/environment/:name",
127
+ role: "admin",
128
+ handle: async (request, { identity, params }) => {
129
+ const name = secretName.parse(params.name);
130
+ const { value } = environmentValueSchema.parse(await request.json());
131
+ const { service, names } = await declared();
132
+ await Bun.secrets.set({ service, name, value });
133
+ await writeStoredNames(service, (stored) => [
134
+ ...stored.filter((other) => other !== name),
135
+ name,
136
+ ]);
137
+ await record(identity, `environment set ${name}`);
138
+ const entry: EnvironmentEntry = {
139
+ name,
140
+ declared: names.includes(name),
141
+ set: true,
142
+ };
143
+ return Response.json(entry);
144
+ },
145
+ },
146
+ {
147
+ method: "DELETE",
148
+ pattern: "/api/environment/:name",
149
+ role: "admin",
150
+ handle: async (_request, { identity, params }) => {
151
+ const name = secretName.parse(params.name);
152
+ const { service, names } = await declared();
153
+ if (!(await Bun.secrets.delete({ service, name }))) {
154
+ throw new AgentError(`${name} isn't set`, 404);
155
+ }
156
+ await writeStoredNames(service, (stored) =>
157
+ stored.filter((other) => other !== name),
158
+ );
159
+ await record(identity, `environment delete ${name}`);
160
+ const entry: EnvironmentEntry = {
161
+ name,
162
+ declared: names.includes(name),
163
+ set: false,
164
+ };
165
+ return Response.json(entry);
166
+ },
167
+ },
168
+ {
169
+ method: "POST",
170
+ pattern: "/api/server/restart",
171
+ role: "deployer",
172
+ handle: async (_request, { identity }) => {
173
+ const running = context.server.status();
174
+ if (!running) {
175
+ throw new AgentError("The deployed release runs no server", 409);
176
+ }
177
+ const failure = await context.operations
178
+ .exclusive("a server restart", () =>
179
+ context.server.replace(running.executable),
180
+ )
181
+ .then(
182
+ () => null,
183
+ (error: unknown) => error,
184
+ );
185
+ // Refused before it began: another operation runs.
186
+ if (failure instanceof AgentError) {
187
+ throw failure;
188
+ }
189
+ await audit.record({
190
+ identity,
191
+ command: "server restart",
192
+ values: {},
193
+ previous: null,
194
+ error: failure === null ? null : errorMessage(failure),
195
+ });
196
+ if (failure !== null) {
197
+ context.log(`Restarting the server failed: ${errorMessage(failure)}`);
198
+ throw new AgentError(errorMessage(failure), 500);
199
+ }
200
+ return Response.json(context.server.status());
201
+ },
202
+ },
203
+ ];
204
+ return { routes };
205
+ };
package/src/index.ts CHANGED
@@ -4,17 +4,21 @@ export {
4
4
  type AgentEvent,
5
5
  type AgentStatus,
6
6
  type Audit,
7
+ agentVersionHeader,
7
8
  auditSchema,
8
9
  type Credentials,
9
10
  clientHeaders,
10
11
  controllerSchema,
11
12
  credentialsSchema,
12
13
  type Deployment,
14
+ type DeploymentMode,
15
+ type DeploymentRecord,
13
16
  type DeployOptions,
14
17
  type DiscoveredController,
15
18
  deploymentSchema,
16
19
  deployOptionsSchema,
17
20
  eventSchema,
21
+ type GitSource,
18
22
  logoutSchema,
19
23
  type NetworkInterface,
20
24
  networkInterfaceSchema,
package/src/operations.ts CHANGED
@@ -3,7 +3,11 @@ import { AgentError, errorMessage } from "./errors";
3
3
  import type { AgentEvent } from "./protocol";
4
4
 
5
5
  /** What the agent can be busy with, as its messages name it. */
6
- export type Operation = "a deployment" | "a login" | "a logout";
6
+ export type Operation =
7
+ | "a deployment"
8
+ | "a login"
9
+ | "a logout"
10
+ | "a server restart";
7
11
 
8
12
  /** The agent runs one deployment, login or logout at a time, and none while it is held for an upgrade. */
9
13
  export const createOperations = (log: (message: string) => void) => {