@tsplc/agent 0.2.17 → 0.2.18

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/dist/index.js CHANGED
@@ -1,88 +1,76 @@
1
1
  // packages/agent/src/agent.ts
2
- import { execFile } from "node:child_process";
3
2
  import { timingSafeEqual } from "node:crypto";
3
+ import { join as join7 } from "node:path";
4
+ import { loginCommandSchema } from "@tsplc/build";
5
+ import { z as z4 } from "zod";
6
+
7
+ // packages/agent/src/debugging.ts
4
8
  import { existsSync as existsSync3 } from "node:fs";
5
- import { mkdir as mkdir2, readdir, readFile as readFile3, stat as stat2, writeFile as writeFile2 } from "node:fs/promises";
6
- import { join as join2 } from "node:path";
7
- import { setTimeout as delay2 } from "node:timers/promises";
8
- import { promisify } from "node:util";
9
- import {
10
- explicitDownload,
11
- failureReason,
12
- findControllerLogin,
13
- gatewayImage,
14
- loginCommandSchema,
15
- openControllerLogin,
16
- resolveConfig,
17
- startWarmController,
18
- updateWarmController
19
- } from "@tsplc/build";
9
+ import { join as join3 } from "node:path";
20
10
  import {
21
11
  createDebugger,
22
12
  createDebugHandler,
23
13
  createLoginAdapter,
24
14
  loadManifest,
25
- LoginUnavailable,
26
- noLogin,
27
15
  timelineEntries
28
16
  } from "@tsplc/debug";
29
- import { z as z3 } from "zod";
30
17
 
31
- // packages/agent/src/discovery.ts
32
- import { Resolver } from "node:dns/promises";
33
- import { createConnection } from "node:net";
34
- import { networkInterfaces as osInterfaces } from "node:os";
35
- var runtimePort = 11740;
36
- var largestPrefix = 22;
37
- var probeTimeoutMs = 500;
38
- var probesAtOnce = 128;
39
- var networkInterfaces = () => Object.entries(osInterfaces()).flatMap(([name, addresses]) => (addresses ?? []).filter((address) => address.family === "IPv4" && !address.internal).map((address) => ({
40
- name,
41
- address: address.address,
42
- prefixLength: address.netmask.split(".").reduce((bits, octet) => bits + Number(octet).toString(2).replaceAll("0", "").length, 0)
43
- })));
44
- var toNumber = (address) => address.split(".").reduce((value, octet) => value * 256 + Number(octet), 0);
45
- var toAddress = (value) => [24, 16, 8, 0].map((shift) => Math.floor(value / 2 ** shift) % 256).join(".");
46
- var subnetHosts = ({ address, prefixLength }) => {
47
- if (prefixLength < largestPrefix)
48
- throw new Error(`The /${prefixLength} network is too large to scan; the limit is /${largestPrefix}.`);
49
- const size = 2 ** (32 - prefixLength);
50
- const network = toNumber(address) - toNumber(address) % size;
51
- const hosts = size <= 2 ? Array.from({ length: size }, (_, index) => network + index) : Array.from({ length: size - 2 }, (_, index) => network + index + 1);
52
- return hosts.map(toAddress).filter((host) => host !== address);
18
+ // packages/agent/src/errors.ts
19
+ class AgentError extends Error {
20
+ status;
21
+ downloadRequired;
22
+ constructor(message, status, { downloadRequired = false } = {}) {
23
+ super(message);
24
+ this.status = status;
25
+ this.downloadRequired = downloadRequired;
26
+ }
27
+ }
28
+ var errorMessage = (error) => error instanceof Error ? error.message : String(error);
29
+
30
+ // packages/agent/src/logs.ts
31
+ import { existsSync } from "node:fs";
32
+ import { open, readFile, rename, stat } from "node:fs/promises";
33
+ var rotateBytes = 5 * 2 ** 20;
34
+ var appendJsonl = async (file, value) => {
35
+ if (existsSync(file) && (await stat(file)).size >= rotateBytes) {
36
+ await rename(file, `${file}.1`);
37
+ }
38
+ const log = await open(file, "a+");
39
+ try {
40
+ const { size } = await log.stat();
41
+ const last = Buffer.alloc(1);
42
+ if (size) {
43
+ await log.read(last, 0, 1, size - 1);
44
+ }
45
+ const separator = size && last[0] !== 10 ? `
46
+ ` : "";
47
+ await log.writeFile(`${separator}${JSON.stringify(value)}
48
+ `);
49
+ } finally {
50
+ await log.close();
51
+ }
53
52
  };
54
- var accepts = (host, port) => new Promise((resolve) => {
55
- const socket = createConnection({ host, port });
56
- const timer = setTimeout(() => finish(false), probeTimeoutMs);
57
- const finish = (open) => {
58
- clearTimeout(timer);
59
- socket.destroy();
60
- resolve(open);
61
- };
62
- socket.once("connect", () => finish(true));
63
- socket.once("error", () => finish(false));
64
- });
65
- var resolver = new Resolver({ timeout: 1000, tries: 1 });
66
- var hostname = (address) => resolver.reverse(address).then((names) => names[0] ?? null, () => null);
67
- var discoverControllers = async (network, port = runtimePort) => {
68
- const hosts = subnetHosts(network);
69
- const found = [];
70
- for (let start = 0;start < hosts.length; start += probesAtOnce) {
71
- const batch = hosts.slice(start, start + probesAtOnce);
72
- const open = await Promise.all(batch.map((host) => accepts(host, port)));
73
- for (const [index, host] of batch.entries())
74
- if (open[index])
75
- found.push({ address: host, port, hostname: await hostname(host) });
53
+ var readJsonl = async (file, schema, limit) => {
54
+ if (!existsSync(file)) {
55
+ return [];
76
56
  }
77
- return found;
57
+ return (await readFile(file, "utf8")).split(`
58
+ `).filter(Boolean).slice(-limit).flatMap((line) => {
59
+ try {
60
+ return [schema.parse(JSON.parse(line))];
61
+ } catch {
62
+ return [];
63
+ }
64
+ });
78
65
  };
79
66
 
80
67
  // packages/agent/src/protocol.ts
81
68
  import { tsplcConfigSchema } from "@tsplc/config";
69
+ import { tcpPort } from "@tsplc/config/build";
82
70
  import { z } from "zod";
83
71
  var targetSchema = z.strictObject({
84
72
  host: z.string().nonempty(),
85
- port: z.number().int().min(1).max(65535)
73
+ port: tcpPort
86
74
  });
87
75
  var networkInterfaceSchema = z.strictObject({
88
76
  name: z.string(),
@@ -94,24 +82,29 @@ var controllerSchema = z.strictObject({
94
82
  port: z.number().int(),
95
83
  hostname: z.string().nullable()
96
84
  });
85
+ var discoverSchema = z.strictObject({ name: z.string() });
97
86
  var credentialsSchema = z.strictObject({
98
87
  username: z.string().nonempty(),
99
88
  password: z.string().nonempty()
100
89
  });
101
- var variableSchema = z.strictObject({ path: z.string(), type: z.string() });
90
+ var variableSchema = z.strictObject({
91
+ path: z.string(),
92
+ type: z.string()
93
+ });
102
94
  var releaseManifestSchema = z.strictObject({
103
95
  config: z.record(z.string(), z.unknown()),
104
96
  variables: z.array(variableSchema),
105
97
  server: z.string().nonempty().optional(),
106
98
  debug: tsplcConfigSchema.shape.debug,
107
- serverTokenEnv: z.string().nonempty().optional()
99
+ serverTokenEnv: z.string().nonempty().optional(),
100
+ secrets: tsplcConfigSchema.shape.secrets
108
101
  });
109
102
  var uploadEncoding = "gzip";
110
103
  var deployOptionsSchema = z.strictObject({
111
- credentials: credentialsSchema,
104
+ credentials: credentialsSchema.nullable(),
112
105
  download: z.boolean(),
113
106
  initializeUser: z.boolean()
114
- });
107
+ }).refine((options) => options.credentials || !options.initializeUser, "Initializing the controller's user needs the user's credentials.");
115
108
  var eventSchema = z.discriminatedUnion("kind", [
116
109
  z.strictObject({ kind: z.literal("progress"), message: z.string() }),
117
110
  z.strictObject({ kind: z.literal("done"), result: z.unknown() }),
@@ -121,10 +114,12 @@ var eventSchema = z.discriminatedUnion("kind", [
121
114
  downloadRequired: z.boolean()
122
115
  })
123
116
  ]);
117
+ var errorSchema = z.object({ error: z.string() });
118
+ var deployOperationSchema = z.enum(["download", "online-change"]);
124
119
  var releaseSchema = z.strictObject({
125
120
  id: z.string(),
126
121
  deployedAt: z.iso.datetime(),
127
- operation: z.enum(["download", "online-change"]),
122
+ operation: deployOperationSchema,
128
123
  controllerIds: z.strictObject({ codeId: z.string(), dataId: z.string() }),
129
124
  server: z.string().optional()
130
125
  });
@@ -135,15 +130,24 @@ var statusSchema = z.strictObject({
135
130
  login: z.union([
136
131
  z.strictObject({ state: z.string(), forced: z.array(z.string()) }),
137
132
  z.strictObject({ error: z.string() })
138
- ]).nullable()
133
+ ]).nullable(),
134
+ credentialsStored: z.boolean()
139
135
  });
140
136
  var logoutSchema = z.strictObject({ failure: z.string().optional() });
141
- var clientHeaders = { user: "x-tsplc-user", host: "x-tsplc-host" };
137
+ var clientHeaders = {
138
+ user: "x-tsplc-user",
139
+ host: "x-tsplc-host"
140
+ };
141
+ var clientIdentity = (request) => {
142
+ const header = (name) => request.headers.get(name)?.slice(0, 200) || undefined;
143
+ return { user: header(clientHeaders.user), host: header(clientHeaders.host) };
144
+ };
142
145
  var deploymentSchema = z.strictObject({
143
146
  at: z.iso.datetime(),
144
147
  release: z.string(),
145
148
  build: z.string().optional(),
146
- operation: z.enum(["download", "online-change"]),
149
+ operation: deployOperationSchema,
150
+ credentials: z.enum(["provided", "stored"]).optional(),
147
151
  user: z.string().optional(),
148
152
  host: z.string().optional()
149
153
  });
@@ -158,69 +162,46 @@ var auditSchema = z.strictObject({
158
162
  error: z.string().optional()
159
163
  });
160
164
 
161
- // packages/agent/src/logs.ts
162
- import { existsSync } from "node:fs";
163
- import { open, readFile, rename, stat } from "node:fs/promises";
164
- var rotateBytes = 5 * 2 ** 20;
165
- var appendJsonl = async (file, value) => {
166
- if (existsSync(file) && (await stat(file)).size >= rotateBytes)
167
- await rename(file, `${file}.1`);
168
- const log = await open(file, "a+");
169
- try {
170
- const { size } = await log.stat();
171
- const last = Buffer.alloc(1);
172
- if (size)
173
- await log.read(last, 0, 1, size - 1);
174
- const separator = size && last[0] !== 10 ? `
175
- ` : "";
176
- await log.writeFile(`${separator}${JSON.stringify(value)}
177
- `);
178
- } finally {
179
- await log.close();
180
- }
181
- };
182
- var readJsonl = async (file, schema, limit) => {
183
- if (!existsSync(file))
184
- return [];
185
- return (await readFile(file, "utf8")).split(`
186
- `).filter(Boolean).slice(-limit).flatMap((line) => {
187
- try {
188
- return [schema.parse(JSON.parse(line))];
189
- } catch {
190
- return [];
191
- }
192
- });
193
- };
194
-
195
165
  // packages/agent/src/releases.ts
196
166
  import { createHash } from "node:crypto";
197
167
  import { existsSync as existsSync2 } from "node:fs";
198
- import { mkdir, mkdtemp, readFile as readFile2, rename as rename2, rm, writeFile } from "node:fs/promises";
168
+ import {
169
+ mkdir,
170
+ mkdtemp,
171
+ readFile as readFile2,
172
+ rename as rename2,
173
+ rm,
174
+ writeFile
175
+ } from "node:fs/promises";
199
176
  import { dirname, join, posix } from "node:path";
200
177
  import { z as z2 } from "zod";
201
178
  var filePrefix = "files/";
202
179
  var releasePath = (name) => {
203
180
  const path = posix.normalize(name.slice(filePrefix.length));
204
- if (posix.isAbsolute(path) || path.startsWith("..") || path.includes("\\"))
181
+ if (posix.isAbsolute(path) || path.startsWith("..") || path.includes("\\")) {
205
182
  throw new Error(`Invalid release file name: ${name}`);
183
+ }
206
184
  return path;
207
185
  };
208
186
  var readUpload = async (form) => {
209
- if (form.get("encoding") !== uploadEncoding)
187
+ if (form.get("encoding") !== uploadEncoding) {
210
188
  throw new Error("This deployment came from an older tsplc: update tsplc where you deploy from.");
189
+ }
211
190
  const manifest = releaseManifestSchema.parse(JSON.parse(z2.string().parse(form.get("manifest"))));
212
191
  const files = await Promise.all([...form.entries()].filter(([name]) => name.startsWith(filePrefix)).map(async ([name, value]) => ({
213
192
  path: releasePath(name),
214
193
  content: Bun.gunzipSync(await z2.instanceof(File).parse(value).bytes())
215
194
  })));
216
- if (manifest.server && !files.some((file) => file.path === manifest.server))
195
+ if (manifest.server && !files.some((file) => file.path === manifest.server)) {
217
196
  throw new Error(`The release names a server ${manifest.server} it doesn't contain`);
197
+ }
218
198
  return { manifest, files };
219
199
  };
220
200
  var saveRelease = async (releases, { manifest, files }) => {
221
201
  const hash = createHash("sha256").update(JSON.stringify(manifest));
222
- for (const file of [...files].sort((a, b) => a.path.localeCompare(b.path)))
202
+ for (const file of [...files].sort((a, b) => a.path.localeCompare(b.path))) {
223
203
  hash.update(file.path).update(createHash("sha256").update(file.content).digest("hex"));
204
+ }
224
205
  const id = hash.digest("hex").slice(0, 16);
225
206
  const directory = join(releases, id);
226
207
  if (!existsSync2(directory)) {
@@ -248,81 +229,170 @@ var loadRelease = async (releases, id) => {
248
229
  return { id, directory, manifest };
249
230
  };
250
231
 
251
- // packages/agent/src/server-process.ts
252
- import { dirname as dirname2 } from "node:path";
253
- import { setTimeout as delay } from "node:timers/promises";
254
- var healthyWithinMs = 60000;
255
- var settleMs = 5000;
256
- var restartDelayMs = 2000;
257
- var createServerSupervisor = (options) => {
258
- let current;
259
- const spawn = (executable) => {
260
- const command = executable.endsWith(".js") ? [process.execPath, executable] : [executable];
261
- const child = Bun.spawn(command, {
262
- cwd: dirname2(executable),
263
- stdio: ["ignore", "inherit", "inherit"],
264
- onExit: (_, code) => {
265
- if (current?.process !== child)
266
- return;
267
- options.log(`Server exited (${code}); restarting it in ${restartDelayMs / 1000} s`);
268
- delay(restartDelayMs).then(() => {
269
- if (current?.process === child)
270
- current = { executable, process: spawn(executable) };
271
- });
272
- }
273
- });
274
- return child;
275
- };
276
- const start = (executable) => {
277
- current = { executable, process: spawn(executable) };
278
- return current.process;
279
- };
280
- const stop = async () => {
281
- const running = current;
282
- current = undefined;
283
- if (!running)
284
- return;
285
- running.process.kill();
286
- await running.process.exited;
232
+ // packages/agent/src/secrets.ts
233
+ import { mkdir as mkdir2, readFile as readFile3, rm as rm2, writeFile as writeFile2 } from "node:fs/promises";
234
+ import { dirname as dirname2, join as join2, relative } from "node:path";
235
+ import { secretPlaceholder, secretValue } from "@tsplc/config";
236
+ import { escapeString } from "@tsplc/iec/st";
237
+ var agentService = "tsplc-agent";
238
+ var controllerSecretNames = {
239
+ username: "controller-username",
240
+ password: "controller-password"
241
+ };
242
+ var storedCredentials = async () => {
243
+ const [username, password] = await Promise.all([
244
+ Bun.secrets.get({
245
+ service: agentService,
246
+ name: controllerSecretNames.username
247
+ }),
248
+ Bun.secrets.get({
249
+ service: agentService,
250
+ name: controllerSecretNames.password
251
+ })
252
+ ]);
253
+ return username && password ? { username, password } : null;
254
+ };
255
+ var controllerCredentials = async (sent) => {
256
+ const credentials = sent ?? await storedCredentials();
257
+ if (!credentials) {
258
+ throw new AgentError("No controller user is stored on the plant PC: run tsplc-agent secrets set-controller there", 409);
259
+ }
260
+ return credentials;
261
+ };
262
+ var readSecrets = async (secrets) => {
263
+ const values = new Map;
264
+ if (!secrets) {
265
+ return values;
266
+ }
267
+ const { service } = secrets;
268
+ const missing = [];
269
+ for (const name of secrets.names) {
270
+ const value = await Bun.secrets.get({ service, name });
271
+ const valid = secretValue.safeParse(value);
272
+ if (!value) {
273
+ missing.push(name);
274
+ } else if (!valid.success) {
275
+ throw new AgentError(`Secret ${name} in Bun.secrets service ${service} ${valid.error.issues.map((issue) => issue.message).join(" and ")}`, 409);
276
+ } else {
277
+ values.set(name, value);
278
+ }
279
+ }
280
+ if (missing.length) {
281
+ throw new AgentError(`The plant PC has no ${missing.join(", ")} in Bun.secrets service ${service}: run tsplc-agent secrets set <name> --service ${service} there`, 409);
282
+ }
283
+ return values;
284
+ };
285
+ var releaseVariable = async (manifest, name) => manifest.secrets?.names.includes(name) ? Bun.secrets.get({ service: manifest.secrets.service, name }) : process.env[name];
286
+ var fillSecrets = (st, secrets) => [...secrets].reduce((text, [name, value]) => text.replaceAll(secretPlaceholder(name), () => escapeString(value, "'")), st);
287
+ var withSecrets = async (config, secrets, directory) => {
288
+ await rm2(directory, { recursive: true, force: true });
289
+ for await (const path of new Bun.Glob("**/*").scan({
290
+ cwd: config.sourceDir,
291
+ dot: true
292
+ })) {
293
+ const file = join2(directory, path);
294
+ await mkdir2(dirname2(file), { recursive: true });
295
+ await writeFile2(file, fillSecrets(await readFile3(join2(config.sourceDir, path), "utf8"), secrets));
296
+ }
297
+ return {
298
+ ...config,
299
+ sourceDir: directory,
300
+ entry: join2(directory, relative(config.sourceDir, config.entry))
287
301
  };
288
- const healthy = async (child) => {
289
- if (!options.healthUrl) {
290
- await delay(settleMs);
291
- return child.exitCode === null;
302
+ };
303
+
304
+ // packages/agent/src/debugging.ts
305
+ var recentEntries = 500;
306
+ var createDebugging = (context) => {
307
+ const { state, log } = context;
308
+ const start = async () => {
309
+ const release = await state.release();
310
+ if (!release) {
311
+ return null;
292
312
  }
293
- const deadline = Date.now() + healthyWithinMs;
294
- while (Date.now() < deadline && child.exitCode === null) {
295
- if (await fetch(options.healthUrl).then((response) => response.ok, () => false))
296
- return true;
297
- await delay(1000);
313
+ const { directory, manifest: releaseManifest } = await loadRelease(state.paths.releases, release.id);
314
+ const manifestFile = join3(directory, "debug.json");
315
+ if (!existsSync3(manifestFile)) {
316
+ return null;
298
317
  }
299
- return false;
318
+ const manifest = await loadManifest(manifestFile);
319
+ const serverToken = releaseManifest.serverTokenEnv && await releaseVariable(releaseManifest, releaseManifest.serverTokenEnv);
320
+ const debug = await createDebugger({
321
+ manifest,
322
+ adapter: createLoginAdapter({
323
+ read: context.readLogin,
324
+ probe: manifest.build.target,
325
+ endpoint: "the agent's login"
326
+ }),
327
+ stateDirectory: state.paths.debug,
328
+ watch: releaseManifest.debug?.watch ?? {},
329
+ ...context.serverHealthUrl && serverToken && {
330
+ server: {
331
+ url: new URL(context.serverHealthUrl).origin,
332
+ token: serverToken
333
+ }
334
+ },
335
+ release: {
336
+ id: release.id,
337
+ deployedAt: release.deployedAt,
338
+ operation: release.operation
339
+ },
340
+ timeline: [
341
+ ...(await readJsonl(state.paths.deployments, deploymentSchema, recentEntries)).map(({ at, ...deployment }) => timelineEntries.deploy(at, deployment)),
342
+ ...(await readJsonl(state.paths.audit, auditSchema, recentEntries)).map(({ at, ...audit }) => timelineEntries.audit(at, audit))
343
+ ],
344
+ log
345
+ });
346
+ return { debug, handle: createDebugHandler(debug, log) };
300
347
  };
348
+ const startOrLog = () => start().catch((error) => {
349
+ log(`Starting the debugger failed: ${errorMessage(error)}`);
350
+ return null;
351
+ });
352
+ let current = startOrLog();
301
353
  return {
302
- start,
303
- stop,
304
- replace: async (executable) => {
305
- const previous = current?.executable;
306
- await stop();
307
- let failure;
308
- const started = await (async () => healthy(start(executable)))().catch((error) => {
309
- failure = error;
310
- return false;
354
+ handle: async (request, route) => {
355
+ const debugging = await current;
356
+ if (!debugging) {
357
+ return Response.json({
358
+ error: "The deployed release has no debug manifest, or the debugger failed to start"
359
+ }, { status: 503 });
360
+ }
361
+ return debugging.handle(request, route);
362
+ },
363
+ record: async ({ at, ...audit }) => {
364
+ (await current)?.debug.record(timelineEntries.audit(at, audit));
365
+ },
366
+ restart: () => {
367
+ current = current.then(async (debugging) => {
368
+ await debugging?.debug.close();
369
+ return startOrLog();
311
370
  });
312
- if (started)
313
- return;
314
- await stop();
315
- if (previous)
316
- start(previous);
317
- const reason = failure instanceof Error ? failure.message : `it did not start${options.healthUrl ? ` answering ${options.healthUrl}` : ""}`;
318
- throw new Error(`The new server failed: ${reason}. ${previous ? "The previous one is running again." : ""}`.trim(), { cause: failure });
319
371
  },
320
- status: () => current && { executable: current.executable, running: current.process.exitCode === null }
372
+ close: async () => {
373
+ await (await current)?.debug.close();
374
+ }
321
375
  };
322
376
  };
323
377
 
324
- // packages/agent/src/agent.ts
325
- var execute = promisify(execFile);
378
+ // packages/agent/src/deploy.ts
379
+ import { existsSync as existsSync4 } from "node:fs";
380
+ import { readdir, readFile as readFile4, stat as stat2 } from "node:fs/promises";
381
+ import { join as join5 } from "node:path";
382
+ import { setTimeout as delay } from "node:timers/promises";
383
+ import {
384
+ findControllerLogin,
385
+ startWarmController,
386
+ updateWarmController
387
+ } from "@tsplc/build";
388
+ import { loadManifest as loadManifest2 } from "@tsplc/debug";
389
+ import { z as z3 } from "zod";
390
+
391
+ // packages/agent/src/codesys.ts
392
+ import { execFile } from "node:child_process";
393
+ import { join as join4 } from "node:path";
394
+ import { promisify } from "node:util";
395
+ import { gatewayImage, resolveConfig } from "@tsplc/build";
326
396
  var network = "tsplc-agent";
327
397
  var codesysNetwork = "tsplc-agent-codesys";
328
398
  var gateway = { host: "tsplc-agent-gateway", port: 1217 };
@@ -332,55 +402,14 @@ var credentialNames = {
332
402
  usernameEnv: "TSPLC_DEVICE_USERNAME",
333
403
  passwordEnv: "TSPLC_DEVICE_PASSWORD"
334
404
  };
335
-
336
- class AgentError extends Error {
337
- status;
338
- downloadRequired;
339
- constructor(message, status, downloadRequired = false) {
340
- super(message);
341
- this.status = status;
342
- this.downloadRequired = downloadRequired;
405
+ var docker = async (...args) => {
406
+ const { stdout } = await promisify(execFile)("docker", args);
407
+ return stdout.trim();
408
+ };
409
+ var ensureNetwork = async (name, ...options) => {
410
+ if (!await docker("network", "ls", "--quiet", "--filter", `name=^${name}$`)) {
411
+ await docker("network", "create", ...options, name);
343
412
  }
344
- }
345
- var json = (body, status = 200) => Response.json(body, { status });
346
- var message = (error) => error instanceof Error ? error.message : String(error);
347
- var loginStateTimeout = 30000;
348
- var stoppedAnswering = { error: "The login stopped answering" };
349
- var recentEntries = 500;
350
- var clientOf = (request) => {
351
- const header = (name) => request.headers.get(name)?.slice(0, 200) || undefined;
352
- return { user: header(clientHeaders.user), host: header(clientHeaders.host) };
353
- };
354
- var auditOf = (command) => {
355
- switch (command.command) {
356
- case "write":
357
- case "force":
358
- return { command: command.command, values: command.values };
359
- case "unforce":
360
- return {
361
- command: command.restore ? "unforce --restore" : "unforce",
362
- values: Object.fromEntries(command.expressions.map((expression) => [expression, ""]))
363
- };
364
- case "start":
365
- case "stop":
366
- return { command: command.command, values: {} };
367
- case "reset":
368
- return { command: `reset ${command.kind.toLowerCase()}`, values: {} };
369
- case "state":
370
- case "read":
371
- return;
372
- }
373
- };
374
- var matches = (presented, token) => {
375
- const actual = Buffer.from(presented);
376
- const expected = Buffer.from(token);
377
- return actual.length === expected.length && timingSafeEqual(actual, expected);
378
- };
379
- var readJson = async (path, schema) => existsSync3(path) ? schema.parse(JSON.parse(await readFile3(path, "utf8"))) : null;
380
- var docker = (...args) => execute("docker", args).then(({ stdout }) => stdout.trim());
381
- var ensureNetwork = async (name, ...options) => {
382
- if (!await docker("network", "ls", "--quiet", "--filter", `name=^${name}$`))
383
- await docker("network", "create", ...options, name);
384
413
  };
385
414
  var ensureGateway = async () => {
386
415
  await ensureNetwork(network);
@@ -390,8 +419,9 @@ var ensureGateway = async () => {
390
419
  await docker("run", "--detach", "--restart", "unless-stopped", "--platform", "linux/amd64", "--network", network, "--name", gateway.host, gatewayImage);
391
420
  }
392
421
  const networks = await docker("inspect", "--format", "{{json .NetworkSettings.Networks}}", gateway.host);
393
- if (!(codesysNetwork in JSON.parse(networks)))
422
+ if (!(codesysNetwork in JSON.parse(networks))) {
394
423
  await docker("network", "connect", codesysNetwork, gateway.host);
424
+ }
395
425
  };
396
426
  var withCredentials = async (credentials, run) => {
397
427
  process.env[credentialNames.usernameEnv] = credentials.username;
@@ -403,28 +433,45 @@ var withCredentials = async (credentials, run) => {
403
433
  delete process.env[credentialNames.passwordEnv];
404
434
  }
405
435
  };
436
+ var controllerConfig = (release, target, controllerDirectory) => ({
437
+ ...resolveConfig({
438
+ ...release.manifest.config,
439
+ online: {
440
+ network: codesysNetwork,
441
+ gateway,
442
+ device: target,
443
+ credentials: credentialNames
444
+ }
445
+ }, join4(release.directory, "manifest.json")),
446
+ outDir: controllerDirectory
447
+ });
448
+
449
+ // packages/agent/src/deploy.ts
406
450
  var followProgress = (controller, emit) => {
407
- const jobs = join2(controller, ".codesys/controller/jobs");
451
+ const jobs = join5(controller, ".codesys/controller/jobs");
408
452
  const since = Date.now();
409
453
  let following = true;
410
454
  const done = (async () => {
411
455
  let log;
412
456
  let offset = 0;
413
457
  while (following) {
414
- await delay2(2000);
415
- if (!log && existsSync3(jobs)) {
458
+ await delay(2000);
459
+ if (!log && existsSync4(jobs)) {
416
460
  for (const job of await readdir(jobs)) {
417
- const path = join2(jobs, job, ".codesys/controller/progress.log");
418
- if (existsSync3(path) && (await stat2(path)).mtimeMs >= since)
461
+ const path = join5(jobs, job, ".codesys/controller/progress.log");
462
+ if (existsSync4(path) && (await stat2(path)).mtimeMs >= since) {
419
463
  log = path;
464
+ }
420
465
  }
421
466
  }
422
- if (!log)
467
+ if (!log) {
423
468
  continue;
424
- const text = await readFile3(log, "utf8");
469
+ }
470
+ const text = await readFile4(log, "utf8");
425
471
  for (const line of text.slice(offset).split(`
426
- `).filter(Boolean))
472
+ `).filter(Boolean)) {
427
473
  emit({ kind: "progress", message: line.replace(/^\S+Z /, "") });
474
+ }
428
475
  offset = text.length;
429
476
  }
430
477
  })();
@@ -433,58 +480,176 @@ var followProgress = (controller, emit) => {
433
480
  await done;
434
481
  };
435
482
  };
436
- var createAgent = async (options) => {
437
- const paths = {
438
- releases: join2(options.state, "releases"),
439
- controller: join2(options.state, "controller"),
440
- release: join2(options.state, "release.json"),
441
- target: join2(options.state, "target.json"),
442
- deployments: join2(options.state, "deployments.jsonl"),
443
- audit: join2(options.state, "audit.jsonl"),
444
- debug: join2(options.state, "debug")
445
- };
446
- await mkdir2(options.state, { recursive: true });
447
- const server = createServerSupervisor({ healthUrl: options.serverHealthUrl, log: options.log });
448
- const deployed = await readJson(paths.release, releaseSchema);
449
- if (deployed?.server)
450
- server.start(join2(paths.releases, deployed.server));
451
- let busy;
452
- const requireTarget = async () => {
453
- const target = await readJson(paths.target, targetSchema);
454
- if (!target)
455
- throw new AgentError("Select the controller first: tsplc target", 409);
456
- return target;
457
- };
458
- const controllerConfig = (release, target) => ({
459
- ...resolveConfig({
460
- ...release.manifest.config,
461
- online: { network: codesysNetwork, gateway, device: target, credentials: credentialNames }
462
- }, join2(release.directory, "manifest.json")),
463
- outDir: paths.controller
464
- });
465
- const currentRelease = async () => {
466
- const release = await readJson(paths.release, releaseSchema);
467
- if (!release)
468
- throw new AgentError("Nothing has been deployed yet: tsplc deploy", 409);
469
- return loadRelease(paths.releases, release.id);
470
- };
483
+ var createDeployments = (context) => {
484
+ const { state, server } = context;
471
485
  const warming = (async () => {
472
- const target = await readJson(paths.target, targetSchema);
473
- if (!deployed || !target)
486
+ const deployed = await state.release();
487
+ const target = await state.target();
488
+ if (!deployed || !target) {
474
489
  return;
490
+ }
475
491
  await ensureGateway();
476
- const release = await loadRelease(paths.releases, deployed.id);
477
- await startWarmController(controllerConfig(release, target), deployContainer);
492
+ const release = await loadRelease(state.paths.releases, deployed.id);
493
+ await startWarmController(controllerConfig(release, target, state.paths.controller), deployContainer);
478
494
  })().catch((error) => {
479
- options.log(`Starting CODESYS failed: ${error instanceof Error ? error.message : String(error)}`);
495
+ context.log(`Starting CODESYS failed: ${errorMessage(error)}`);
480
496
  });
481
- let loginGeneration = 0;
497
+ return {
498
+ deploy: async (form, client) => {
499
+ const settings = deployOptionsSchema.parse(JSON.parse(z3.string().parse(form.get("options"))));
500
+ const upload = await readUpload(form);
501
+ const target = await state.requireTarget();
502
+ if (await findControllerLogin(loginContainer)) {
503
+ throw new AgentError("A login is open; log out before deploying: tsplc logout", 409);
504
+ }
505
+ const credentials = await controllerCredentials(settings.credentials);
506
+ const secrets = await readSecrets(upload.manifest.secrets);
507
+ return context.operations.stream("a deployment", async (emit) => {
508
+ const release = await saveRelease(state.paths.releases, upload);
509
+ if (!settings.download && !existsSync4(join5(state.paths.controller, ".codesys/controller/current.json"))) {
510
+ throw new AgentError("The controller has no application downloaded by this agent; only a full download can deploy", 409, { downloadRequired: true });
511
+ }
512
+ const config = await withSecrets(controllerConfig(release, target, state.paths.controller), secrets, state.paths.sources);
513
+ const previous = await state.release();
514
+ const serverPath = release.manifest.server && `${release.id}/${release.manifest.server}`;
515
+ if (serverPath) {
516
+ emit({ kind: "progress", message: "Starting the new server" });
517
+ await server.replace(join5(state.paths.releases, serverPath));
518
+ }
519
+ const kind = settings.download ? "download" : "online-change";
520
+ emit({ kind: "progress", message: `Starting the ${kind}` });
521
+ await ensureGateway();
522
+ await warming;
523
+ const stopFollowing = followProgress(state.paths.controller, emit);
524
+ const receipt = await updateWarmController(config, deployContainer, kind, { initializeUser: settings.initializeUser, credentials }).catch(async (failure) => {
525
+ if (serverPath) {
526
+ emit({
527
+ kind: "progress",
528
+ message: "Restoring the previous server"
529
+ });
530
+ await (previous?.server ? server.replace(join5(state.paths.releases, previous.server)) : server.stop());
531
+ }
532
+ throw failure;
533
+ }).finally(stopFollowing);
534
+ const deployed = {
535
+ id: release.id,
536
+ deployedAt: new Date().toISOString(),
537
+ operation: kind,
538
+ controllerIds: receipt.controllerIds,
539
+ server: serverPath ?? previous?.server
540
+ };
541
+ await state.setRelease(deployed);
542
+ const debugManifest = join5(release.directory, "debug.json");
543
+ const deployment = {
544
+ at: deployed.deployedAt,
545
+ release: release.id,
546
+ ...existsSync4(debugManifest) && {
547
+ build: (await loadManifest2(debugManifest)).build.id
548
+ },
549
+ operation: kind,
550
+ credentials: settings.credentials ? "provided" : "stored",
551
+ ...client
552
+ };
553
+ await appendJsonl(state.paths.deployments, deployment);
554
+ context.debugging.restart();
555
+ return deployed;
556
+ });
557
+ }
558
+ };
559
+ };
560
+
561
+ // packages/agent/src/discovery.ts
562
+ import { Resolver } from "node:dns/promises";
563
+ import { createConnection } from "node:net";
564
+ import { networkInterfaces as osInterfaces } from "node:os";
565
+ var runtimePort = 11740;
566
+ var largestPrefix = 22;
567
+ var probeTimeoutMs = 500;
568
+ var probesAtOnce = 128;
569
+ var networkInterfaces = () => Object.entries(osInterfaces()).flatMap(([name, addresses]) => (addresses ?? []).filter((address) => address.family === "IPv4" && !address.internal).map((address) => ({
570
+ name,
571
+ address: address.address,
572
+ prefixLength: address.netmask.split(".").reduce((bits, octet) => bits + Number(octet).toString(2).replaceAll("0", "").length, 0)
573
+ })));
574
+ var toNumber = (address) => address.split(".").reduce((value, octet) => value * 256 + Number(octet), 0);
575
+ var toAddress = (value) => [24, 16, 8, 0].map((shift) => Math.floor(value / 2 ** shift) % 256).join(".");
576
+ var subnetHosts = ({ address, prefixLength }) => {
577
+ if (prefixLength < largestPrefix) {
578
+ throw new Error(`The /${prefixLength} network is too large to scan; the limit is /${largestPrefix}.`);
579
+ }
580
+ const size = 2 ** (32 - prefixLength);
581
+ const network = toNumber(address) - toNumber(address) % size;
582
+ const hosts = size <= 2 ? Array.from({ length: size }, (_, index) => network + index) : Array.from({ length: size - 2 }, (_, index) => network + index + 1);
583
+ return hosts.map(toAddress).filter((host) => host !== address);
584
+ };
585
+ var accepts = (host, port) => new Promise((resolve) => {
586
+ const socket = createConnection({ host, port });
587
+ const timer = setTimeout(() => finish(false), probeTimeoutMs);
588
+ const finish = (open) => {
589
+ clearTimeout(timer);
590
+ socket.destroy();
591
+ resolve(open);
592
+ };
593
+ socket.once("connect", () => finish(true));
594
+ socket.once("error", () => finish(false));
595
+ });
596
+ var resolver = new Resolver({ timeout: 1000, tries: 1 });
597
+ var hostname = (address) => resolver.reverse(address).then((names) => names[0] ?? null, () => null);
598
+ var discoverControllers = async (network, port = runtimePort) => {
599
+ const hosts = subnetHosts(network);
600
+ const found = [];
601
+ for (let start = 0;start < hosts.length; start += probesAtOnce) {
602
+ const batch = hosts.slice(start, start + probesAtOnce);
603
+ const open = await Promise.all(batch.map((host) => accepts(host, port)));
604
+ for (const [index, host] of batch.entries()) {
605
+ if (open[index]) {
606
+ found.push({ address: host, port, hostname: await hostname(host) });
607
+ }
608
+ }
609
+ }
610
+ return found;
611
+ };
612
+
613
+ // packages/agent/src/login.ts
614
+ import { setTimeout as delay2 } from "node:timers/promises";
615
+ import {
616
+ failureReason,
617
+ findControllerLogin as findControllerLogin2,
618
+ openControllerLogin
619
+ } from "@tsplc/build";
620
+ import { LoginUnavailable, noLogin } from "@tsplc/debug";
621
+ var loginStateTimeout = 30000;
622
+ var stoppedAnswering = { error: "The login stopped answering" };
623
+ var auditOf = (command) => {
624
+ switch (command.command) {
625
+ case "write":
626
+ case "force":
627
+ return { command: command.command, values: command.values };
628
+ case "unforce":
629
+ return {
630
+ command: command.restore ? "unforce --restore" : "unforce",
631
+ values: Object.fromEntries(command.expressions.map((expression) => [expression, ""]))
632
+ };
633
+ case "start":
634
+ case "stop":
635
+ return { command: command.command, values: {} };
636
+ case "reset":
637
+ return { command: `reset ${command.kind.toLowerCase()}`, values: {} };
638
+ case "state":
639
+ case "read":
640
+ return;
641
+ }
642
+ };
643
+ var createLogin = (context) => {
644
+ const { state, operations } = context;
645
+ let generation = 0;
482
646
  let commands = Promise.resolve();
483
647
  const enqueue = (run) => {
484
- const generation = loginGeneration;
648
+ const queuedIn = generation;
485
649
  const sent = commands.then(() => {
486
- if (generation !== loginGeneration)
650
+ if (queuedIn !== generation) {
487
651
  throw new AgentError("The login was closed", 409);
652
+ }
488
653
  return run();
489
654
  });
490
655
  commands = sent.catch(() => {
@@ -492,321 +657,497 @@ var createAgent = async (options) => {
492
657
  });
493
658
  return sent;
494
659
  };
495
- const send = (login, loginCommand) => enqueue(() => login.send(loginCommand));
496
- const readLogin = async ([first, ...rest]) => {
497
- if (busy === "a login")
498
- throw new LoginUnavailable("The engineering login is opening", { state: "connecting" });
499
- if (busy)
500
- throw new LoginUnavailable(`Live values pause during ${busy}`);
501
- const login = await findControllerLogin(loginContainer);
502
- if (!login)
503
- throw new LoginUnavailable(noLogin);
504
- if (!first)
505
- return {};
506
- const result = await send(login, { command: "read", expressions: [first, ...rest] });
507
- if (!("values" in result))
508
- throw new Error("The login answered a read without values");
509
- return result.values;
510
- };
511
- const startDebugger = async () => {
512
- const release = await readJson(paths.release, releaseSchema);
513
- if (!release)
514
- return null;
515
- const { directory, manifest: releaseManifest } = await loadRelease(paths.releases, release.id);
516
- const manifestFile = join2(directory, "debug.json");
517
- if (!existsSync3(manifestFile))
518
- return null;
519
- const manifest = await loadManifest(manifestFile);
520
- const serverToken = releaseManifest.serverTokenEnv && process.env[releaseManifest.serverTokenEnv];
521
- const debug = await createDebugger({
522
- manifest,
523
- adapter: createLoginAdapter({
524
- read: readLogin,
525
- probe: manifest.build.target,
526
- endpoint: "the agent's login"
527
- }),
528
- stateDirectory: paths.debug,
529
- watch: releaseManifest.debug?.watch ?? {},
530
- ...options.serverHealthUrl && serverToken && {
531
- server: { url: new URL(options.serverHealthUrl).origin, token: serverToken }
532
- },
533
- release: { id: release.id, deployedAt: release.deployedAt, operation: release.operation },
534
- timeline: [
535
- ...(await readJsonl(paths.deployments, deploymentSchema, recentEntries)).map(({ at, ...deployment }) => timelineEntries.deploy(at, deployment)),
536
- ...(await readJsonl(paths.audit, auditSchema, recentEntries)).map(({ at, ...audit }) => timelineEntries.audit(at, audit))
537
- ],
538
- log: options.log
539
- });
540
- return { debug, handle: createDebugHandler(debug, options.log) };
541
- };
542
- const debuggerFailed = (error) => {
543
- options.log(`Starting the debugger failed: ${message(error)}`);
544
- return null;
545
- };
546
- let debugging = startDebugger().catch(debuggerFailed);
547
- const restartDebugger = () => {
548
- debugging = debugging.then(async (current) => {
549
- await current?.debug.close();
550
- return startDebugger().catch(debuggerFailed);
551
- });
660
+ const send = (login, command) => enqueue(() => login.send(command));
661
+ const requireLogin = async () => {
662
+ operations.requireIdle();
663
+ const lookedUpIn = generation;
664
+ const login = await findControllerLogin2(loginContainer);
665
+ if (lookedUpIn !== generation) {
666
+ throw new AgentError("The login was closed", 409);
667
+ }
668
+ operations.requireIdle();
669
+ if (!login) {
670
+ throw new AgentError("No login is open: tsplc login", 409);
671
+ }
672
+ return login;
552
673
  };
553
- const operation = (name, run) => {
554
- if (busy)
555
- throw new AgentError(`The agent is busy with ${busy}`, 409);
556
- busy = name;
557
- const encoder = new TextEncoder;
558
- let listening = true;
559
- return new Response(new ReadableStream({
560
- start: async (controller) => {
561
- const write = (text) => {
562
- if (listening)
563
- controller.enqueue(encoder.encode(text));
674
+ return {
675
+ read: async ([first, ...rest]) => {
676
+ const busy = operations.busy();
677
+ if (busy === "a login") {
678
+ throw new LoginUnavailable("The engineering login is opening", {
679
+ state: "connecting"
680
+ });
681
+ }
682
+ if (busy) {
683
+ throw new LoginUnavailable(`Live values pause during ${busy}`);
684
+ }
685
+ const login = await findControllerLogin2(loginContainer);
686
+ if (!login) {
687
+ throw new LoginUnavailable(noLogin);
688
+ }
689
+ if (!first) {
690
+ return {};
691
+ }
692
+ const result = await send(login, {
693
+ command: "read",
694
+ expressions: [first, ...rest]
695
+ });
696
+ if (!("values" in result)) {
697
+ throw new Error("The login answered a read without values");
698
+ }
699
+ return result.values;
700
+ },
701
+ open: async (sent) => {
702
+ const credentials = await controllerCredentials(sent);
703
+ context.log(`Opening a login with the ${sent ? "provided" : "stored"} controller user`);
704
+ const config = controllerConfig(await state.requireRelease(), await state.requireTarget(), state.paths.controller);
705
+ return operations.stream("a login", async (emit) => {
706
+ if (await findControllerLogin2(loginContainer)) {
707
+ throw new AgentError("A login is already open", 409);
708
+ }
709
+ emit({
710
+ kind: "progress",
711
+ message: "Logging in; CODESYS takes minutes to start"
712
+ });
713
+ await ensureGateway();
714
+ const login = await withCredentials(credentials, () => openControllerLogin(config, loginContainer));
715
+ return send(login, { command: "state" });
716
+ });
717
+ },
718
+ command: async (command, client) => {
719
+ const login = await requireLogin();
720
+ const change = auditOf(command);
721
+ if (!change) {
722
+ return send(login, command);
723
+ }
724
+ return enqueue(async () => {
725
+ const [first, ...rest] = Object.keys(change.values);
726
+ const previous = first ? await login.send({ command: "read", expressions: [first, ...rest] }).then((result) => ("values" in result) ? result.values : undefined).catch(() => {
727
+ return;
728
+ }) : undefined;
729
+ const audit = async (error) => {
730
+ const entry = {
731
+ at: new Date().toISOString(),
732
+ ...change,
733
+ ...previous && { previous },
734
+ ...client,
735
+ release: (await state.release())?.id,
736
+ ...error !== undefined && { error: errorMessage(error) }
737
+ };
738
+ await appendJsonl(state.paths.audit, entry);
739
+ await context.onAudit(entry);
564
740
  };
565
- const emit = (event) => write(`${JSON.stringify(event)}
566
- `);
567
- const heartbeat = setInterval(() => write(`
568
- `), 15000);
569
741
  try {
570
- emit({ kind: "done", result: await run(emit) });
742
+ const result = await login.send(command);
743
+ await audit();
744
+ return result;
571
745
  } catch (error) {
572
- options.log(`${name} failed: ${error instanceof Error ? error.stack : String(error)}`);
573
- emit({
574
- kind: "error",
575
- message: error instanceof Error ? error.message : String(error),
576
- downloadRequired: error instanceof AgentError && error.downloadRequired || error instanceof Error && error.message.includes(explicitDownload)
577
- });
578
- } finally {
579
- clearInterval(heartbeat);
580
- busy = undefined;
581
- if (listening)
582
- controller.close();
746
+ await audit(error);
747
+ throw error;
583
748
  }
584
- },
585
- cancel: () => {
586
- listening = false;
749
+ });
750
+ },
751
+ status: async () => {
752
+ const login = await findControllerLogin2(loginContainer);
753
+ if (!login) {
754
+ return null;
755
+ }
756
+ if (!await login.ready()) {
757
+ return operations.busy() === "a login" ? null : stoppedAnswering;
587
758
  }
588
- }), { headers: { "Content-Type": "application/x-ndjson" } });
759
+ try {
760
+ const loginState = await Promise.race([
761
+ send(login, { command: "state" }),
762
+ delay2(loginStateTimeout, null)
763
+ ]);
764
+ if (!loginState) {
765
+ return stoppedAnswering;
766
+ }
767
+ return "state" in loginState ? loginState : null;
768
+ } catch (error) {
769
+ return { error: failureReason(error) };
770
+ }
771
+ },
772
+ logout: async () => {
773
+ const login = await requireLogin();
774
+ return operations.exclusive("a logout", async () => {
775
+ generation++;
776
+ const failure = await login.close();
777
+ commands = Promise.resolve();
778
+ if (failure) {
779
+ context.log(`The login couldn't log out (${failure}); its container was removed`);
780
+ }
781
+ return failure ? { failure } : {};
782
+ });
783
+ }
589
784
  };
590
- const deploy = async (form, client) => {
591
- const settings = deployOptionsSchema.parse(JSON.parse(z3.string().parse(form.get("options"))));
592
- const upload = await readUpload(form);
593
- const target = await requireTarget();
594
- if (await findControllerLogin(loginContainer))
595
- throw new AgentError("A login is open; log out before deploying: tsplc logout", 409);
596
- return operation("a deployment", async (emit) => {
597
- const release = await saveRelease(paths.releases, upload);
598
- const config = controllerConfig(release, target);
599
- if (!settings.download && !existsSync3(join2(paths.controller, ".codesys/controller/current.json")))
600
- throw new AgentError("The controller has no application downloaded by this agent; only a full download can deploy", 409, true);
601
- const previous = await readJson(paths.release, releaseSchema);
602
- const serverPath = release.manifest.server && `${release.id}/${release.manifest.server}`;
603
- if (serverPath) {
604
- emit({ kind: "progress", message: "Starting the new server" });
605
- await server.replace(join2(paths.releases, serverPath));
606
- }
607
- const kind = settings.download ? "download" : "online-change";
608
- emit({ kind: "progress", message: `Starting the ${kind}` });
609
- await ensureGateway();
610
- await warming;
611
- const stopFollowing = followProgress(paths.controller, emit);
612
- const receipt = await updateWarmController(config, deployContainer, kind, {
613
- initializeUser: settings.initializeUser,
614
- credentials: settings.credentials
615
- }).catch(async (failure) => {
616
- if (serverPath) {
617
- emit({ kind: "progress", message: "Restoring the previous server" });
618
- await (previous?.server ? server.replace(join2(paths.releases, previous.server)) : server.stop());
785
+ };
786
+
787
+ // packages/agent/src/operations.ts
788
+ import { explicitDownload } from "@tsplc/build";
789
+ var createOperations = (log) => {
790
+ let busy;
791
+ const requireIdle = () => {
792
+ if (busy) {
793
+ throw new AgentError(`The agent is busy with ${busy}`, 409);
794
+ }
795
+ };
796
+ return {
797
+ busy: () => busy,
798
+ requireIdle,
799
+ exclusive: async (operation, run) => {
800
+ requireIdle();
801
+ busy = operation;
802
+ try {
803
+ return await run();
804
+ } finally {
805
+ busy = undefined;
806
+ }
807
+ },
808
+ stream: (operation, run) => {
809
+ requireIdle();
810
+ busy = operation;
811
+ const encoder = new TextEncoder;
812
+ let listening = true;
813
+ return new Response(new ReadableStream({
814
+ start: async (controller) => {
815
+ const write = (text) => {
816
+ if (listening) {
817
+ controller.enqueue(encoder.encode(text));
818
+ }
819
+ };
820
+ const emit = (event) => write(`${JSON.stringify(event)}
821
+ `);
822
+ const heartbeat = setInterval(() => write(`
823
+ `), 15000);
824
+ try {
825
+ emit({ kind: "done", result: await run(emit) });
826
+ } catch (error) {
827
+ log(`${operation} failed: ${error instanceof Error ? error.stack : String(error)}`);
828
+ emit({
829
+ kind: "error",
830
+ message: errorMessage(error),
831
+ downloadRequired: error instanceof AgentError && error.downloadRequired || error instanceof Error && error.message.includes(explicitDownload)
832
+ });
833
+ } finally {
834
+ clearInterval(heartbeat);
835
+ busy = undefined;
836
+ if (listening) {
837
+ controller.close();
838
+ }
839
+ }
840
+ },
841
+ cancel: () => {
842
+ listening = false;
619
843
  }
620
- throw failure;
621
- }).finally(stopFollowing);
622
- const deployedRelease = {
623
- id: release.id,
624
- deployedAt: new Date().toISOString(),
625
- operation: kind,
626
- controllerIds: receipt.controllerIds,
627
- server: serverPath ?? previous?.server
628
- };
629
- await writeFile2(paths.release, JSON.stringify(deployedRelease, null, 2));
630
- const debugManifest = join2(release.directory, "debug.json");
631
- const deployment = {
632
- at: deployedRelease.deployedAt,
633
- release: release.id,
634
- ...existsSync3(debugManifest) && { build: (await loadManifest(debugManifest)).build.id },
635
- operation: kind,
636
- ...client
637
- };
638
- await appendJsonl(paths.deployments, deployment);
639
- restartDebugger();
640
- return deployedRelease;
641
- });
844
+ }), { headers: { "Content-Type": "application/x-ndjson" } });
845
+ }
642
846
  };
643
- const openLogin = async (credentials) => {
644
- const release = await currentRelease();
645
- const config = controllerConfig(release, await requireTarget());
646
- return operation("a login", async (emit) => {
647
- if (await findControllerLogin(loginContainer))
648
- throw new AgentError("A login is already open", 409);
649
- emit({ kind: "progress", message: "Logging in; CODESYS takes minutes to start" });
650
- await ensureGateway();
651
- const login = await withCredentials(credentials, () => openControllerLogin(config, loginContainer));
652
- return send(login, { command: "state" });
847
+ };
848
+
849
+ // packages/agent/src/server-process.ts
850
+ import { dirname as dirname3 } from "node:path";
851
+ import { setTimeout as delay3 } from "node:timers/promises";
852
+ var healthyWithinMs = 60000;
853
+ var settleMs = 5000;
854
+ var restartDelayMs = 2000;
855
+ var createServerSupervisor = (options) => {
856
+ let current;
857
+ const spawn = (executable) => {
858
+ const command = executable.endsWith(".js") ? [process.execPath, executable] : [executable];
859
+ const child = Bun.spawn(command, {
860
+ cwd: dirname3(executable),
861
+ stdio: ["ignore", "inherit", "inherit"],
862
+ onExit: (_, code) => {
863
+ if (current?.process !== child) {
864
+ return;
865
+ }
866
+ options.log(`Server exited (${code}); restarting it in ${restartDelayMs / 1000} s`);
867
+ delay3(restartDelayMs).then(() => {
868
+ if (current?.process === child) {
869
+ current = { executable, process: spawn(executable) };
870
+ }
871
+ });
872
+ }
653
873
  });
874
+ return child;
654
875
  };
655
- const requireLogin = async () => {
656
- if (busy)
657
- throw new AgentError(`The agent is busy with ${busy}`, 409);
658
- const generation = loginGeneration;
659
- const login = await findControllerLogin(loginContainer);
660
- if (generation !== loginGeneration)
661
- throw new AgentError("The login was closed", 409);
662
- if (busy)
663
- throw new AgentError(`The agent is busy with ${busy}`, 409);
664
- if (!login)
665
- throw new AgentError("No login is open: tsplc login", 409);
666
- return login;
876
+ const start = (executable) => {
877
+ current = { executable, process: spawn(executable) };
878
+ return current.process;
879
+ };
880
+ const stop = async () => {
881
+ const running = current;
882
+ current = undefined;
883
+ if (!running) {
884
+ return;
885
+ }
886
+ running.process.kill();
887
+ await running.process.exited;
888
+ };
889
+ const healthy = async (child) => {
890
+ if (!options.healthUrl) {
891
+ await delay3(settleMs);
892
+ return child.exitCode === null;
893
+ }
894
+ const deadline = Date.now() + healthyWithinMs;
895
+ while (Date.now() < deadline && child.exitCode === null) {
896
+ if (await fetch(options.healthUrl).then((response) => response.ok, () => false)) {
897
+ return true;
898
+ }
899
+ await delay3(1000);
900
+ }
901
+ return false;
667
902
  };
668
- const command = async (loginCommand, client) => {
669
- const login = await requireLogin();
670
- const change = auditOf(loginCommand);
671
- if (!change)
672
- return send(login, loginCommand);
673
- return enqueue(async () => {
674
- const [first, ...rest] = Object.keys(change.values);
675
- const previous = first ? await login.send({ command: "read", expressions: [first, ...rest] }).then((result) => ("values" in result) ? result.values : undefined).catch(() => {
903
+ return {
904
+ start,
905
+ stop,
906
+ replace: async (executable) => {
907
+ const previous = current?.executable;
908
+ await stop();
909
+ let failure;
910
+ const started = await (async () => healthy(start(executable)))().catch((error) => {
911
+ failure = error;
912
+ return false;
913
+ });
914
+ if (started) {
676
915
  return;
677
- }) : undefined;
678
- const audit = async (error) => {
679
- const entry = {
680
- at: new Date().toISOString(),
681
- ...change,
682
- ...previous && { previous },
683
- ...client,
684
- release: (await readJson(paths.release, releaseSchema))?.id,
685
- ...error !== undefined && { error: message(error) }
686
- };
687
- await appendJsonl(paths.audit, entry);
688
- const { at, ...details } = entry;
689
- (await debugging)?.debug.record(timelineEntries.audit(at, details));
690
- };
691
- try {
692
- const result = await login.send(loginCommand);
693
- await audit();
694
- return result;
695
- } catch (error) {
696
- await audit(error);
697
- throw error;
698
916
  }
699
- });
917
+ await stop();
918
+ if (previous) {
919
+ start(previous);
920
+ }
921
+ const reason = failure instanceof Error ? failure.message : `it did not start${options.healthUrl ? ` answering ${options.healthUrl}` : ""}`;
922
+ throw new Error(`The new server failed: ${reason}. ${previous ? "The previous one is running again." : ""}`.trim(), { cause: failure });
923
+ },
924
+ status: () => current && {
925
+ executable: current.executable,
926
+ running: current.process.exitCode === null
927
+ }
700
928
  };
701
- const loginStatus = async () => {
702
- const login = await findControllerLogin(loginContainer);
703
- if (!login)
704
- return null;
705
- if (!await login.ready())
706
- return busy === "a login" ? null : stoppedAnswering;
707
- try {
708
- const state = await Promise.race([
709
- send(login, { command: "state" }),
710
- delay2(loginStateTimeout, null)
711
- ]);
712
- if (!state)
713
- return stoppedAnswering;
714
- return "state" in state ? state : null;
715
- } catch (error) {
716
- return { error: failureReason(error) };
929
+ };
930
+
931
+ // packages/agent/src/state.ts
932
+ import { existsSync as existsSync5 } from "node:fs";
933
+ import { mkdir as mkdir3, readFile as readFile5, writeFile as writeFile3 } from "node:fs/promises";
934
+ import { join as join6 } from "node:path";
935
+ var readJsonFile = async (path, schema) => existsSync5(path) ? schema.parse(JSON.parse(await readFile5(path, "utf8"))) : null;
936
+ var writeJsonFile = (path, value) => writeFile3(path, JSON.stringify(value, null, 2));
937
+ var openState = async (directory) => {
938
+ const paths = {
939
+ releases: join6(directory, "releases"),
940
+ controller: join6(directory, "controller"),
941
+ sources: join6(directory, "sources"),
942
+ release: join6(directory, "release.json"),
943
+ target: join6(directory, "target.json"),
944
+ deployments: join6(directory, "deployments.jsonl"),
945
+ audit: join6(directory, "audit.jsonl"),
946
+ debug: join6(directory, "debug")
947
+ };
948
+ await mkdir3(directory, { recursive: true });
949
+ const target = () => readJsonFile(paths.target, targetSchema);
950
+ const release = () => readJsonFile(paths.release, releaseSchema);
951
+ return {
952
+ paths,
953
+ target,
954
+ setTarget: (selected) => writeJsonFile(paths.target, selected),
955
+ requireTarget: async () => {
956
+ const selected = await target();
957
+ if (!selected) {
958
+ throw new AgentError("Select the controller first: tsplc target", 409);
959
+ }
960
+ return selected;
961
+ },
962
+ release,
963
+ setRelease: (deployed) => writeJsonFile(paths.release, deployed),
964
+ requireRelease: async () => {
965
+ const deployed = await release();
966
+ if (!deployed) {
967
+ throw new AgentError("Nothing has been deployed yet: tsplc deploy", 409);
968
+ }
969
+ return loadRelease(paths.releases, deployed.id);
717
970
  }
718
971
  };
719
- const status = async () => ({
720
- target: await readJson(paths.target, targetSchema),
721
- release: await readJson(paths.release, releaseSchema),
722
- server: server.status() ?? null,
723
- login: await loginStatus()
972
+ };
973
+
974
+ // packages/agent/src/agent.ts
975
+ var matches = (presented, token) => {
976
+ const actual = Buffer.from(presented);
977
+ const expected = Buffer.from(token);
978
+ return actual.length === expected.length && timingSafeEqual(actual, expected);
979
+ };
980
+ var createAgent = async (options) => {
981
+ const { log } = options;
982
+ const state = await openState(options.state);
983
+ const server = createServerSupervisor({
984
+ healthUrl: options.serverHealthUrl,
985
+ log
986
+ });
987
+ const deployed = await state.release();
988
+ if (deployed?.server) {
989
+ server.start(join7(state.paths.releases, deployed.server));
990
+ }
991
+ const operations = createOperations(log);
992
+ const login = createLogin({
993
+ state,
994
+ operations,
995
+ onAudit: (entry) => debugging.record(entry),
996
+ log
997
+ });
998
+ const debugging = createDebugging({
999
+ state,
1000
+ readLogin: login.read,
1001
+ serverHealthUrl: options.serverHealthUrl,
1002
+ log
1003
+ });
1004
+ const deployments = createDeployments({
1005
+ state,
1006
+ operations,
1007
+ server,
1008
+ debugging,
1009
+ log
724
1010
  });
725
1011
  const route = async (request) => {
726
1012
  const { pathname } = new URL(request.url);
727
1013
  const key = `${request.method} ${pathname}`;
728
1014
  switch (key) {
729
- case "GET /status":
730
- return json(await status());
1015
+ case "GET /status": {
1016
+ const status = {
1017
+ target: await state.target(),
1018
+ release: await state.release(),
1019
+ server: server.status() ?? null,
1020
+ login: await login.status(),
1021
+ credentialsStored: await storedCredentials() !== null
1022
+ };
1023
+ return Response.json(status);
1024
+ }
731
1025
  case "GET /interfaces":
732
- return json(networkInterfaces());
1026
+ return Response.json(networkInterfaces());
733
1027
  case "POST /discover": {
734
- const { name } = z3.strictObject({ name: z3.string() }).parse(await request.json());
1028
+ const { name } = discoverSchema.parse(await request.json());
735
1029
  const selected = networkInterfaces().find((network) => network.name === name);
736
- if (!selected)
1030
+ if (!selected) {
737
1031
  throw new AgentError(`No IPv4 interface named ${name}`, 404);
738
- return json(await discoverControllers(selected));
1032
+ }
1033
+ return Response.json(await discoverControllers(selected));
739
1034
  }
740
1035
  case "PUT /target": {
741
1036
  const target = targetSchema.parse(await request.json());
742
- await writeFile2(paths.target, JSON.stringify(target, null, 2));
743
- return json(target);
1037
+ await state.setTarget(target);
1038
+ return Response.json(target);
744
1039
  }
745
1040
  case "GET /variables":
746
- return json((await currentRelease()).manifest.variables);
1041
+ return Response.json((await state.requireRelease()).manifest.variables);
747
1042
  case "POST /deploy":
748
- return deploy(await request.formData(), clientOf(request));
1043
+ return deployments.deploy(await request.formData(), clientIdentity(request));
749
1044
  case "POST /login":
750
- return openLogin(credentialsSchema.parse(await request.json()));
1045
+ return login.open(credentialsSchema.nullable().parse(await request.json()));
751
1046
  case "POST /login/command":
752
- return json(await command(loginCommandSchema.parse(await request.json()), clientOf(request)));
753
- case "DELETE /login": {
754
- const login = await requireLogin();
755
- busy = "a logout";
756
- loginGeneration++;
757
- try {
758
- const failure = await login.close();
759
- commands = Promise.resolve();
760
- if (failure)
761
- options.log(`The login couldn't log out (${failure}); its container was removed`);
762
- return json(failure ? { failure } : {});
763
- } finally {
764
- busy = undefined;
765
- }
766
- }
1047
+ return Response.json(await login.command(loginCommandSchema.parse(await request.json()), clientIdentity(request)));
1048
+ case "DELETE /login":
1049
+ return Response.json(await login.logout());
767
1050
  default:
768
- return json({ error: `No route ${key}` }, 404);
1051
+ return Response.json({ error: `No route ${key}` }, { status: 404 });
769
1052
  }
770
1053
  };
771
- const debugRoute = async (request, route) => {
772
- const current = await debugging;
773
- if (!current)
774
- return json({ error: "The deployed release has no debug manifest, or the debugger failed to start" }, 503);
775
- return current.handle(request, route);
776
- };
777
1054
  return {
778
1055
  fetch: async (request) => {
779
1056
  const { pathname, search, searchParams } = new URL(request.url);
780
1057
  const debugPath = pathname.startsWith("/debug/");
781
- if (pathname === "/debug")
782
- return new Response(null, { status: 308, headers: { Location: `/debug/${search}` } });
783
- if (request.method === "GET" && (pathname === "/debug/" || pathname === "/debug/ui.js"))
784
- return debugRoute(request, pathname.slice("/debug".length));
1058
+ if (pathname === "/debug") {
1059
+ return new Response(null, {
1060
+ status: 308,
1061
+ headers: { Location: `/debug/${search}` }
1062
+ });
1063
+ }
1064
+ if (request.method === "GET" && (pathname === "/debug/" || pathname === "/debug/ui.js")) {
1065
+ return debugging.handle(request, pathname.slice("/debug".length));
1066
+ }
785
1067
  const presented = /^Bearer (.+)$/.exec(request.headers.get("authorization") ?? "")?.[1] ?? (debugPath ? searchParams.get("token") : null) ?? "";
786
1068
  const full = matches(presented, options.token);
787
1069
  const read = options.readToken !== undefined && matches(presented, options.readToken) && (debugPath || request.method === "GET" && pathname === "/status");
788
- if (!full && !read)
789
- return json({ error: "Unauthorized" }, 401);
1070
+ if (!full && !read) {
1071
+ return Response.json({ error: "Unauthorized" }, { status: 401 });
1072
+ }
790
1073
  try {
791
- if (debugPath)
792
- return await debugRoute(request, pathname.slice("/debug".length));
1074
+ if (debugPath) {
1075
+ return await debugging.handle(request, pathname.slice("/debug".length));
1076
+ }
793
1077
  return await route(request);
794
1078
  } catch (error) {
795
- if (error instanceof AgentError)
796
- return json({ error: error.message }, error.status);
797
- if (error instanceof z3.ZodError)
798
- return json({ error: z3.prettifyError(error) }, 400);
799
- options.log(`${request.method} ${request.url} failed: ${error instanceof Error ? error.stack : String(error)}`);
800
- return json({ error: error instanceof Error ? error.message : String(error) }, 500);
1079
+ if (error instanceof AgentError) {
1080
+ return Response.json({ error: error.message }, { status: error.status });
1081
+ }
1082
+ if (error instanceof z4.ZodError) {
1083
+ return Response.json({ error: z4.prettifyError(error) }, { status: 400 });
1084
+ }
1085
+ log(`${request.method} ${request.url} failed: ${error instanceof Error ? error.stack : String(error)}`);
1086
+ return Response.json({ error: errorMessage(error) }, { status: 500 });
801
1087
  }
802
1088
  },
803
1089
  stop: async () => {
804
- await (await debugging)?.debug.close();
1090
+ await debugging.close();
805
1091
  await server.stop();
806
1092
  }
807
1093
  };
808
1094
  };
1095
+ // packages/agent/src/terminal.ts
1096
+ import { createInterface } from "node:readline/promises";
1097
+ var ask = async (question) => {
1098
+ const lines = createInterface({
1099
+ input: process.stdin,
1100
+ output: process.stdout
1101
+ });
1102
+ try {
1103
+ return (await lines.question(question)).trim();
1104
+ } finally {
1105
+ lines.close();
1106
+ }
1107
+ };
1108
+ var askSecret = (question) => new Promise((accept, reject) => {
1109
+ if (!process.stdin.isTTY) {
1110
+ reject(new Error("Typing a secret needs an interactive terminal."));
1111
+ return;
1112
+ }
1113
+ process.stdin.setRawMode(true);
1114
+ process.stdin.setEncoding("utf8");
1115
+ process.stdin.resume();
1116
+ process.stdout.write(question);
1117
+ let secret = "";
1118
+ const finish = () => {
1119
+ process.stdin.off("data", read);
1120
+ process.stdin.setRawMode(false);
1121
+ process.stdin.pause();
1122
+ process.stdout.write(`
1123
+ `);
1124
+ };
1125
+ const read = (text) => {
1126
+ for (const character of text) {
1127
+ if (character === "\r" || character === `
1128
+ `) {
1129
+ finish();
1130
+ accept(secret);
1131
+ return;
1132
+ }
1133
+ if (character === "\x03") {
1134
+ finish();
1135
+ reject(new Error("Cancelled."));
1136
+ return;
1137
+ }
1138
+ secret = character === "" ? secret.slice(0, -1) : secret + character;
1139
+ }
1140
+ };
1141
+ process.stdin.on("data", read);
1142
+ });
1143
+ var askCredentials = async () => ({
1144
+ username: await ask("Controller username: "),
1145
+ password: await askSecret("Controller password: ")
1146
+ });
809
1147
  export {
1148
+ ask,
1149
+ askCredentials,
1150
+ askSecret,
810
1151
  auditSchema,
811
1152
  clientHeaders,
812
1153
  controllerSchema,
@@ -825,5 +1166,5 @@ export {
825
1166
  variableSchema
826
1167
  };
827
1168
 
828
- //# debugId=1614B96D4F00471464756E2164756E21
1169
+ //# debugId=F9096C79802F487164756E2164756E21
829
1170
  //# sourceMappingURL=index.js.map