@tsplc/agent 0.4.4 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tsplc/agent",
3
- "version": "0.4.4",
3
+ "version": "0.5.1",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "description": "The tsPLC plant agent: deploys a program and its server to a controller on the plant network, and holds an engineering login for reads, writes and forces.",
@@ -42,10 +42,10 @@
42
42
  "bun": ">=1.4.3"
43
43
  },
44
44
  "dependencies": {
45
- "@tsplc/build": "0.4.4",
46
- "@tsplc/config": "0.4.4",
47
- "@tsplc/debug": "0.4.4",
48
- "@tsplc/iec": "0.4.4",
45
+ "@tsplc/build": "0.5.1",
46
+ "@tsplc/config": "0.5.1",
47
+ "@tsplc/debug": "0.5.1",
48
+ "@tsplc/iec": "0.5.1",
49
49
  "zod": "4.3.6"
50
50
  },
51
51
  "bin": {
package/src/agent.ts CHANGED
@@ -2,11 +2,12 @@ import { timingSafeEqual } from "node:crypto";
2
2
  import { join } from "node:path";
3
3
  import { loginCommandSchema } from "@tsplc/build";
4
4
  import { z } from "zod";
5
- import type { CodesysSettings } from "./codesys";
5
+ import { type CodesysSettings, describeBuilder } from "./codesys";
6
6
  import { createDebugging } from "./debugging";
7
7
  import { createDeployments } from "./deploy";
8
8
  import { discoverControllers, networkInterfaces } from "./discovery";
9
9
  import { AgentError, errorMessage } from "./errors";
10
+ import { type AgentExit, exitSchema } from "./instance";
10
11
  import { createLogin } from "./login";
11
12
  import { createOperations } from "./operations";
12
13
  import {
@@ -44,6 +45,11 @@ export interface AgentOptions {
44
45
  /** Experimental: downloads without a baseline import their POUs in one PLCopenXML import. */
45
46
  bulkImport?: boolean;
46
47
  log: (message: string) => void;
48
+ /**
49
+ * Ends this process once `POST /agent/exit` has been answered, after the agent has stopped or
50
+ * left the line's server as asked.
51
+ */
52
+ exit: (exit: AgentExit) => void;
47
53
  }
48
54
 
49
55
  /** The plant agent's routes. It runs one deployment or login operation at a time. */
@@ -52,12 +58,18 @@ export const createAgent = async (options: AgentOptions) => {
52
58
  const state = await openState(options.state);
53
59
  const server = createServerSupervisor({
54
60
  healthUrl: options.serverHealthUrl,
61
+ record: state.paths.server,
62
+ output: state.paths.serverLog,
55
63
  log,
56
64
  });
57
65
  const deployed = await state.release();
58
66
  if (deployed?.server) {
59
- server.start(join(state.paths.releases, deployed.server));
67
+ await server.resume(join(state.paths.releases, deployed.server));
60
68
  }
69
+ // Whether deployments can run, said once at start; each deployment and login checks again.
70
+ void describeBuilder().then(log, (error: unknown) =>
71
+ log(`Can't check the CODESYS builder image yet: ${errorMessage(error)}`),
72
+ );
61
73
  const operations = createOperations(log);
62
74
  const codesys: CodesysSettings = { bulkImport: options.bulkImport ?? false };
63
75
  const releases = createReleaseStore(state.paths.releases);
@@ -150,6 +162,42 @@ export const createAgent = async (options: AgentOptions) => {
150
162
  );
151
163
  case "DELETE /login":
152
164
  return Response.json(await login.logout());
165
+ case "POST /agent/hold": {
166
+ operations.hold();
167
+ try {
168
+ // A login's container outlives the agent and runs the code it started with.
169
+ if (await login.isOpen()) {
170
+ throw new AgentError(
171
+ "A login is open; log out before upgrading the agent: tsplc logout",
172
+ 409,
173
+ );
174
+ }
175
+ await deployments.retire();
176
+ } catch (error) {
177
+ operations.release();
178
+ throw error;
179
+ }
180
+ return Response.json({ held: true });
181
+ }
182
+ case "DELETE /agent/hold":
183
+ operations.release();
184
+ return Response.json({ held: false });
185
+ case "POST /agent/exit": {
186
+ const exit = exitSchema.parse(await request.json());
187
+ if (!operations.held()) {
188
+ throw new AgentError(
189
+ "Hold the agent before it exits, so no operation is cut short",
190
+ 409,
191
+ );
192
+ }
193
+ // Answered first: the caller waits for this process to end.
194
+ setTimeout(() => {
195
+ void (exit.server === "leave" ? leave() : stop()).then(() =>
196
+ options.exit(exit),
197
+ );
198
+ }, 100);
199
+ return Response.json({ exiting: true });
200
+ }
153
201
  default:
154
202
  return Response.json({ error: `No route ${key}` }, { status: 404 });
155
203
  }
@@ -210,6 +258,17 @@ export const createAgent = async (options: AgentOptions) => {
210
258
  }
211
259
  };
212
260
 
261
+ /** Stops the debugger and the supervised server; a login container keeps running for the next agent. */
262
+ const stop = async () => {
263
+ await debugging.close();
264
+ await server.stop();
265
+ };
266
+ /** Stops the debugger and leaves the server running for the agent that replaces this one. */
267
+ const leave = async () => {
268
+ await debugging.close();
269
+ server.leave();
270
+ };
271
+
213
272
  return {
214
273
  /** Answers `request`, naming the agent's tsPLC version so a client can refuse a mismatched agent. */
215
274
  fetch: async (request: Request) => {
@@ -223,10 +282,7 @@ export const createAgent = async (options: AgentOptions) => {
223
282
  headers,
224
283
  });
225
284
  },
226
- /** Stops the debugger and the supervised server; a login container keeps running for the next agent. */
227
- stop: async () => {
228
- await debugging.close();
229
- await server.stop();
230
- },
285
+ stop,
286
+ leave,
231
287
  };
232
288
  };
package/src/cli.ts CHANGED
@@ -6,18 +6,31 @@ import { configureDocker, configureGateway } from "@tsplc/build";
6
6
  import { tcpPort } from "@tsplc/config/build";
7
7
  import { z } from "zod";
8
8
  import { createAgent } from "./agent.ts";
9
+ import { removeInstance, restartStatus, writeInstance } from "./instance.ts";
10
+ import { serviceCommand, upgradeCommand } from "./maintenance.ts";
11
+ import { tsplcVersion } from "./protocol.ts";
9
12
  import {
10
13
  agentService,
11
14
  agentSetting,
12
15
  controllerSecretNames,
13
16
  } from "./secrets.ts";
17
+ import { supervisedEnv } from "./service.ts";
18
+ import { openState } from "./state.ts";
14
19
  import { askCredentials, askSecret } from "./terminal.ts";
20
+ import { versionSchema } from "./upgrade.ts";
15
21
 
16
- const usage = `tsplc-agent setup|serve [--listen host:port] [--state directory] [--server-health url] [--bulk-import]
22
+ const usage = `tsplc-agent setup [--if-needed]
23
+ tsplc-agent serve --listen host:port [--state directory] [--server-health url] [--bulk-import]
24
+ tsplc-agent upgrade [version] [--state directory]
25
+ tsplc-agent service install|uninstall|status [serve options] [--stop-server]
17
26
  tsplc-agent secrets set|delete <name> [--service ${agentService}]
18
27
  tsplc-agent secrets set-controller
19
28
 
20
- setup Builds the CODESYS builder and gateway images. Run it once, and after updating tsPLC.
29
+ setup Builds the CODESYS builder and gateway images, keeping each that is already right for
30
+ this tsPLC. Builder containers run the installed tsPLC's code and CODESYS scripts, so
31
+ only a release that changes the image's recipe (the CODESYS installation, Bun or the
32
+ container's third-party packages) needs it; the agent says so when it does. --if-needed
33
+ also keeps an image from before tsPLC 0.5.0 whose packages match.
21
34
  serve Serves deployments and logins. --listen is required: use the machine's Tailscale
22
35
  address, such as 100.101.102.103:4850. TSPLC_AGENT_TOKEN must hold a shared secret of
23
36
  at least 32 characters, such as one from \`openssl rand -hex 32\`. An optional
@@ -25,6 +38,17 @@ serve Serves deployments and logins. --listen is required: use the machine's T
25
38
  Each comes from its environment variable, or else from \`secrets set\` under ${agentService}.
26
39
  --bulk-import (experimental) brings a download without a baseline's POUs into CODESYS
27
40
  in one PLCopenXML import, importing one at a time if CODESYS reports any problem.
41
+ The line's server writes to logs/server.log in the state directory.
42
+ upgrade Installs @tsplc/agent at version (latest by default) with the bun or npm that installed
43
+ this one, runs its setup if it needs one, and restarts the running agent on it. It
44
+ refuses while a deployment runs or a login is open, and leaves the line's server running
45
+ and the controller untouched.
46
+ service Runs the agent as a Windows service: a Task Scheduler task that starts it at boot as
47
+ you, whether or not anyone logs on, and starts it again if it exits. install takes the
48
+ serve options and asks for your Windows password; run install and uninstall in a
49
+ PowerShell opened with Run as administrator, signed in as the user the agent runs as.
50
+ The agent's output goes to logs/agent.log in the state directory. uninstall leaves the
51
+ line's server running unless --stop-server.
28
52
  secrets Stores a value a release's secrets name, typed without echo, in Bun.secrets under
29
53
  --service, or deletes it. set-controller stores the controller user, which deployments
30
54
  and logins then use when they send none. Run it as the user the agent runs as.`;
@@ -38,6 +62,8 @@ const { values, positionals } = parseArgs({
38
62
  "server-health": { type: "string" },
39
63
  "bulk-import": { type: "boolean" },
40
64
  service: { type: "string" },
65
+ "if-needed": { type: "boolean" },
66
+ "stop-server": { type: "boolean" },
41
67
  },
42
68
  });
43
69
  const [command, ...args] = positionals;
@@ -45,18 +71,43 @@ if (!command || values.help) {
45
71
  console.log(usage);
46
72
  process.exit(0);
47
73
  }
48
- if (command !== "secrets" && args.length) {
49
- throw new Error("Specify one command.");
74
+ const takesArguments: Record<string, number> = {
75
+ secrets: 3,
76
+ upgrade: 1,
77
+ service: 1,
78
+ };
79
+ if (args.length > (takesArguments[command] ?? 0)) {
80
+ throw new Error(`Too many arguments for ${command}. See tsplc-agent --help.`);
50
81
  }
51
- if (command === "setup") {
52
- await configureDocker();
53
- await configureGateway();
54
- } else if (command === "serve") {
82
+ const stateDirectory = values.state ?? join(homedir(), ".tsplc-agent");
83
+
84
+ /** The serve options as given, which the service and an upgraded agent repeat. */
85
+ const serveOptions = () => {
55
86
  const [, hostname, portText] = /^(.+):(\d+)$/.exec(values.listen ?? "") ?? [];
56
87
  const port = tcpPort.safeParse(Number(portText));
57
88
  if (!hostname || !port.success) {
58
89
  throw new Error("--listen host:port is required, with a TCP port.");
59
90
  }
91
+ return {
92
+ hostname,
93
+ port: port.data,
94
+ args: [
95
+ "--listen",
96
+ `${hostname}:${port.data}`,
97
+ ...(values.state ? ["--state", values.state] : []),
98
+ ...(values["server-health"]
99
+ ? ["--server-health", values["server-health"]]
100
+ : []),
101
+ ...(values["bulk-import"] ? ["--bulk-import"] : []),
102
+ ],
103
+ };
104
+ };
105
+
106
+ if (command === "setup") {
107
+ await configureDocker({ keepUnverified: values["if-needed"] ?? false });
108
+ await configureGateway();
109
+ } else if (command === "serve") {
110
+ const { hostname, port, args: serve } = serveOptions();
60
111
  const token = z
61
112
  .string({
62
113
  error:
@@ -73,29 +124,59 @@ if (command === "setup") {
73
124
  )
74
125
  .optional()
75
126
  .parse(await agentSetting("TSPLC_AGENT_READ_TOKEN"));
127
+ const { paths } = await openState(stateDirectory);
76
128
  const agent = await createAgent({
77
- state: values.state ?? join(homedir(), ".tsplc-agent"),
129
+ state: stateDirectory,
78
130
  token,
79
131
  readToken,
80
132
  serverHealthUrl: values["server-health"],
81
133
  bulkImport: values["bulk-import"] ?? false,
82
134
  environment: process.env,
83
135
  log: (message) => console.log(`${new Date().toISOString()} ${message}`),
136
+ exit: ({ restart }) => {
137
+ void removeInstance(paths.agent, process.pid).then(() =>
138
+ process.exit(restart ? restartStatus : 0),
139
+ );
140
+ },
84
141
  });
85
142
  const server = Bun.serve({
86
143
  hostname,
87
- port: port.data,
144
+ port,
88
145
  fetch: agent.fetch,
89
146
  // Deployments stream for minutes and upload a server executable.
90
147
  idleTimeout: 0,
91
148
  maxRequestBodySize: 2 ** 30,
92
149
  });
93
- console.log(`tsPLC agent listening on ${server.url}`);
150
+ await writeInstance(paths.agent, {
151
+ pid: process.pid,
152
+ version: tsplcVersion,
153
+ url: server.url.href,
154
+ serve,
155
+ supervised: process.env[supervisedEnv] === "1",
156
+ startedAt: new Date().toISOString(),
157
+ });
158
+ console.log(`tsPLC agent ${tsplcVersion} listening on ${server.url}`);
94
159
  for (const signal of ["SIGINT", "SIGTERM"] as const) {
95
160
  process.on(signal, () => {
96
- void agent.stop().then(() => process.exit(0));
161
+ void agent
162
+ .stop()
163
+ .then(() => removeInstance(paths.agent, process.pid))
164
+ .then(() => process.exit(0));
97
165
  });
98
166
  }
167
+ } else if (command === "upgrade") {
168
+ await upgradeCommand({
169
+ version: versionSchema.parse(args[0] ?? "latest"),
170
+ state: stateDirectory,
171
+ });
172
+ } else if (command === "service") {
173
+ const action = args[0];
174
+ await serviceCommand({
175
+ action,
176
+ state: stateDirectory,
177
+ serve: action === "install" || action === "run" ? serveOptions().args : [],
178
+ stopServer: values["stop-server"] ?? false,
179
+ });
99
180
  } else if (command === "secrets") {
100
181
  const [action, name, ...extra] = args;
101
182
  const service = values.service ?? agentService;
package/src/client.ts CHANGED
@@ -26,6 +26,7 @@ import {
26
26
  type Target,
27
27
  targetSchema,
28
28
  tsplcVersion,
29
+ upgradesItself,
29
30
  variableSchema,
30
31
  versionMismatch,
31
32
  } from "./protocol";
@@ -178,7 +179,11 @@ export const createAgentClient = (options: { url: string; token: string }) => {
178
179
  );
179
180
  if (agentVersion !== tsplcVersion) {
180
181
  throw new AgentOperationError(
181
- versionMismatch({ agent: agentVersion, client: tsplcVersion }),
182
+ versionMismatch({
183
+ agent: agentVersion,
184
+ client: tsplcVersion,
185
+ agentUpgrades: upgradesItself(agentVersion),
186
+ }),
182
187
  );
183
188
  }
184
189
  const files = await Promise.all(
package/src/codesys.ts CHANGED
@@ -1,6 +1,12 @@
1
1
  import { join } from "node:path";
2
- import { captureDocker, gatewayImage } from "@tsplc/build";
2
+ import {
3
+ builderImageStatus,
4
+ captureDocker,
5
+ gatewayImage,
6
+ setupReason,
7
+ } from "@tsplc/build";
3
8
  import { resolveConfig } from "@tsplc/config/build";
9
+ import { AgentError, errorMessage } from "./errors";
4
10
  import type { Credentials, Target } from "./protocol";
5
11
  import type { StoredRelease } from "./releases";
6
12
 
@@ -22,6 +28,11 @@ const gateway = { host: "tsplc-agent-gateway", port: 1217 };
22
28
  export const loginContainer = "tsplc-agent-login";
23
29
  /** Keeps CODESYS running between deployments, so each skips starting it. */
24
30
  export const deployContainer = "tsplc-agent-deploy";
31
+ /** Every Docker container and network the agent creates: one agent per Docker server uses them. */
32
+ export const agentDockerResources = {
33
+ containers: [gateway.host, deployContainer, loginContainer],
34
+ networks: [network, codesysNetwork],
35
+ };
25
36
  /** CODESYS reads the controller user from these for one operation; the agent never stores it. */
26
37
  const credentialNames = {
27
38
  usernameEnv: "TSPLC_DEVICE_USERNAME",
@@ -42,6 +53,55 @@ const ensureNetwork = async (name: string, ...options: string[]) => {
42
53
  }
43
54
  };
44
55
 
56
+ /**
57
+ * Why the images can't serve a deployment or login, or null when they can. Containers run the
58
+ * installed tsPLC's code, so only a new image recipe or a missing image needs setup.
59
+ */
60
+ const setupNeeded = async () => {
61
+ const status = await builderImageStatus();
62
+ const reason =
63
+ setupReason(status) ??
64
+ ((await docker("image", "ls", "--quiet", gatewayImage))
65
+ ? null
66
+ : `the CODESYS gateway image ${gatewayImage} is missing`);
67
+ return { status, reason };
68
+ };
69
+
70
+ /**
71
+ * Checks that the images can serve a deployment or login, naming what to run on the plant PC
72
+ * when they can't, and returns the builder image's status.
73
+ */
74
+ export const requireBuilder = async () => {
75
+ const { status, reason } = await setupNeeded().catch((cause: unknown) => {
76
+ throw new AgentError(
77
+ `Docker doesn't answer on the plant PC; start Docker Desktop there: ${errorMessage(cause)}`,
78
+ 503,
79
+ );
80
+ });
81
+ if (reason) {
82
+ throw new AgentError(
83
+ `The plant PC needs tsplc-agent setup: ${reason}. Run tsplc-agent setup there; the line's server keeps running meanwhile`,
84
+ 409,
85
+ );
86
+ }
87
+ return status;
88
+ };
89
+
90
+ /** What the agent says about its images when it starts. */
91
+ export const describeBuilder = async () => {
92
+ const { status, reason } = await setupNeeded();
93
+ if (reason) {
94
+ return `Deployments and logins need tsplc-agent setup first: ${reason}`;
95
+ }
96
+ if (status.kind === "unverified") {
97
+ return `Warning: ${status.reason}. Deployments use it; run tsplc-agent setup once to rebuild and label it`;
98
+ }
99
+ return "The CODESYS images match this tsPLC";
100
+ };
101
+
102
+ /** Removes container `name`, which need not exist. */
103
+ export const removeContainer = (name: string) => docker("rm", "--force", name);
104
+
45
105
  /** The gateway container stays up between operations, as a CODESYS gateway service would. */
46
106
  export const ensureGateway = async () => {
47
107
  await ensureNetwork(network);
package/src/deploy.ts CHANGED
@@ -16,6 +16,8 @@ import {
16
16
  deployContainer,
17
17
  ensureGateway,
18
18
  loginContainer,
19
+ removeContainer,
20
+ requireBuilder,
19
21
  } from "./codesys";
20
22
  import type { Debugging } from "./debugging";
21
23
  import { AgentError, errorMessage } from "./errors";
@@ -55,6 +57,7 @@ export const createDeployments = (context: {
55
57
  if (!deployed || !target) {
56
58
  return;
57
59
  }
60
+ await requireBuilder();
58
61
  await ensureGateway();
59
62
  const release = await loadRelease(state.paths.releases, deployed.id);
60
63
  await startWarmController(
@@ -71,6 +74,27 @@ export const createDeployments = (context: {
71
74
  });
72
75
 
73
76
  return {
77
+ /**
78
+ * Stops the warm container once it has committed the last deployment, so an upgraded agent
79
+ * starts one running its own code and none keeps the installed package's files in use.
80
+ */
81
+ retire: async () => {
82
+ await warming;
83
+ const deployed = await state.release();
84
+ const target = await state.target();
85
+ if (deployed && target) {
86
+ await settleWarmController(
87
+ controllerConfig(
88
+ await loadRelease(state.paths.releases, deployed.id),
89
+ target,
90
+ state.paths.controller,
91
+ context.codesys,
92
+ ),
93
+ deployContainer,
94
+ );
95
+ }
96
+ await removeContainer(deployContainer);
97
+ },
74
98
  deploy: async (
75
99
  /** Reads the upload once the client's version is checked, so a mismatch is reported before a large body is read. */
76
100
  readRequest: () => Promise<DeployRequest>,
@@ -84,10 +108,16 @@ export const createDeployments = (context: {
84
108
  clientTsplc.version !== tsplcVersion
85
109
  ) {
86
110
  throw new AgentError(
87
- versionMismatch({ agent: tsplcVersion, client: clientTsplc.version }),
111
+ versionMismatch({
112
+ agent: tsplcVersion,
113
+ client: clientTsplc.version,
114
+ agentUpgrades: true,
115
+ }),
88
116
  409,
89
117
  );
90
118
  }
119
+ context.operations.requireIdle();
120
+ const builder = await requireBuilder();
91
121
  const { settings, upload } = await readRequest();
92
122
  const target = await state.requireTarget();
93
123
  if (await findControllerLogin(loginContainer)) {
@@ -102,6 +132,12 @@ export const createDeployments = (context: {
102
132
  return context.operations.stream(
103
133
  "a deployment",
104
134
  async (emit) => {
135
+ if (builder.kind === "unverified") {
136
+ emit({
137
+ kind: "progress",
138
+ message: `Warning: ${builder.reason}. Run tsplc-agent setup on the plant PC once to rebuild and label it`,
139
+ });
140
+ }
105
141
  if (clientTsplc.version === undefined) {
106
142
  emit({
107
143
  kind: "progress",
package/src/index.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  export { type AgentOptions, createAgent } from "./agent.ts";
2
+ export { agentDockerResources } from "./codesys.ts";
2
3
  export {
3
4
  type AgentEvent,
4
5
  type AgentStatus,
@@ -0,0 +1,102 @@
1
+ import { existsSync } from "node:fs";
2
+ import { readFile, rm, writeFile } from "node:fs/promises";
3
+ import { z } from "zod";
4
+ import { processAlive } from "./processes";
5
+ import { agentVersionHeader, errorSchema } from "./protocol";
6
+
7
+ /**
8
+ * The running agent, as `serve` records it in its state directory, so that `upgrade` and
9
+ * `service` on the same PC can reach it and start it again the same way.
10
+ */
11
+ export const instanceSchema = z.strictObject({
12
+ pid: z.int().positive(),
13
+ version: z.string(),
14
+ url: z.url(),
15
+ /** The arguments after `serve` it was started with. */
16
+ serve: z.array(z.string()),
17
+ /** Started by `tsplc-agent service run`, which starts it again when it exits. */
18
+ supervised: z.boolean(),
19
+ startedAt: z.iso.datetime(),
20
+ });
21
+ export type Instance = z.infer<typeof instanceSchema>;
22
+
23
+ /** The exit status of an agent that exits to be started again, such as after an upgrade. */
24
+ export const restartStatus = 75;
25
+
26
+ export const writeInstance = (file: string, instance: Instance) =>
27
+ writeFile(file, JSON.stringify(instance, null, 2));
28
+
29
+ /** Removes the record, unless another agent has replaced it since. */
30
+ export const removeInstance = async (file: string, pid: number) => {
31
+ if ((await readInstance(file))?.pid === pid) {
32
+ await rm(file, { force: true });
33
+ }
34
+ };
35
+
36
+ const readInstance = async (file: string) =>
37
+ existsSync(file)
38
+ ? instanceSchema.safeParse(
39
+ await readFile(file, "utf8").then(
40
+ (text): unknown => JSON.parse(text),
41
+ () => undefined,
42
+ ),
43
+ ).data
44
+ : undefined;
45
+
46
+ /** The agent recorded in `file`, when its process still runs, or null. */
47
+ export const runningAgent = async (file: string) => {
48
+ const instance = await readInstance(file);
49
+ return instance && processAlive(instance.pid) ? instance : null;
50
+ };
51
+
52
+ /**
53
+ * How a held agent exits: leaving the line's server running for the next agent or stopping it,
54
+ * and whether whatever started it should start it again.
55
+ */
56
+ export const exitSchema = z.strictObject({
57
+ server: z.enum(["leave", "stop"]),
58
+ restart: z.boolean(),
59
+ });
60
+ export type AgentExit = z.infer<typeof exitSchema>;
61
+
62
+ /** The tsPLC version the agent at `url` answers with, which it names even to a request without its token, or null. */
63
+ export const answeringVersion = (url: string) =>
64
+ fetch(new URL("/status", url), { signal: AbortSignal.timeout(5000) }).then(
65
+ (response) => response.headers.get(agentVersionHeader),
66
+ () => null,
67
+ );
68
+
69
+ /** Calls the control routes of `instance` with the agent's full token. */
70
+ export const createAgentControl = (instance: Instance, token: string) => {
71
+ const call = async (
72
+ method: "GET" | "POST" | "DELETE",
73
+ path: string,
74
+ body?: unknown,
75
+ ) => {
76
+ const response = await fetch(new URL(path, instance.url), {
77
+ method,
78
+ headers: {
79
+ authorization: `Bearer ${token}`,
80
+ ...(body === undefined ? {} : { "content-type": "application/json" }),
81
+ },
82
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
83
+ });
84
+ if (!response.ok) {
85
+ const failure = errorSchema.safeParse(
86
+ await response.json().catch(() => undefined),
87
+ );
88
+ throw new Error(
89
+ failure.data?.error ?? `The agent answered ${response.status}`,
90
+ );
91
+ }
92
+ return response;
93
+ };
94
+ return {
95
+ /** Stops the agent taking new operations; fails while one runs or a login is open. */
96
+ hold: () => call("POST", "/agent/hold").then(() => {}),
97
+ release: () => call("DELETE", "/agent/hold").then(() => {}),
98
+ /** Makes the held agent exit. */
99
+ exit: (exit: AgentExit) => call("POST", "/agent/exit", exit).then(() => {}),
100
+ };
101
+ };
102
+ export type AgentControl = ReturnType<typeof createAgentControl>;
package/src/login.ts CHANGED
@@ -15,6 +15,7 @@ import {
15
15
  deployContainer,
16
16
  ensureGateway,
17
17
  loginContainer,
18
+ requireBuilder,
18
19
  } from "./codesys";
19
20
  import { AgentError, errorMessage } from "./errors";
20
21
  import { appendJsonl } from "./logs";
@@ -130,6 +131,8 @@ export const createLogin = (context: {
130
131
  },
131
132
 
132
133
  open: async (sent: Credentials | null) => {
134
+ operations.requireIdle();
135
+ await requireBuilder();
133
136
  const credentials = await controllerCredentials(sent);
134
137
  context.log(
135
138
  `Opening a login with the ${sent ? "provided" : "stored"} controller user`,
@@ -199,6 +202,10 @@ export const createLogin = (context: {
199
202
  });
200
203
  },
201
204
 
205
+ /** Whether a login's container runs, open or opening. */
206
+ isOpen: async () =>
207
+ (await findControllerLogin(loginContainer)) !== undefined,
208
+
202
209
  /**
203
210
  * The open login's state. A login that lost the controller, or whose worker died or hangs, is
204
211
  * reported as failed, so the CLI can log it out and open a new one.