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