@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
@@ -0,0 +1,144 @@
1
+ import { type Child, h, icon, icons } from "./dom";
2
+
3
+ /** A menu item: an action, or a line between groups of them. */
4
+ export type MenuItem =
5
+ | {
6
+ label: string;
7
+ run: () => void;
8
+ tone?: "danger";
9
+ disabled?: boolean;
10
+ }
11
+ | "separator";
12
+
13
+ let closeOpenMenu: (() => void) | null = null;
14
+
15
+ /** Whether a menu or dialog is open, so a refresh doesn't pull the rows out from under it. */
16
+ export const overlayOpen = () =>
17
+ closeOpenMenu !== null || document.querySelector("dialog[open]") !== null;
18
+
19
+ const openMenu = (anchor: HTMLElement, items: MenuItem[]) => {
20
+ closeOpenMenu?.();
21
+ const menu = h(
22
+ "div",
23
+ { class: "menu", role: "menu" },
24
+ ...items.map((item) =>
25
+ item === "separator"
26
+ ? h("div", { class: "menu-separator" })
27
+ : h(
28
+ "button",
29
+ {
30
+ class: `menu-item${item.tone ? ` ${item.tone}` : ""}`,
31
+ role: "menuitem",
32
+ disabled: item.disabled,
33
+ onclick: (event) => {
34
+ event.stopPropagation();
35
+ close();
36
+ item.run();
37
+ },
38
+ },
39
+ item.label,
40
+ ),
41
+ ),
42
+ );
43
+ const outside = (event: Event) => {
44
+ if (event.target instanceof Node && !menu.contains(event.target)) {
45
+ close();
46
+ }
47
+ };
48
+ const onKey = (event: KeyboardEvent) => {
49
+ if (event.key === "Escape") {
50
+ close();
51
+ }
52
+ };
53
+ const close = () => {
54
+ menu.remove();
55
+ document.removeEventListener("click", outside, true);
56
+ document.removeEventListener("keydown", onKey);
57
+ closeOpenMenu = null;
58
+ };
59
+ document.body.append(menu);
60
+ const box = anchor.getBoundingClientRect();
61
+ menu.style.top = `${box.bottom + window.scrollY + 4}px`;
62
+ menu.style.left = `${Math.max(8, box.right + window.scrollX - menu.offsetWidth)}px`;
63
+ document.addEventListener("click", outside, true);
64
+ document.addEventListener("keydown", onKey);
65
+ closeOpenMenu = close;
66
+ menu.querySelector<HTMLButtonElement>("button:not([disabled])")?.focus();
67
+ };
68
+
69
+ export const menuButton = (label: string, items: () => MenuItem[]) =>
70
+ h(
71
+ "button",
72
+ {
73
+ class: "icon-button",
74
+ title: label,
75
+ "aria-label": label,
76
+ "aria-haspopup": "menu",
77
+ onclick: (event) => {
78
+ event.stopPropagation();
79
+ if (event.currentTarget instanceof HTMLElement) {
80
+ openMenu(event.currentTarget, items());
81
+ }
82
+ },
83
+ },
84
+ icon(icons.more),
85
+ );
86
+
87
+ /**
88
+ * A modal dialog. `actions` builds its buttons, given `close`; it resolves with what `close` was
89
+ * given, or null when dismissed.
90
+ */
91
+ export const dialog = <T>(options: {
92
+ title: string;
93
+ body: Child[];
94
+ actions: (close: (value: T) => void) => Child[];
95
+ }) =>
96
+ new Promise<T | null>((resolve) => {
97
+ const element = h("dialog", { class: "dialog" });
98
+ let result: T | null = null;
99
+ const close = (value: T) => {
100
+ result = value;
101
+ element.close();
102
+ };
103
+ element.addEventListener("close", () => {
104
+ element.remove();
105
+ resolve(result);
106
+ });
107
+ element.append(
108
+ h("h2", {}, options.title),
109
+ h("div", { class: "dialog-body" }, ...options.body),
110
+ h("div", { class: "dialog-actions" }, ...options.actions(close)),
111
+ );
112
+ document.body.append(element);
113
+ element.showModal();
114
+ });
115
+
116
+ /** Asks to confirm an action: resolves true once confirmed. */
117
+ export const confirm = async (options: {
118
+ title: string;
119
+ body: Child[];
120
+ confirm: string;
121
+ tone: "primary" | "danger";
122
+ }) =>
123
+ (await dialog<boolean>({
124
+ title: options.title,
125
+ body: options.body,
126
+ actions: (close) => [
127
+ h("button", { class: "button", onclick: () => close(false) }, "Cancel"),
128
+ h(
129
+ "button",
130
+ { class: `button ${options.tone}`, onclick: () => close(true) },
131
+ options.confirm,
132
+ ),
133
+ ],
134
+ })) === true;
135
+
136
+ const toasts = () =>
137
+ document.querySelector(".toasts") ??
138
+ document.body.appendChild(h("div", { class: "toasts", role: "status" }));
139
+
140
+ export const toast = (message: string, tone: "ok" | "error") => {
141
+ const element = h("div", { class: `toast t-${tone}` }, message);
142
+ toasts().append(element);
143
+ setTimeout(() => element.remove(), tone === "error" ? 8000 : 4000);
144
+ };
@@ -0,0 +1,185 @@
1
+ import { errorMessage } from "../../errors";
2
+ import { restartController } from "./actions";
3
+ import { agentVersion, api } from "./api";
4
+ import { type App, attempt } from "./app";
5
+ import { contract } from "./contract";
6
+ import { badge, fill, h, icon, icons } from "./dom";
7
+
8
+ const [home] = contract.pages;
9
+
10
+ /** Light, dark, or the system's, cycled by the header's button and kept in local storage. */
11
+ const themeButton = () => {
12
+ const button = h("button", { class: "icon-button", title: "Theme" });
13
+ const render = () => {
14
+ const theme = document.documentElement.dataset.theme ?? "";
15
+ fill(button, icon(theme === "light" ? icons.sun : icons.moon));
16
+ button.title = `Theme: ${theme || "system"}`;
17
+ };
18
+ button.addEventListener("click", () => {
19
+ const order = ["", "dark", "light"];
20
+ const theme = document.documentElement.dataset.theme ?? "";
21
+ const next = order[(order.indexOf(theme) + 1) % order.length] ?? "";
22
+ document.documentElement.dataset.theme = next;
23
+ localStorage.setItem(contract.themeKey, next);
24
+ render();
25
+ });
26
+ render();
27
+ return button;
28
+ };
29
+
30
+ /** Resets the application and starts it again, from any page; busy until the controller answers. */
31
+ const restartButton = () => {
32
+ const button = h(
33
+ "button",
34
+ {
35
+ class: "button small",
36
+ title: "Reset the application warm or cold, then start it",
37
+ },
38
+ "Reset and start",
39
+ );
40
+ button.addEventListener("click", () => {
41
+ void restartController((busy) => {
42
+ button.disabled = busy;
43
+ button.textContent = busy ? "Restarting…" : "Reset and start";
44
+ });
45
+ });
46
+ return button;
47
+ };
48
+
49
+ /** The header: the agent and controller, who is signed in, and the pages. */
50
+ export const shell = (app: App) => {
51
+ const where = h("span", { class: "muted mono" });
52
+ const version = h("span", { class: "muted mono version" });
53
+ const nav = h("nav", { class: "nav" });
54
+ void api
55
+ .status()
56
+ .then(
57
+ (status) => {
58
+ where.textContent = status.target
59
+ ? `${status.target.host}:${status.target.port}`
60
+ : "No controller selected";
61
+ },
62
+ () => {},
63
+ )
64
+ .finally(() => {
65
+ version.textContent = agentVersion() ? `tsPLC ${agentVersion()}` : "";
66
+ });
67
+
68
+ const setActive = (pathname: string) => {
69
+ const active = pathname === "/" ? home.path : pathname;
70
+ fill(
71
+ nav,
72
+ ...contract.pages
73
+ .filter((section) => app.can(section.role))
74
+ .map((section) =>
75
+ h(
76
+ "a",
77
+ {
78
+ class: `nav-link${active === section.path || active.startsWith(`${section.path}/`) ? " on" : ""}`,
79
+ href: section.path,
80
+ onclick: (event) => {
81
+ event.preventDefault();
82
+ app.navigate(section.path);
83
+ },
84
+ },
85
+ section.label,
86
+ ),
87
+ ),
88
+ // The debugger is its own app.
89
+ h("a", { class: "nav-link", href: contract.debuggerMount }, "Debugger"),
90
+ );
91
+ };
92
+
93
+ const element = h(
94
+ "header",
95
+ { class: "topbar" },
96
+ h(
97
+ "div",
98
+ { class: "topbar-row" },
99
+ h(
100
+ "a",
101
+ {
102
+ class: "brand",
103
+ href: home.path,
104
+ onclick: (event) => {
105
+ event.preventDefault();
106
+ app.navigate(home.path);
107
+ },
108
+ },
109
+ h("span", { class: "logo", "aria-hidden": "true" }),
110
+ h("b", {}, "tsPLC"),
111
+ h("span", { class: "muted" }, "plant agent"),
112
+ ),
113
+ h("span", { class: "slash" }, "/"),
114
+ where,
115
+ app.can("deployer") ? restartButton() : null,
116
+ h(
117
+ "div",
118
+ { class: "topbar-end" },
119
+ version,
120
+ themeButton(),
121
+ h(
122
+ "span",
123
+ { class: "who", title: app.identity.login ?? app.identity.name },
124
+ app.identity.name,
125
+ badge(app.identity.role, "neutral"),
126
+ ),
127
+ // A token's session is a cookie, which signing out clears; Tailscale and the agent's PC can't sign out.
128
+ app.identity.via === "token"
129
+ ? h(
130
+ "button",
131
+ {
132
+ class: "button small",
133
+ onclick: () =>
134
+ void attempt(() => api.signOut(), { done: null }).then(() =>
135
+ location.reload(),
136
+ ),
137
+ },
138
+ "Sign out",
139
+ )
140
+ : null,
141
+ ),
142
+ ),
143
+ nav,
144
+ );
145
+ return { element, setActive };
146
+ };
147
+
148
+ /** Asks for the agent's token, which signs this browser in with a cookie. */
149
+ export const signInForm = (onSignedIn: () => void) => {
150
+ const token = h("input", {
151
+ class: "input mono",
152
+ type: "password",
153
+ autocomplete: "current-password",
154
+ placeholder: "Agent token",
155
+ required: true,
156
+ });
157
+ const error = h("p", { class: "error-text" });
158
+ return h(
159
+ "div",
160
+ { class: "sign-in" },
161
+ h(
162
+ "form",
163
+ {
164
+ class: "card",
165
+ onsubmit: (event) => {
166
+ event.preventDefault();
167
+ error.textContent = "";
168
+ api.signIn(token.value).then(onSignedIn, (failure: unknown) => {
169
+ error.textContent = errorMessage(failure);
170
+ });
171
+ },
172
+ },
173
+ h("span", { class: "logo large", "aria-hidden": "true" }),
174
+ h("h1", {}, "Sign in to the plant agent"),
175
+ h(
176
+ "p",
177
+ { class: "muted" },
178
+ "Your Tailscale login has no role on this agent. Sign in with the agent's token, or ask an admin for a role.",
179
+ ),
180
+ token,
181
+ error,
182
+ h("button", { class: "button primary", type: "submit" }, "Sign in"),
183
+ ),
184
+ );
185
+ };
@@ -0,0 +1,144 @@
1
+ import { errorMessage } from "../../errors";
2
+ import { api, type SourceFile } from "./api";
3
+ import { type App, deploymentHref } from "./app";
4
+ import { empty, fill, h, icon, icons } from "./dom";
5
+ import { encodePath, formatSize } from "./format";
6
+
7
+ interface Folder {
8
+ folders: Map<string, Folder>;
9
+ files: SourceFile[];
10
+ }
11
+
12
+ const tree = (files: readonly SourceFile[]) => {
13
+ const root: Folder = { folders: new Map(), files: [] };
14
+ for (const file of files) {
15
+ const parts = file.path.split("/");
16
+ const folder = parts.slice(0, -1).reduce((parent, name) => {
17
+ const existing = parent.folders.get(name);
18
+ if (existing) {
19
+ return existing;
20
+ }
21
+ const created: Folder = { folders: new Map(), files: [] };
22
+ parent.folders.set(name, created);
23
+ return created;
24
+ }, root);
25
+ folder.files.push(file);
26
+ }
27
+ return root;
28
+ };
29
+
30
+ const fileName = (path: string) => path.slice(path.lastIndexOf("/") + 1);
31
+
32
+ /** The release's files as a tree, and the selected one's text with line numbers. */
33
+ export const sourceView = (app: App, id: string) => {
34
+ const files = h("nav", { class: "file-tree" }, empty("Loading files…"));
35
+ const content = h(
36
+ "div",
37
+ { class: "file-view" },
38
+ empty("Select a file to see its text."),
39
+ );
40
+ const sourceHref = (path: string) =>
41
+ `${deploymentHref(id, "source")}/${encodePath(path)}`;
42
+ let selected: string | null = null;
43
+ let listing: SourceFile[] | null = null;
44
+
45
+ const fileLink = (file: SourceFile) =>
46
+ h(
47
+ "a",
48
+ {
49
+ class: `file${file.path === selected ? " on" : ""}`,
50
+ href: sourceHref(file.path),
51
+ title: `${file.path} · ${formatSize(file.size)}`,
52
+ onclick: (event) => {
53
+ event.preventDefault();
54
+ app.navigate(sourceHref(file.path));
55
+ },
56
+ },
57
+ icon(icons.file),
58
+ fileName(file.path),
59
+ );
60
+
61
+ const folderElement = (folder: Folder, path: string): HTMLElement[] => [
62
+ ...[...folder.folders]
63
+ .sort(([a], [b]) => a.localeCompare(b))
64
+ .map(([name, child]) => {
65
+ const childPath = path ? `${path}/${name}` : name;
66
+ return h(
67
+ "details",
68
+ {
69
+ open:
70
+ !selected || selected.startsWith(`${childPath}/`) || path === "",
71
+ },
72
+ h("summary", {}, icon(icons.folder), name),
73
+ h("div", { class: "folder" }, ...folderElement(child, childPath)),
74
+ );
75
+ }),
76
+ ...folder.files
77
+ .slice()
78
+ .sort((a, b) => a.path.localeCompare(b.path))
79
+ .map(fileLink),
80
+ ];
81
+
82
+ const renderTree = () => {
83
+ if (listing) {
84
+ fill(
85
+ files,
86
+ ...(listing.length
87
+ ? folderElement(tree(listing), "")
88
+ : [empty("This release has no files.")]),
89
+ );
90
+ }
91
+ };
92
+
93
+ const show = async (path: string | null) => {
94
+ selected = path;
95
+ renderTree();
96
+ if (!path) {
97
+ fill(content, empty("Select a file to see its text."));
98
+ return;
99
+ }
100
+ const size = listing?.find((file) => file.path === path)?.size;
101
+ fill(content, empty(`Loading ${path}…`));
102
+ try {
103
+ const text = await api.sourceFile(id, path);
104
+ if (selected !== path) {
105
+ return;
106
+ }
107
+ fill(
108
+ content,
109
+ h(
110
+ "div",
111
+ { class: "file-header" },
112
+ h("span", { class: "mono" }, path),
113
+ size === undefined
114
+ ? null
115
+ : h("span", { class: "muted" }, formatSize(size)),
116
+ ),
117
+ h(
118
+ "pre",
119
+ { class: "code" },
120
+ ...text
121
+ .replace(/\n$/, "")
122
+ .split("\n")
123
+ .map((line) => h("span", { class: "code-line" }, line, "\n")),
124
+ ),
125
+ );
126
+ } catch (error) {
127
+ fill(content, h("p", { class: "error-text" }, errorMessage(error)));
128
+ }
129
+ };
130
+
131
+ void api.source(id).then(
132
+ (loaded) => {
133
+ listing = loaded;
134
+ renderTree();
135
+ },
136
+ (error: unknown) =>
137
+ fill(files, h("p", { class: "error-text" }, errorMessage(error))),
138
+ );
139
+
140
+ return {
141
+ element: h("div", { class: "source" }, files, content),
142
+ show,
143
+ };
144
+ };
@@ -0,0 +1,142 @@
1
+ import { existsSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import type { Environment } from "@tsplc/config";
4
+ import {
5
+ createDebugger,
6
+ createDebugHandler,
7
+ type Debugger,
8
+ loadDebugBuild,
9
+ loginReader,
10
+ timelineEntries,
11
+ } from "@tsplc/debug";
12
+ import { debugManifestFile } from "@tsplc/debug/manifest";
13
+ import { errorMessage } from "./errors";
14
+ import { readJsonl } from "./logs";
15
+ import {
16
+ type AgentStatus,
17
+ type Audit,
18
+ auditSchema,
19
+ deploymentSchema,
20
+ } from "./protocol";
21
+ import { loadRelease } from "./releases";
22
+ import { serverEnvironment } from "./secrets";
23
+ import type { AgentState } from "./state";
24
+
25
+ /** Log entries a new debugger starts its timeline with. */
26
+ const recentEntries = 500;
27
+
28
+ interface RunningDebugger {
29
+ debug: Debugger;
30
+ handle: ReturnType<typeof createDebugHandler>;
31
+ }
32
+
33
+ /**
34
+ * The deployed release's debugger, when it has a debug manifest. It reads the controller
35
+ * through the agent's engineering login, and the server's telemetry and requests through the
36
+ * server's health origin.
37
+ */
38
+ export const createDebugging = (context: {
39
+ state: AgentState;
40
+ readLogin: (expressions: string[]) => Promise<Record<string, string>>;
41
+ /** The login's state, with the expressions the controller forces. */
42
+ loginStatus: () => Promise<AgentStatus["login"]>;
43
+ serverHealthUrl: string | null;
44
+ environment: Environment;
45
+ log: (message: string) => void;
46
+ }) => {
47
+ const { state, log } = context;
48
+
49
+ const start = async (): Promise<RunningDebugger | null> => {
50
+ const release = await state.release();
51
+ if (!release) {
52
+ return null;
53
+ }
54
+ const stored = await loadRelease(state.paths.releases, release.id);
55
+ const manifestFile = join(stored.directory, debugManifestFile);
56
+ if (!existsSync(manifestFile)) {
57
+ return null;
58
+ }
59
+ const { serverTokenEnv, debug: settings } = stored.manifest;
60
+ const serverToken =
61
+ serverTokenEnv &&
62
+ (await serverEnvironment(stored, context.environment))[serverTokenEnv];
63
+ const build = await loadDebugBuild(manifestFile);
64
+ const debug = await createDebugger({
65
+ ...build,
66
+ ...loginReader(build.manifest, {
67
+ read: context.readLogin,
68
+ status: context.loginStatus,
69
+ endpoint: "the agent's login",
70
+ }),
71
+ stateDirectory: state.paths.debug,
72
+ watch: settings?.watch ?? {},
73
+ ...(context.serverHealthUrl &&
74
+ serverToken && {
75
+ server: {
76
+ url: new URL(context.serverHealthUrl).origin,
77
+ token: serverToken,
78
+ },
79
+ }),
80
+ release: {
81
+ id: release.id,
82
+ deployedAt: release.deployedAt,
83
+ operation: release.operation,
84
+ },
85
+ timeline: [
86
+ ...(
87
+ await readJsonl(
88
+ state.paths.deployments,
89
+ deploymentSchema,
90
+ recentEntries,
91
+ )
92
+ ).map(({ at, ...deployment }) =>
93
+ timelineEntries.deploy(at, deployment),
94
+ ),
95
+ ...(await readJsonl(state.paths.audit, auditSchema, recentEntries)).map(
96
+ ({ at, ...audit }) => timelineEntries.audit(at, audit),
97
+ ),
98
+ ],
99
+ log,
100
+ });
101
+ return { debug, handle: createDebugHandler(debug, log) };
102
+ };
103
+ const startOrLog = () =>
104
+ start().catch((error: unknown) => {
105
+ log(`Starting the debugger failed: ${errorMessage(error)}`);
106
+ return null;
107
+ });
108
+
109
+ let current = startOrLog();
110
+
111
+ return {
112
+ /** Answers a request under `/debug`, at `route` within it. */
113
+ handle: async (request: Request, route: string) => {
114
+ const debugging = await current;
115
+ if (!debugging) {
116
+ return Response.json(
117
+ {
118
+ error:
119
+ "The deployed release has no debug manifest, or the debugger failed to start",
120
+ },
121
+ { status: 503 },
122
+ );
123
+ }
124
+ return debugging.handle(request, route);
125
+ },
126
+ /** Adds an audited command to the debugger's timeline. */
127
+ record: async ({ at, ...audit }: Audit) => {
128
+ (await current)?.debug.record(timelineEntries.audit(at, audit));
129
+ },
130
+ /** Replaces the debugger after the release changes. */
131
+ restart: () => {
132
+ current = current.then(async (debugging) => {
133
+ await debugging?.debug.close();
134
+ return startOrLog();
135
+ });
136
+ },
137
+ close: async () => {
138
+ await (await current)?.debug.close();
139
+ },
140
+ };
141
+ };
142
+ export type Debugging = ReturnType<typeof createDebugging>;