@tsplc/tmp-agent 0.0.0-stage → 0.6.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/README.md +26 -2
  2. package/dist/cli.js +4888 -0
  3. package/dist/cli.js.map +53 -0
  4. package/dist/client.js +514 -0
  5. package/dist/client.js.map +12 -0
  6. package/dist/index.js +3680 -0
  7. package/dist/index.js.map +41 -0
  8. package/package.json +61 -4
  9. package/src/access.ts +260 -0
  10. package/src/agent.ts +461 -0
  11. package/src/audit.ts +74 -0
  12. package/src/cli.ts +290 -0
  13. package/src/client.ts +407 -0
  14. package/src/codesys.ts +195 -0
  15. package/src/dashboard/index.ts +159 -0
  16. package/src/dashboard/ui/access.ts +191 -0
  17. package/src/dashboard/ui/actions.ts +207 -0
  18. package/src/dashboard/ui/api.ts +138 -0
  19. package/src/dashboard/ui/app.ts +41 -0
  20. package/src/dashboard/ui/approval.ts +131 -0
  21. package/src/dashboard/ui/audit.ts +115 -0
  22. package/src/dashboard/ui/contract.ts +19 -0
  23. package/src/dashboard/ui/dashboard.css +1332 -0
  24. package/src/dashboard/ui/deployment.ts +431 -0
  25. package/src/dashboard/ui/deployments.ts +319 -0
  26. package/src/dashboard/ui/details.ts +214 -0
  27. package/src/dashboard/ui/dom.ts +87 -0
  28. package/src/dashboard/ui/environment.ts +345 -0
  29. package/src/dashboard/ui/format.ts +124 -0
  30. package/src/dashboard/ui/logs.ts +126 -0
  31. package/src/dashboard/ui/main.ts +88 -0
  32. package/src/dashboard/ui/overlay.ts +144 -0
  33. package/src/dashboard/ui/shell.ts +185 -0
  34. package/src/dashboard/ui/source.ts +144 -0
  35. package/src/debugging.ts +142 -0
  36. package/src/deploy.ts +203 -0
  37. package/src/deployments/health.ts +98 -0
  38. package/src/deployments/retention.ts +44 -0
  39. package/src/deployments/routes.ts +281 -0
  40. package/src/deployments/runner.ts +900 -0
  41. package/src/deployments/store.ts +209 -0
  42. package/src/deployments/submission.ts +78 -0
  43. package/src/discovery.ts +90 -0
  44. package/src/environment.ts +214 -0
  45. package/src/errors.ts +12 -0
  46. package/src/index.ts +36 -0
  47. package/src/instance.ts +51 -0
  48. package/src/login.ts +267 -0
  49. package/src/logs.ts +115 -0
  50. package/src/maintenance.ts +303 -0
  51. package/src/operations.ts +149 -0
  52. package/src/processes.ts +41 -0
  53. package/src/protocol.ts +557 -0
  54. package/src/releases.ts +414 -0
  55. package/src/restarts.ts +96 -0
  56. package/src/routes.ts +128 -0
  57. package/src/secrets.ts +174 -0
  58. package/src/server-process.ts +264 -0
  59. package/src/service.ts +194 -0
  60. package/src/sessions.ts +58 -0
  61. package/src/state.ts +126 -0
  62. package/src/tailscale.ts +112 -0
  63. package/src/terminal.ts +57 -0
  64. package/src/transfer.ts +94 -0
  65. package/src/upgrade.ts +153 -0
package/src/login.ts ADDED
@@ -0,0 +1,267 @@
1
+ import { setTimeout as delay } from "node:timers/promises";
2
+ import {
3
+ type ControllerLogin,
4
+ failureReason,
5
+ findControllerLogin,
6
+ type LoginCommand,
7
+ openControllerLogin,
8
+ type ResetKind,
9
+ settleWarmController,
10
+ } from "@tsplc/build";
11
+ import { LoginUnavailable, noLogin } from "@tsplc/debug";
12
+ import type { AuditLog } from "./audit";
13
+ import {
14
+ type CodesysSettings,
15
+ controllerConfig,
16
+ credentialEnvironment,
17
+ deployContainer,
18
+ ensureGateway,
19
+ loginContainer,
20
+ requireBuilder,
21
+ } from "./codesys";
22
+ import { AgentError, errorMessage } from "./errors";
23
+ import type { Operations } from "./operations";
24
+ import type { AgentStatus, ClientIdentity, Credentials } from "./protocol";
25
+ import { controllerCredentials } from "./secrets";
26
+ import type { AgentState } from "./state";
27
+
28
+ /** A login's state comes back within a second; one that takes this long waits on a hung worker. */
29
+ const loginStateTimeout = 30_000;
30
+ const stoppedAnswering = { error: "The login stopped answering" };
31
+
32
+ /** How an audited login command reads in the log, or nothing for commands that only read. */
33
+ const auditOf = (command: LoginCommand) => {
34
+ switch (command.command) {
35
+ case "write":
36
+ case "force":
37
+ return { command: command.command, values: command.values };
38
+ case "unforce":
39
+ return {
40
+ command: command.restore ? "unforce --restore" : "unforce",
41
+ values: Object.fromEntries(
42
+ command.expressions.map((expression) => [expression, ""]),
43
+ ),
44
+ };
45
+ case "start":
46
+ case "stop":
47
+ return { command: command.command, values: {} };
48
+ case "reset":
49
+ return { command: `reset ${command.kind.toLowerCase()}`, values: {} };
50
+ case "state":
51
+ case "read":
52
+ return undefined;
53
+ }
54
+ };
55
+
56
+ /**
57
+ * The agent's engineering login to the controller, which outlives the agent in its own
58
+ * container. Its commands, the debugger's reads among them, run one at a time.
59
+ */
60
+ export const createLogin = (context: {
61
+ state: AgentState;
62
+ operations: Operations;
63
+ codesys: CodesysSettings;
64
+ audit: AuditLog;
65
+ log: (message: string) => void;
66
+ }) => {
67
+ const { state, operations } = context;
68
+ let generation = 0;
69
+ let commands: Promise<unknown> = Promise.resolve();
70
+
71
+ const enqueue = <Result>(run: () => Promise<Result>) => {
72
+ const queuedIn = generation;
73
+ const sent = commands.then(() => {
74
+ if (queuedIn !== generation) {
75
+ throw new AgentError("The login was closed", 409);
76
+ }
77
+ return run();
78
+ });
79
+ commands = sent.catch(() => undefined);
80
+ return sent;
81
+ };
82
+ const send = (login: ControllerLogin, command: LoginCommand) =>
83
+ enqueue(() => login.send(command));
84
+
85
+ const openLogin = async () => {
86
+ const lookedUpIn = generation;
87
+ const login = await findControllerLogin(loginContainer);
88
+ if (lookedUpIn !== generation) {
89
+ throw new AgentError("The login was closed", 409);
90
+ }
91
+ if (!login) {
92
+ throw new AgentError("No login is open: tsplc login", 409);
93
+ }
94
+ return login;
95
+ };
96
+ /** The open login, for a command that runs while no operation does. */
97
+ const requireLogin = async () => {
98
+ operations.requireIdle();
99
+ const login = await openLogin();
100
+ operations.requireIdle();
101
+ return login;
102
+ };
103
+
104
+ /** Whether a login's container runs, open or opening. */
105
+ const isOpen = async () =>
106
+ (await findControllerLogin(loginContainer)) !== undefined;
107
+
108
+ return {
109
+ /** What the debugger reads through: the open login, which it never opens itself. */
110
+ read: async ([first, ...rest]: string[]) => {
111
+ const busy = operations.busy();
112
+ if (busy === "a login") {
113
+ throw new LoginUnavailable("The engineering login is opening", {
114
+ state: "connecting",
115
+ });
116
+ }
117
+ if (busy) {
118
+ throw new LoginUnavailable(`Live values pause during ${busy}`);
119
+ }
120
+ const login = await findControllerLogin(loginContainer);
121
+ if (!login) {
122
+ throw new LoginUnavailable(noLogin);
123
+ }
124
+ if (!first) {
125
+ return {};
126
+ }
127
+ const result = await send(login, {
128
+ command: "read",
129
+ expressions: [first, ...rest],
130
+ });
131
+ if (!("values" in result)) {
132
+ throw new Error("The login answered a read without values");
133
+ }
134
+ return result.values;
135
+ },
136
+
137
+ open: async (sent: Credentials | null) => {
138
+ operations.requireIdle();
139
+ await requireBuilder();
140
+ const credentials = await controllerCredentials(sent);
141
+ context.log(
142
+ `Opening a login with the ${sent ? "provided" : "stored"} controller user`,
143
+ );
144
+ const config = controllerConfig(
145
+ await state.requireRelease(),
146
+ await state.requireTarget(),
147
+ state.paths.controller,
148
+ context.codesys,
149
+ );
150
+ return operations.stream("a login", async (emit) => {
151
+ if (await isOpen()) {
152
+ throw new AgentError("A login is already open", 409);
153
+ }
154
+ // The login opens the committed download, which the last deployment may still be saving.
155
+ await settleWarmController(config, deployContainer);
156
+ emit({
157
+ kind: "progress",
158
+ message: "Logging in; CODESYS takes minutes to start",
159
+ });
160
+ await ensureGateway();
161
+ const login = await openControllerLogin(config, loginContainer, {
162
+ environment: credentialEnvironment(credentials),
163
+ });
164
+ return send(login, { command: "state" });
165
+ });
166
+ },
167
+
168
+ /** Runs a login command; one that changes the controller goes to the audit log, with the values it replaces. */
169
+ command: async (command: LoginCommand, client: ClientIdentity) => {
170
+ const login = await requireLogin();
171
+ const change = auditOf(command);
172
+ if (!change) {
173
+ return send(login, command);
174
+ }
175
+ return enqueue(async () => {
176
+ const [first, ...rest] = Object.keys(change.values);
177
+ // Without the old values the command is still worth running and recording.
178
+ const previous = first
179
+ ? await login
180
+ .send({ command: "read", expressions: [first, ...rest] })
181
+ .then((result) =>
182
+ "values" in result ? result.values : undefined,
183
+ )
184
+ .catch(() => undefined)
185
+ : undefined;
186
+ const audit = async (error: string | null) =>
187
+ context.audit.record({
188
+ by: { ...client, release: (await state.release())?.id },
189
+ ...change,
190
+ previous: previous ?? null,
191
+ error,
192
+ });
193
+ try {
194
+ const result = await login.send(command);
195
+ await audit(null);
196
+ return result;
197
+ } catch (error) {
198
+ await audit(errorMessage(error));
199
+ throw error;
200
+ }
201
+ });
202
+ },
203
+
204
+ /**
205
+ * Resets the application through the open login and starts it again, as `tsplc reset` then
206
+ * `tsplc start` do, for a caller that holds the agent's one operation. Returns the state it
207
+ * runs in.
208
+ */
209
+ restart: async (reset: ResetKind) => {
210
+ const login = await openLogin();
211
+ return enqueue(async () => {
212
+ await login.send({ command: "reset", kind: reset });
213
+ const started = await login.send({ command: "start" });
214
+ if (!("state" in started)) {
215
+ throw new Error("The login answered a start without the state");
216
+ }
217
+ return { state: started.state };
218
+ });
219
+ },
220
+
221
+ isOpen,
222
+
223
+ /**
224
+ * The open login's state. A login that lost the controller, or whose worker died or hangs, is
225
+ * reported as failed, so the CLI can log it out and open a new one.
226
+ */
227
+ status: async (): Promise<AgentStatus["login"]> => {
228
+ const login = await findControllerLogin(loginContainer);
229
+ if (!login) {
230
+ return null;
231
+ }
232
+ // A login still opening has its container but doesn't answer yet.
233
+ if (!(await login.ready())) {
234
+ return operations.busy() === "a login" ? null : stoppedAnswering;
235
+ }
236
+ try {
237
+ const loginState = await Promise.race([
238
+ send(login, { command: "state" }),
239
+ delay(loginStateTimeout, null),
240
+ ]);
241
+ if (!loginState) {
242
+ return stoppedAnswering;
243
+ }
244
+ return "state" in loginState ? loginState : null;
245
+ } catch (error) {
246
+ return { error: failureReason(error) };
247
+ }
248
+ },
249
+
250
+ /** Logs out, cancelling queued commands; a replacement login starts with an empty queue. */
251
+ logout: async () => {
252
+ const login = await requireLogin();
253
+ return operations.exclusive("a logout", async () => {
254
+ generation++;
255
+ const failure = await login.close();
256
+ commands = Promise.resolve();
257
+ if (failure) {
258
+ context.log(
259
+ `The login couldn't log out (${failure}); its container was removed`,
260
+ );
261
+ }
262
+ return failure ? { failure } : {};
263
+ });
264
+ },
265
+ };
266
+ };
267
+ export type Login = ReturnType<typeof createLogin>;
package/src/logs.ts ADDED
@@ -0,0 +1,115 @@
1
+ import {
2
+ closeSync,
3
+ existsSync,
4
+ openSync,
5
+ renameSync,
6
+ statSync,
7
+ writeSync,
8
+ } from "node:fs";
9
+ import { open } from "node:fs/promises";
10
+ import { z } from "zod";
11
+ import { readTextIfPresent } from "./state";
12
+
13
+ /** Renames `file` to `<file>.1`, replacing the one before, once it reaches `bytes`. */
14
+ const rotateLog = (file: string, bytes: number) => {
15
+ if (existsSync(file) && statSync(file).size >= bytes) {
16
+ renameSync(file, `${file}.1`);
17
+ }
18
+ };
19
+
20
+ /** A process's output log rotates when a process starts into it past this size. */
21
+ const outputLogBytes = 10 * 2 ** 20;
22
+
23
+ /** Starts `command` with its output appended to `log`, rotating the log first. */
24
+ export const spawnWithLog = (
25
+ command: string[],
26
+ log: string,
27
+ options: Pick<
28
+ Bun.SpawnOptions.SpawnOptions<"ignore", number, number>,
29
+ "cwd" | "env" | "detached" | "windowsHide"
30
+ > & {
31
+ /** Written to the log after it rotates and before the process's output. */
32
+ heading?: string;
33
+ },
34
+ ) => {
35
+ const { heading, ...spawnOptions } = options;
36
+ rotateLog(log, outputLogBytes);
37
+ const output = openSync(log, "a");
38
+ try {
39
+ if (heading) {
40
+ writeSync(output, heading);
41
+ }
42
+ return Bun.spawn(command, {
43
+ ...spawnOptions,
44
+ stdio: ["ignore", output, output],
45
+ });
46
+ } finally {
47
+ closeSync(output);
48
+ }
49
+ };
50
+
51
+ /** Appends one JSON line to `file`, on a line of its own after any partial line a crash left. */
52
+ export const appendJsonLine = async (file: string, value: unknown) => {
53
+ const log = await open(file, "a+");
54
+ try {
55
+ const { size } = await log.stat();
56
+ const last = Buffer.alloc(1);
57
+ if (size) {
58
+ await log.read(last, 0, 1, size - 1);
59
+ }
60
+ const separator = size && last[0] !== 10 ? "\n" : "";
61
+ await log.writeFile(`${separator}${JSON.stringify(value)}\n`);
62
+ } finally {
63
+ await log.close();
64
+ }
65
+ };
66
+
67
+ /** An append-only log rotates once it reaches this size. */
68
+ const appendOnlyBytes = 5 * 2 ** 20;
69
+
70
+ /** Appends one JSON line to an append-only log, keeping it and its rotated copy bounded. */
71
+ export const appendJsonl = async (file: string, value: unknown) => {
72
+ rotateLog(file, appendOnlyBytes);
73
+ await appendJsonLine(file, value);
74
+ };
75
+
76
+ export const parsesAsJson = (line: string): { json: unknown } | null => {
77
+ try {
78
+ return { json: JSON.parse(line) };
79
+ } catch {
80
+ return null;
81
+ }
82
+ };
83
+
84
+ /**
85
+ * The newest `limit` lines of a log, oldest first. A line a crash left half written isn't JSON
86
+ * and is skipped; a whole line its schema refuses is an error.
87
+ */
88
+ export const readJsonl = async <T>(
89
+ file: string,
90
+ schema: z.ZodType<T>,
91
+ limit: number,
92
+ ) => {
93
+ const text = await readTextIfPresent(file);
94
+ if (text === null) {
95
+ return [];
96
+ }
97
+ return text
98
+ .split("\n")
99
+ .map((line, index) => ({ line, number: index + 1 }))
100
+ .filter(({ line }) => line)
101
+ .slice(-limit)
102
+ .flatMap(({ line, number }) => {
103
+ const parsed = parsesAsJson(line);
104
+ if (!parsed) {
105
+ return [];
106
+ }
107
+ const entry = schema.safeParse(parsed.json);
108
+ if (!entry.success) {
109
+ throw new Error(
110
+ `Line ${number} of ${file} isn't a valid entry: ${z.prettifyError(entry.error)}`,
111
+ );
112
+ }
113
+ return [entry.data];
114
+ });
115
+ };
@@ -0,0 +1,303 @@
1
+ import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
2
+ import { homedir, tmpdir } from "node:os";
3
+ import { join, resolve } from "node:path";
4
+ import { agentTokenEnv, type Environment } from "@tsplc/config";
5
+ import { z } from "zod";
6
+ import { createAgentClient } from "./client";
7
+ import {
8
+ type AgentControl,
9
+ answeringVersion,
10
+ type Instance,
11
+ runningAgent,
12
+ } from "./instance";
13
+ import { spawnWithLog } from "./logs";
14
+ import { processAlive, waitUntil } from "./processes";
15
+ import { agentSetting } from "./secrets";
16
+ import { schtasks, superviseAgent, taskDefinition, taskFile } from "./service";
17
+ import { openState } from "./state";
18
+ import {
19
+ installCommand,
20
+ npmCommand,
21
+ packageManagerFor,
22
+ upgradeAgent,
23
+ } from "./upgrade";
24
+
25
+ /** The installed agent package, one directory above its source modules and its bundle alike. */
26
+ const agentPackage = resolve(import.meta.dir, "..");
27
+
28
+ /** The version of the agent package installed now, which an upgrade may have changed under this process. */
29
+ const installedVersion = async () =>
30
+ z
31
+ .object({ version: z.string() })
32
+ .parse(
33
+ JSON.parse(await readFile(join(agentPackage, "package.json"), "utf8")),
34
+ ).version;
35
+
36
+ /** How long a new agent may take to answer, and an old one to exit. */
37
+ const answerWithinMs = 180_000;
38
+ const exitWithinMs = 60_000;
39
+
40
+ const run = (command: string[]) =>
41
+ Bun.spawn(command, { stdio: ["inherit", "inherit", "inherit"] }).exited;
42
+
43
+ const quietly = (command: string[]) =>
44
+ Bun.spawn(command, { stdio: ["ignore", "ignore", "ignore"] }).exited;
45
+
46
+ /** What `command` prints, or null when it fails or isn't installed. */
47
+ const capture = async (command: string[]) => {
48
+ try {
49
+ const child = Bun.spawn(command, { stdio: ["ignore", "pipe", "ignore"] });
50
+ const [output, status] = await Promise.all([
51
+ new Response(child.stdout).text(),
52
+ child.exited,
53
+ ]);
54
+ return status === 0 ? output.trim() : null;
55
+ } catch {
56
+ return null;
57
+ }
58
+ };
59
+
60
+ /** The command that runs this agent's CLI with `args`, on the Bun running it now. */
61
+ const agentCommand = (...args: string[]) => [
62
+ process.execPath,
63
+ Bun.main,
64
+ ...args,
65
+ ];
66
+
67
+ /** The control routes of `instance`, which need its full token. */
68
+ const controlOf = async (
69
+ instance: Instance,
70
+ environment: Environment,
71
+ ): Promise<AgentControl> => {
72
+ const token = await agentSetting(agentTokenEnv, environment);
73
+ if (!token) {
74
+ throw new Error(
75
+ `tsplc-agent ${instance.version} is running, and holding it needs its token: set ${agentTokenEnv}, or store it with tsplc-agent secrets set ${agentTokenEnv} as the user the agent runs as`,
76
+ );
77
+ }
78
+ return createAgentClient({ url: instance.url, token });
79
+ };
80
+
81
+ /** The running agent and its control routes. */
82
+ const controlRunning = async (agentFile: string, environment: Environment) => {
83
+ const instance = await runningAgent(agentFile);
84
+ return (
85
+ instance && { instance, control: await controlOf(instance, environment) }
86
+ );
87
+ };
88
+
89
+ const waitForExit = async (instance: Instance) => {
90
+ if (
91
+ !(await waitUntil(async () => !processAlive(instance.pid), exitWithinMs))
92
+ ) {
93
+ throw new Error(
94
+ `tsplc-agent (process ${instance.pid}) didn't exit within ${exitWithinMs / 1000} s`,
95
+ );
96
+ }
97
+ };
98
+
99
+ /** Whether the agent recorded in `agentFile` runs `version` and answers. */
100
+ const answers = (agentFile: string, version: string) =>
101
+ waitUntil(async () => {
102
+ const instance = await runningAgent(agentFile);
103
+ return (
104
+ instance?.version === version &&
105
+ (await answeringVersion(instance.url)) === version
106
+ );
107
+ }, answerWithinMs);
108
+
109
+ /** `tsplc-agent upgrade [version]`. */
110
+ export const upgradeCommand = async (options: {
111
+ version: string;
112
+ state: string;
113
+ environment: Environment;
114
+ }) => {
115
+ const state = await openState(options.state);
116
+ const manager =
117
+ packageManagerFor(agentPackage, null) ??
118
+ packageManagerFor(
119
+ agentPackage,
120
+ await capture(npmCommand(process.platform, "root", "--global")),
121
+ );
122
+ if (!manager) {
123
+ throw new Error(
124
+ `This agent runs from ${agentPackage}, which isn't a global bun or npm install; upgrade it the way it was installed`,
125
+ );
126
+ }
127
+ await upgradeAgent(
128
+ {
129
+ version: options.version,
130
+ install: installCommand(manager, options.version, {
131
+ bun: process.execPath,
132
+ platform: process.platform,
133
+ }),
134
+ setup: agentCommand("setup", "--if-needed"),
135
+ running: await controlRunning(state.paths.agent, options.environment),
136
+ agentLog: state.paths.agentLog,
137
+ },
138
+ {
139
+ run,
140
+ installedVersion,
141
+ startAgent: async (instance) => {
142
+ await waitForExit(instance);
143
+ spawnWithLog(
144
+ agentCommand("serve", ...instance.serve),
145
+ state.paths.agentLog,
146
+ { detached: true, windowsHide: true },
147
+ ).unref();
148
+ },
149
+ startService: async () =>
150
+ process.platform === "win32" &&
151
+ (await quietly(schtasks.query())) === 0 &&
152
+ (await run(schtasks.run())) === 0,
153
+ answers: (version) => answers(state.paths.agent, version),
154
+ print: (line) => console.log(line),
155
+ },
156
+ );
157
+ };
158
+
159
+ const requireWindows = () => {
160
+ if (process.platform !== "win32") {
161
+ throw new Error(
162
+ "tsplc-agent service registers a Windows Task Scheduler task. Elsewhere, have your init system run tsplc-agent service run with the serve options, such as a systemd unit",
163
+ );
164
+ }
165
+ };
166
+
167
+ const releasing = async <T>(
168
+ running: { control: AgentControl } | null,
169
+ step: () => Promise<T>,
170
+ ) =>
171
+ step().catch(async (error: unknown) => {
172
+ await running?.control.releaseHold();
173
+ throw error;
174
+ });
175
+
176
+ /** `tsplc-agent service install|uninstall|status|run`. */
177
+ export const serviceCommand = async (options: {
178
+ action: string | undefined;
179
+ state: string;
180
+ /** The serve options the service runs the agent with. */
181
+ serve: string[];
182
+ stopServer: boolean;
183
+ environment: Environment;
184
+ }) => {
185
+ const state = await openState(options.state);
186
+ const logs = `The agent's log is ${state.paths.agentLog}; the line's server's is ${state.paths.serverLog}`;
187
+ switch (options.action) {
188
+ case "run":
189
+ await superviseAgent({
190
+ command: agentCommand("serve", ...options.serve),
191
+ log: state.paths.agentLog,
192
+ environment: options.environment,
193
+ });
194
+ return;
195
+ case "install": {
196
+ requireWindows();
197
+ const { USERDOMAIN, USERNAME } = options.environment;
198
+ if (!USERNAME) {
199
+ throw new Error(
200
+ "USERNAME isn't set, so the service has no user to run as",
201
+ );
202
+ }
203
+ const user = [USERDOMAIN, USERNAME].filter(Boolean).join("\\");
204
+ const running = await controlRunning(
205
+ state.paths.agent,
206
+ options.environment,
207
+ );
208
+ await running?.control.hold();
209
+ await releasing(running, async () => {
210
+ const directory = await mkdtemp(join(tmpdir(), "tsplc-agent-service-"));
211
+ try {
212
+ const file = join(directory, "task.xml");
213
+ await writeFile(
214
+ file,
215
+ taskFile(
216
+ taskDefinition({
217
+ bun: process.execPath,
218
+ script: Bun.main,
219
+ serve: options.serve,
220
+ user,
221
+ workingDirectory: homedir(),
222
+ }),
223
+ ),
224
+ );
225
+ console.log(
226
+ `Registering the ${user} service; schtasks asks for ${user}'s Windows password, which Task Scheduler keeps to start the agent at boot`,
227
+ );
228
+ if ((await run(schtasks.create(file, user))) !== 0) {
229
+ throw new Error(
230
+ "Registering the service failed. Run tsplc-agent service install in a PowerShell opened with Run as administrator, signed in as the user the agent runs as",
231
+ );
232
+ }
233
+ } finally {
234
+ await rm(directory, { recursive: true, force: true });
235
+ }
236
+ });
237
+ if (running) {
238
+ console.log(
239
+ `Handing over from tsplc-agent ${running.instance.version} (process ${running.instance.pid}); the line's server keeps running`,
240
+ );
241
+ await running.control.exit({ server: "leave", restart: false });
242
+ await waitForExit(running.instance);
243
+ }
244
+ if ((await run(schtasks.run())) !== 0) {
245
+ throw new Error("The service is registered but didn't start");
246
+ }
247
+ const version = await installedVersion();
248
+ if (!(await answers(state.paths.agent, version))) {
249
+ throw new Error(
250
+ `The service started but tsplc-agent ${version} doesn't answer. ${logs}`,
251
+ );
252
+ }
253
+ console.log(
254
+ `The tsplc-agent service runs tsplc-agent ${version} at boot as ${user}, and starts it again if it exits. ${logs}`,
255
+ );
256
+ return;
257
+ }
258
+ case "uninstall": {
259
+ requireWindows();
260
+ const running = await runningAgent(state.paths.agent);
261
+ if (running?.supervised) {
262
+ const control = await controlOf(running, options.environment);
263
+ await control.hold();
264
+ await control.exit({
265
+ server: options.stopServer ? "stop" : "leave",
266
+ restart: false,
267
+ });
268
+ await waitForExit(running);
269
+ } else {
270
+ // A service waiting to start the agent again is stopped instead.
271
+ await quietly(schtasks.end());
272
+ }
273
+ if ((await run(schtasks.remove())) !== 0) {
274
+ throw new Error(
275
+ "Removing the service failed. Run it in a PowerShell opened with Run as administrator",
276
+ );
277
+ }
278
+ console.log(
279
+ options.stopServer || !running?.supervised
280
+ ? "Removed the tsplc-agent service"
281
+ : "Removed the tsplc-agent service. The line's server keeps running; the next tsplc-agent serve takes it over",
282
+ );
283
+ return;
284
+ }
285
+ case "status": {
286
+ if (process.platform === "win32" && (await run(schtasks.query())) !== 0) {
287
+ console.log("The tsplc-agent service isn't installed");
288
+ }
289
+ const running = await runningAgent(state.paths.agent);
290
+ console.log(
291
+ running
292
+ ? `tsplc-agent ${running.version} runs as process ${running.pid} at ${running.url}${running.supervised ? ", under the service" : ""}, since ${running.startedAt}`
293
+ : "No tsplc-agent is running",
294
+ );
295
+ console.log(logs);
296
+ return;
297
+ }
298
+ default:
299
+ throw new Error(
300
+ "Usage: tsplc-agent service install|uninstall|status|run [serve options]",
301
+ );
302
+ }
303
+ };