@tsplc/tmp-agent 0.0.0-stage → 0.6.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/README.md +26 -2
  2. package/dist/cli.js +4888 -0
  3. package/dist/cli.js.map +53 -0
  4. package/dist/client.js +514 -0
  5. package/dist/client.js.map +12 -0
  6. package/dist/index.js +3680 -0
  7. package/dist/index.js.map +41 -0
  8. package/package.json +61 -4
  9. package/src/access.ts +260 -0
  10. package/src/agent.ts +461 -0
  11. package/src/audit.ts +74 -0
  12. package/src/cli.ts +290 -0
  13. package/src/client.ts +407 -0
  14. package/src/codesys.ts +195 -0
  15. package/src/dashboard/index.ts +159 -0
  16. package/src/dashboard/ui/access.ts +191 -0
  17. package/src/dashboard/ui/actions.ts +207 -0
  18. package/src/dashboard/ui/api.ts +138 -0
  19. package/src/dashboard/ui/app.ts +41 -0
  20. package/src/dashboard/ui/approval.ts +131 -0
  21. package/src/dashboard/ui/audit.ts +115 -0
  22. package/src/dashboard/ui/contract.ts +19 -0
  23. package/src/dashboard/ui/dashboard.css +1332 -0
  24. package/src/dashboard/ui/deployment.ts +431 -0
  25. package/src/dashboard/ui/deployments.ts +319 -0
  26. package/src/dashboard/ui/details.ts +214 -0
  27. package/src/dashboard/ui/dom.ts +87 -0
  28. package/src/dashboard/ui/environment.ts +345 -0
  29. package/src/dashboard/ui/format.ts +124 -0
  30. package/src/dashboard/ui/logs.ts +126 -0
  31. package/src/dashboard/ui/main.ts +88 -0
  32. package/src/dashboard/ui/overlay.ts +144 -0
  33. package/src/dashboard/ui/shell.ts +185 -0
  34. package/src/dashboard/ui/source.ts +144 -0
  35. package/src/debugging.ts +142 -0
  36. package/src/deploy.ts +203 -0
  37. package/src/deployments/health.ts +98 -0
  38. package/src/deployments/retention.ts +44 -0
  39. package/src/deployments/routes.ts +281 -0
  40. package/src/deployments/runner.ts +900 -0
  41. package/src/deployments/store.ts +209 -0
  42. package/src/deployments/submission.ts +78 -0
  43. package/src/discovery.ts +90 -0
  44. package/src/environment.ts +214 -0
  45. package/src/errors.ts +12 -0
  46. package/src/index.ts +36 -0
  47. package/src/instance.ts +51 -0
  48. package/src/login.ts +267 -0
  49. package/src/logs.ts +115 -0
  50. package/src/maintenance.ts +303 -0
  51. package/src/operations.ts +149 -0
  52. package/src/processes.ts +41 -0
  53. package/src/protocol.ts +557 -0
  54. package/src/releases.ts +414 -0
  55. package/src/restarts.ts +96 -0
  56. package/src/routes.ts +128 -0
  57. package/src/secrets.ts +174 -0
  58. package/src/server-process.ts +264 -0
  59. package/src/service.ts +194 -0
  60. package/src/sessions.ts +58 -0
  61. package/src/state.ts +126 -0
  62. package/src/tailscale.ts +112 -0
  63. package/src/terminal.ts +57 -0
  64. package/src/transfer.ts +94 -0
  65. package/src/upgrade.ts +153 -0
@@ -0,0 +1,53 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/cli.ts", "../src/access.ts", "../src/audit.ts", "../src/logs.ts", "../src/state.ts", "../src/errors.ts", "../src/protocol.ts", "../src/releases.ts", "../src/transfer.ts", "../src/sessions.ts", "../src/tailscale.ts", "../src/agent.ts", "../src/access.ts", "../src/codesys.ts", "../src/dashboard/index.ts", "../src/debugging.ts", "../src/secrets.ts", "../src/deploy.ts", "../src/deployments/runner.ts", "../src/operations.ts", "../src/deployments/health.ts", "../src/deployments/store.ts", "../src/deployments/retention.ts", "../src/deployments/submission.ts", "../src/deployments/routes.ts", "../src/discovery.ts", "../src/environment.ts", "../src/login.ts", "../src/restarts.ts", "../src/routes.ts", "../src/server-process.ts", "../src/processes.ts", "../src/instance.ts", "../src/maintenance.ts", "../src/client.ts", "../src/instance.ts", "../src/service.ts", "../src/upgrade.ts", "../src/protocol.ts", "../src/secrets.ts", "../src/service.ts", "../src/state.ts", "../src/terminal.ts", "../src/upgrade.ts"],
4
+ "sourcesContent": [
5
+ "#!/usr/bin/env bun\nimport { mkdir } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { parseArgs } from \"node:util\";\nimport { configureDocker, configureGateway } from \"@tsplc/build\";\nimport { agentTokenEnv } from \"@tsplc/config\";\nimport { tcpPort } from \"@tsplc/config/build\";\nimport { z } from \"zod\";\nimport { readAccessConfig } from \"./access\";\nimport { createAgent } from \"./agent\";\nimport { type Instance, removeInstance, restartStatus } from \"./instance\";\nimport { serviceCommand, upgradeCommand } from \"./maintenance\";\nimport { type AccessConfig, roleSchema, tsplcVersion } from \"./protocol\";\nimport {\n\tagentReadTokenEnv,\n\tagentService,\n\tagentSetting,\n\tcontrollerSecretNames,\n\tserverToken,\n} from \"./secrets\";\nimport { supervisedEnv } from \"./service\";\nimport { openState, statePaths, writeJsonFile } from \"./state\";\nimport { askCredentials, askSecret } from \"./terminal\";\nimport { versionSchema } from \"./upgrade\";\n\nconst usage = `tsplc-agent setup [--if-needed]\ntsplc-agent serve --listen host:port [--state directory] [--server-health url] [--bulk-import]\ntsplc-agent upgrade [version] [--state directory]\ntsplc-agent service install|uninstall|status [serve options] [--stop-server]\ntsplc-agent secrets set|delete <name> [--service ${agentService}]\ntsplc-agent secrets set-controller\ntsplc-agent access list|grant <login> <role>|revoke <login>|default <role|none> [--state directory]\n\nsetup Builds the CODESYS builder and gateway images, keeping each that is already right for\n this tsPLC. Builder containers run the installed tsPLC's code and CODESYS scripts, so\n only a release that changes the image's recipe (the CODESYS installation, Bun or the\n container's third-party packages) needs it; the agent says so when it does. --if-needed\n also keeps an image from before tsPLC 0.5.0 whose packages match.\nserve Serves deployments and logins. --listen is required: use the machine's Tailscale\n address, such as 100.101.102.103:4850. TSPLC_AGENT_TOKEN must hold a shared secret of\n at least 32 characters, such as one from \\`openssl rand -hex 32\\`. An optional\n TSPLC_AGENT_READ_TOKEN, as long, only reads: the debugger at /debug, GET /status\n and the dashboard.\n Each comes from its environment variable, or else from \\`secrets set\\` under ${agentService}.\n --bulk-import (experimental) brings a download without a baseline's POUs into CODESYS\n in one PLCopenXML import, importing one at a time if CODESYS reports any problem.\n The line's server writes to logs/server.log in the state directory.\nupgrade Installs @tsplc/agent at version (latest by default) with the bun or npm that installed\n this one, runs its setup if it needs one, and restarts the running agent on it. It\n refuses while a deployment runs or a login is open, and leaves the line's server running\n and the controller untouched.\nservice Runs the agent as a Windows service: a Task Scheduler task that starts it at boot as\n you, whether or not anyone logs on, and starts it again if it exits. install takes the\n serve options and asks for your Windows password; run install and uninstall in a\n PowerShell opened with Run as administrator, signed in as the user the agent runs as.\n The agent's output goes to logs/agent.log in the state directory. uninstall leaves the\n line's server running unless --stop-server.\nsecrets Stores a value a release's secrets name, typed without echo, in Bun.secrets under\n --service, or deletes it. set-controller stores the controller user, which deployments\n and logins then use when they send none. Run it as the user the agent runs as.\naccess Who on the tailnet may use the dashboard, by Tailscale login: viewer reads, deployer\n also deploys and restarts the server, admin also manages variables and access. default\n gives every other tailnet member a role, none by default. The full token is an admin,\n the read token a viewer, and a request from this PC an admin. The agent applies a\n change at once.`;\n\nconst { values, positionals } = parseArgs({\n\tallowPositionals: true,\n\toptions: {\n\t\thelp: { type: \"boolean\", short: \"h\" },\n\t\tlisten: { type: \"string\" },\n\t\tstate: { type: \"string\" },\n\t\t\"server-health\": { type: \"string\" },\n\t\t\"bulk-import\": { type: \"boolean\" },\n\t\tservice: { type: \"string\" },\n\t\t\"if-needed\": { type: \"boolean\" },\n\t\t\"stop-server\": { type: \"boolean\" },\n\t},\n});\nconst [command, ...args] = positionals;\nif (!command || values.help) {\n\tconsole.log(usage);\n\tprocess.exit(0);\n}\nconst takesArguments: Record<string, number> = {\n\tsecrets: 3,\n\taccess: 3,\n\tupgrade: 1,\n\tservice: 1,\n};\nif (args.length > (takesArguments[command] ?? 0)) {\n\tthrow new Error(`Too many arguments for ${command}. See tsplc-agent --help.`);\n}\nconst stateDirectory = values.state ?? join(homedir(), \".tsplc-agent\");\n\n/** Wildcard listen addresses, and the loopback a process on this PC reaches them by. */\nconst loopbackFor: Record<string, string> = {\n\t\"0.0.0.0\": \"127.0.0.1\",\n\t\"::\": \"::1\",\n};\n\n/** Where a process on this PC, such as the deployed server, reaches the agent. */\nconst reachableUrl = (hostname: string, port: number) => {\n\tconst bare = hostname.replace(/^\\[(.*)\\]$/, \"$1\");\n\tconst host = loopbackFor[bare] ?? bare;\n\treturn `http://${host.includes(\":\") ? `[${host}]` : host}:${port}/`;\n};\n\n/** The serve options as given, which the service and an upgraded agent repeat. */\nconst serveOptions = () => {\n\tconst [, hostname, portText] = /^(.+):(\\d+)$/.exec(values.listen ?? \"\") ?? [];\n\tconst port = tcpPort.safeParse(Number(portText));\n\tif (!hostname || !port.success) {\n\t\tthrow new Error(\"--listen host:port is required, with a TCP port.\");\n\t}\n\treturn {\n\t\thostname,\n\t\tport: port.data,\n\t\targs: [\n\t\t\t\"--listen\",\n\t\t\t`${hostname}:${port.data}`,\n\t\t\t...(values.state ? [\"--state\", values.state] : []),\n\t\t\t...(values[\"server-health\"]\n\t\t\t\t? [\"--server-health\", values[\"server-health\"]]\n\t\t\t\t: []),\n\t\t\t...(values[\"bulk-import\"] ? [\"--bulk-import\"] : []),\n\t\t],\n\t};\n};\n\nif (command === \"setup\") {\n\tawait configureDocker({\n\t\tkeepUnverified: values[\"if-needed\"] ?? false,\n\t\twinetricksCache: process.env.CODESYS_WINETRICKS_CACHE || null,\n\t});\n\tawait configureGateway();\n} else if (command === \"serve\") {\n\tconst { hostname, port, args: serve } = serveOptions();\n\tconst token = z\n\t\t.string({\n\t\t\terror: `Set ${agentTokenEnv}, or store it with tsplc-agent secrets set ${agentTokenEnv}`,\n\t\t})\n\t\t.min(32, `${agentTokenEnv} must be at least 32 characters`)\n\t\t.parse(await agentSetting(agentTokenEnv, process.env));\n\tconst readToken = z\n\t\t.string()\n\t\t.min(32, `${agentReadTokenEnv} must be at least 32 characters`)\n\t\t.refine(\n\t\t\t(value) => value !== token,\n\t\t\t`${agentReadTokenEnv} must differ from ${agentTokenEnv}`,\n\t\t)\n\t\t.nullable()\n\t\t.parse(await agentSetting(agentReadTokenEnv, process.env));\n\tconst { paths } = await openState(stateDirectory);\n\tconst agent = await createAgent({\n\t\tstate: stateDirectory,\n\t\ttoken,\n\t\treadToken,\n\t\tserverHealthUrl: values[\"server-health\"] ?? null,\n\t\tbulkImport: values[\"bulk-import\"] ?? false,\n\t\tenvironment: process.env,\n\t\tserverAccess: {\n\t\t\turl: reachableUrl(hostname, port),\n\t\t\ttoken: await serverToken(),\n\t\t},\n\t\tlog: (message) => console.log(`${new Date().toISOString()} ${message}`),\n\t\texit: ({ restart }) => {\n\t\t\tvoid removeInstance(paths.agent, process.pid).then(() =>\n\t\t\t\tprocess.exit(restart ? restartStatus : 0),\n\t\t\t);\n\t\t},\n\t});\n\tconst server = Bun.serve({\n\t\thostname,\n\t\tport,\n\t\tfetch: (request, server) => agent.fetch(request, server.requestIP(request)),\n\t\t// Deployments stream for minutes and upload a server executable.\n\t\tidleTimeout: 0,\n\t\tmaxRequestBodySize: 2 ** 30,\n\t});\n\twriteJsonFile(paths.agent, {\n\t\tpid: process.pid,\n\t\tversion: tsplcVersion,\n\t\turl: server.url.href,\n\t\tserve,\n\t\tsupervised: process.env[supervisedEnv] === \"1\",\n\t\tstartedAt: new Date().toISOString(),\n\t} satisfies Instance);\n\tconsole.log(`tsPLC agent ${tsplcVersion} listening on ${server.url}`);\n\tfor (const signal of [\"SIGINT\", \"SIGTERM\"] as const) {\n\t\tprocess.on(signal, () => {\n\t\t\tvoid agent\n\t\t\t\t.stop()\n\t\t\t\t.then(() => removeInstance(paths.agent, process.pid))\n\t\t\t\t.then(() => process.exit(0));\n\t\t});\n\t}\n} else if (command === \"upgrade\") {\n\tawait upgradeCommand({\n\t\tversion: versionSchema.parse(args[0] ?? \"latest\"),\n\t\tstate: stateDirectory,\n\t\tenvironment: process.env,\n\t});\n} else if (command === \"service\") {\n\tconst action = args[0];\n\tawait serviceCommand({\n\t\taction,\n\t\tstate: stateDirectory,\n\t\tserve: action === \"install\" || action === \"run\" ? serveOptions().args : [],\n\t\tstopServer: values[\"stop-server\"] ?? false,\n\t\tenvironment: process.env,\n\t});\n} else if (command === \"secrets\") {\n\tconst [action, name, ...extra] = args;\n\tconst service = values.service ?? agentService;\n\tif (action === \"set\" && name && !extra.length) {\n\t\tawait Bun.secrets.set({\n\t\t\tservice,\n\t\t\tname,\n\t\t\tvalue: await askSecret(`${name}: `),\n\t\t});\n\t} else if (action === \"delete\" && name && !extra.length) {\n\t\tif (!(await Bun.secrets.delete({ service, name }))) {\n\t\t\tthrow new Error(`Service ${service} has no ${name}.`);\n\t\t}\n\t} else if (action === \"set-controller\" && !name) {\n\t\tconst { username, password } = await askCredentials();\n\t\tawait Bun.secrets.set({\n\t\t\tservice: agentService,\n\t\t\tname: controllerSecretNames.username,\n\t\t\tvalue: username,\n\t\t});\n\t\tawait Bun.secrets.set({\n\t\t\tservice: agentService,\n\t\t\tname: controllerSecretNames.password,\n\t\t\tvalue: password,\n\t\t});\n\t} else {\n\t\tthrow new Error(\n\t\t\t\"Usage: tsplc-agent secrets set|delete <name> [--service service], or secrets set-controller\",\n\t\t);\n\t}\n} else if (command === \"access\") {\n\tconst file = statePaths(stateDirectory).access;\n\tconst config = await readAccessConfig(file);\n\tconst [action, first, second, ...extra] = args;\n\tconst change = ((): AccessConfig | null => {\n\t\tif (action === \"grant\" && first && second && !extra.length) {\n\t\t\treturn {\n\t\t\t\t...config,\n\t\t\t\troles: { ...config.roles, [first]: roleSchema.parse(second) },\n\t\t\t};\n\t\t}\n\t\tif (action === \"revoke\" && first && !second) {\n\t\t\tif (!(first in config.roles)) {\n\t\t\t\tthrow new Error(`${first} has no role.`);\n\t\t\t}\n\t\t\treturn {\n\t\t\t\t...config,\n\t\t\t\troles: Object.fromEntries(\n\t\t\t\t\tObject.entries(config.roles).filter(([login]) => login !== first),\n\t\t\t\t),\n\t\t\t};\n\t\t}\n\t\tif (action === \"default\" && first && !second) {\n\t\t\treturn {\n\t\t\t\t...config,\n\t\t\t\ttailnetDefault: first === \"none\" ? null : roleSchema.parse(first),\n\t\t\t};\n\t\t}\n\t\tif (action === \"list\" && !first) {\n\t\t\treturn null;\n\t\t}\n\t\tthrow new Error(\n\t\t\t\"Usage: tsplc-agent access list|grant <login> <role>|revoke <login>|default <role|none>\",\n\t\t);\n\t})();\n\tif (change) {\n\t\tawait mkdir(stateDirectory, { recursive: true });\n\t\twriteJsonFile(file, change);\n\t}\n\tconst shown = change ?? config;\n\tfor (const [login, role] of Object.entries(shown.roles)) {\n\t\tconsole.log(`${login}\\t${role}`);\n\t}\n\tconsole.log(`Other tailnet members: ${shown.tailnetDefault ?? \"none\"}`);\n} else {\n\tthrow new Error(`Unknown command ${command}.`);\n}\n",
6
+ "import { createHash, timingSafeEqual } from \"node:crypto\";\nimport { isIP } from \"node:net\";\nimport { dashboardHeader, tokenQueryParameter } from \"@tsplc/debug/api\";\nimport { controllerRestartPath } from \"@tsplc/server/plant-agent\";\nimport { type AuditLog, authorOf } from \"./audit\";\nimport { errorMessage } from \"./errors\";\nimport {\n\ttype AccessConfig,\n\taccessConfigSchema,\n\tdebuggerMount,\n\ttype Identity,\n\tsessionRequestSchema,\n} from \"./protocol\";\nimport type { ApiRoute } from \"./routes\";\nimport { createSessions } from \"./sessions\";\nimport { readJsonFile, writeJsonFile } from \"./state\";\nimport { peerKind, type Whois } from \"./tailscale\";\n\nconst noAccess: AccessConfig = { roles: {}, tailnetDefault: null };\n\nexport const readAccessConfig = async (file: string) =>\n\t(await readJsonFile(file, accessConfigSchema)) ?? noAccess;\n\n/** Compares digests, so the time taken says nothing about the token, not even its length. */\nconst matches = (presented: string, token: string) =>\n\ttimingSafeEqual(\n\t\tcreateHash(\"sha256\").update(presented).digest(),\n\t\tcreateHash(\"sha256\").update(token).digest(),\n\t);\n\n/** Where a request came from, as the HTTP server reports it. */\nexport interface Peer {\n\taddress: string;\n}\n\nconst refuse = (status: 401 | 403, error: string) =>\n\tResponse.json({ error }, { status });\nconst unauthorized = () => refuse(401, \"Unauthorized\");\n\n/** A proxy on the agent's PC would make every request it forwards look local. */\nconst forwardingHeaders = [\n\t\"forwarded\",\n\t\"x-forwarded-for\",\n\t\"tailscale-user-login\",\n];\n\n/**\n * Whether the request names the agent by an address, a single-label name or a MagicDNS name.\n * Another site that points its own name at the agent (DNS rebinding) names it by that, and gets\n * no identity from where the browser runs.\n */\nconst namesAgentDirectly = (request: Request) => {\n\tconst host = new URL(request.url).hostname.replace(/^\\[(.*)\\]$/, \"$1\");\n\treturn (\n\t\tisIP(host) !== 0 ||\n\t\t!host.includes(\".\") ||\n\t\thost.endsWith(\".ts.net\") ||\n\t\thost === \"localhost\"\n\t);\n};\n\n/** Anything but `GET` may change something, so another site must not be able to send it. */\nconst changes = (request: Request) => request.method !== \"GET\";\nconst fromDashboard = (request: Request) =>\n\trequest.headers.get(dashboardHeader) === \"1\";\nconst crossSite = () =>\n\trefuse(\n\t\t403,\n\t\t`A browser's request that changes something needs the ${dashboardHeader}: 1 header`,\n\t);\n\n/**\n * Who a request is from, and the role that gives them. The full token is an admin and the read\n * token a viewer, as a bearer token or a browser session signed in with one. The deployed server's\n * token restarts the controller and does nothing else; no browser signs in with it. Under `/api` and\n * `/debug`, a request from the agent's own PC is an admin, and one from a tailnet member has the\n * role `access.json` gives their login.\n */\nexport const createAccess = (options: {\n\ttoken: string;\n\treadToken: string | null;\n\t/** The token the agent starts the deployed server with, which may only restart the controller. */\n\tserverToken: string | null;\n\t/** `access.json`, read on each tailnet request so `tsplc-agent access` applies at once. */\n\tfile: string;\n\twhois: Whois;\n\taudit: AuditLog;\n\tnow: () => number;\n\tlog: (message: string) => void;\n}) => {\n\tconst sessions = createSessions(options.now);\n\n\tconst tokenIdentity = (presented: string): Identity | null => {\n\t\tif (matches(presented, options.token)) {\n\t\t\treturn { login: null, name: \"Agent token\", role: \"admin\", via: \"token\" };\n\t\t}\n\t\tif (options.readToken !== null && matches(presented, options.readToken)) {\n\t\t\treturn {\n\t\t\t\tlogin: null,\n\t\t\t\tname: \"Read token\",\n\t\t\t\trole: \"viewer\",\n\t\t\t\tvia: \"token\",\n\t\t\t};\n\t\t}\n\t\treturn null;\n\t};\n\n\tconst serverIdentity: Identity = {\n\t\tlogin: null,\n\t\tname: \"Line server\",\n\t\trole: \"deployer\",\n\t\tvia: \"server\",\n\t};\n\n\tconst peerIdentity = async (\n\t\trequest: Request,\n\t\tpeer: Peer | null,\n\t): Promise<Identity | null> => {\n\t\tif (\n\t\t\t!peer ||\n\t\t\t!namesAgentDirectly(request) ||\n\t\t\tforwardingHeaders.some((name) => request.headers.has(name))\n\t\t) {\n\t\t\treturn null;\n\t\t}\n\t\tconst kind = peerKind(peer.address);\n\t\tif (kind === \"loopback\") {\n\t\t\treturn { login: null, name: \"This PC\", role: \"admin\", via: \"local\" };\n\t\t}\n\t\tif (kind !== \"tailnet\") {\n\t\t\treturn null;\n\t\t}\n\t\tconst user = await options.whois(peer.address);\n\t\tif (!user) {\n\t\t\treturn null;\n\t\t}\n\t\t// A hand-edited file that doesn't parse gives no one a role until it is fixed.\n\t\tconst config = await readAccessConfig(options.file).catch(\n\t\t\t(error: unknown) => {\n\t\t\t\toptions.log(`Can't read ${options.file}: ${errorMessage(error)}`);\n\t\t\t\treturn noAccess;\n\t\t\t},\n\t\t);\n\t\tconst role = config.roles[user.login] ?? config.tailnetDefault;\n\t\treturn (\n\t\t\trole && { login: user.login, name: user.name, role, via: \"tailscale\" }\n\t\t);\n\t};\n\n\t/**\n\t * The request's identity, or the refusal to answer it with. A route a browser calls also takes\n\t * a browser's session or where the request comes from; the CLI's take only a token.\n\t */\n\tconst identify = async (\n\t\trequest: Request,\n\t\tpeer: Peer | null,\n\t\troute: { browser: boolean },\n\t): Promise<Identity | Response> => {\n\t\tconst { searchParams, pathname } = new URL(request.url);\n\t\t// EventSource can't send headers, so the debugger also takes the token in the query.\n\t\tconst presented =\n\t\t\t/^Bearer (.+)$/.exec(request.headers.get(\"authorization\") ?? \"\")?.[1] ??\n\t\t\t(pathname.startsWith(debuggerMount)\n\t\t\t\t? searchParams.get(tokenQueryParameter)\n\t\t\t\t: null);\n\t\tif (presented !== null) {\n\t\t\tif (\n\t\t\t\toptions.serverToken !== null &&\n\t\t\t\tmatches(presented, options.serverToken)\n\t\t\t) {\n\t\t\t\treturn request.method === \"POST\" && pathname === controllerRestartPath\n\t\t\t\t\t? serverIdentity\n\t\t\t\t\t: refuse(403, \"The server's token only restarts the controller\");\n\t\t\t}\n\t\t\treturn tokenIdentity(presented) ?? unauthorized();\n\t\t}\n\t\tif (!route.browser) {\n\t\t\treturn unauthorized();\n\t\t}\n\t\tconst identity =\n\t\t\tsessions.find(request) ?? (await peerIdentity(request, peer));\n\t\tif (!identity) {\n\t\t\treturn unauthorized();\n\t\t}\n\t\treturn changes(request) && !fromDashboard(request) ? crossSite() : identity;\n\t};\n\n\t/** Signs a browser in and out, which needs no identity: the answer, or null for another route. */\n\tconst handle = async (request: Request): Promise<Response | null> => {\n\t\tconst { pathname } = new URL(request.url);\n\t\tif (\n\t\t\tpathname !== \"/api/session\" ||\n\t\t\t(request.method !== \"POST\" && request.method !== \"DELETE\")\n\t\t) {\n\t\t\treturn null;\n\t\t}\n\t\tif (!fromDashboard(request)) {\n\t\t\treturn crossSite();\n\t\t}\n\t\tif (request.method === \"DELETE\") {\n\t\t\treturn new Response(null, {\n\t\t\t\tstatus: 204,\n\t\t\t\theaders: { \"Set-Cookie\": sessions.close(request) },\n\t\t\t});\n\t\t}\n\t\tconst body = sessionRequestSchema.safeParse(\n\t\t\tawait request.json().catch(() => null),\n\t\t);\n\t\tif (!body.success) {\n\t\t\treturn Response.json({ error: \"Send { token }\" }, { status: 400 });\n\t\t}\n\t\tconst identity = tokenIdentity(body.data.token);\n\t\tif (!identity) {\n\t\t\treturn unauthorized();\n\t\t}\n\t\treturn Response.json(identity, {\n\t\t\theaders: { \"Set-Cookie\": sessions.open(identity) },\n\t\t});\n\t};\n\n\tconst routes: ApiRoute[] = [\n\t\t{\n\t\t\tmethod: \"GET\",\n\t\t\tpattern: \"/api/session\",\n\t\t\trole: \"viewer\",\n\t\t\thandle: async (_request, { identity }) => Response.json(identity),\n\t\t},\n\t\t{\n\t\t\tmethod: \"GET\",\n\t\t\tpattern: \"/api/access\",\n\t\t\trole: \"admin\",\n\t\t\thandle: async () => Response.json(await readAccessConfig(options.file)),\n\t\t},\n\t\t{\n\t\t\tmethod: \"PUT\",\n\t\t\tpattern: \"/api/access\",\n\t\t\trole: \"admin\",\n\t\t\thandle: async (request, { identity }) => {\n\t\t\t\tconst config = accessConfigSchema.parse(await request.json());\n\t\t\t\tconst previous = await readAccessConfig(options.file);\n\t\t\t\twriteJsonFile(options.file, config);\n\t\t\t\tawait options.audit.record({\n\t\t\t\t\tby: authorOf(identity),\n\t\t\t\t\tcommand: \"access\",\n\t\t\t\t\tvalues: auditedAccess(config),\n\t\t\t\t\tprevious: auditedAccess(previous),\n\t\t\t\t\terror: null,\n\t\t\t\t});\n\t\t\t\treturn Response.json(config);\n\t\t\t},\n\t\t},\n\t];\n\treturn { identify, handle, routes };\n};\n\n/** Who has which role, as the audit log lists it: each login's role, and the tailnet default. */\nconst auditedAccess = (config: AccessConfig) => ({\n\t...config.roles,\n\t\"(tailnet default)\": config.tailnetDefault ?? \"none\",\n});\n",
7
+ "import { z } from \"zod\";\nimport { appendJsonl, readJsonl } from \"./logs\";\nimport { type Audit, auditSchema, type Identity } from \"./protocol\";\nimport type { ApiRoute } from \"./routes\";\n\n/** How many entries `GET /api/audit` answers without `?limit=`, and at most. */\nexport const auditLimits = { default: 100, max: 1000 } as const;\n\nconst auditQuerySchema = z.object({\n\tlimit: z.coerce\n\t\t.number()\n\t\t.int()\n\t\t.positive()\n\t\t.max(auditLimits.max)\n\t\t.default(auditLimits.default),\n});\n\n/**\n * Who an entry names: a dashboard user by their login or name, or, for a login command, the user\n * and host its client reports and the release it ran against.\n */\ntype Author = Pick<Audit, \"user\" | \"host\" | \"release\">;\n\n/** How the audit log names whoever a request identifies. */\nexport const authorOf = (identity: Identity): Author => ({\n\tuser: identity.login ?? identity.name,\n});\n\n/**\n * The agent's `audit.jsonl`: login commands that changed the controller, and the dashboard's\n * changes to access, the environment and the server, by who made them.\n */\nexport const createAudit = (context: {\n\tfile: string;\n\tonRecord: (entry: Audit) => Promise<void>;\n}) => {\n\tconst record = async (change: {\n\t\tby: Author;\n\t\t/** What was done, such as `environment set API_TOKEN`. */\n\t\tcommand: string;\n\t\tvalues: Audit[\"values\"];\n\t\tprevious: Audit[\"previous\"] | null;\n\t\terror: string | null;\n\t}) => {\n\t\tconst entry: Audit = {\n\t\t\tat: new Date().toISOString(),\n\t\t\tcommand: change.command,\n\t\t\tvalues: change.values,\n\t\t\t...(change.previous && { previous: change.previous }),\n\t\t\t...change.by,\n\t\t\t...(change.error !== null && { error: change.error }),\n\t\t};\n\t\tawait appendJsonl(context.file, entry);\n\t\tawait context.onRecord(entry);\n\t};\n\n\tconst routes: ApiRoute[] = [\n\t\t{\n\t\t\tmethod: \"GET\",\n\t\t\tpattern: \"/api/audit\",\n\t\t\trole: \"viewer\",\n\t\t\thandle: async (request) => {\n\t\t\t\tconst { limit } = auditQuerySchema.parse(\n\t\t\t\t\tObject.fromEntries(new URL(request.url).searchParams),\n\t\t\t\t);\n\t\t\t\treturn Response.json(\n\t\t\t\t\t(await readJsonl(context.file, auditSchema, limit)).reverse(),\n\t\t\t\t);\n\t\t\t},\n\t\t},\n\t];\n\treturn { record, routes };\n};\nexport type AuditLog = ReturnType<typeof createAudit>;\n",
8
+ "import {\n\tcloseSync,\n\texistsSync,\n\topenSync,\n\trenameSync,\n\tstatSync,\n\twriteSync,\n} from \"node:fs\";\nimport { open } from \"node:fs/promises\";\nimport { z } from \"zod\";\nimport { readTextIfPresent } from \"./state\";\n\n/** Renames `file` to `<file>.1`, replacing the one before, once it reaches `bytes`. */\nconst rotateLog = (file: string, bytes: number) => {\n\tif (existsSync(file) && statSync(file).size >= bytes) {\n\t\trenameSync(file, `${file}.1`);\n\t}\n};\n\n/** A process's output log rotates when a process starts into it past this size. */\nconst outputLogBytes = 10 * 2 ** 20;\n\n/** Starts `command` with its output appended to `log`, rotating the log first. */\nexport const spawnWithLog = (\n\tcommand: string[],\n\tlog: string,\n\toptions: Pick<\n\t\tBun.SpawnOptions.SpawnOptions<\"ignore\", number, number>,\n\t\t\"cwd\" | \"env\" | \"detached\" | \"windowsHide\"\n\t> & {\n\t\t/** Written to the log after it rotates and before the process's output. */\n\t\theading?: string;\n\t},\n) => {\n\tconst { heading, ...spawnOptions } = options;\n\trotateLog(log, outputLogBytes);\n\tconst output = openSync(log, \"a\");\n\ttry {\n\t\tif (heading) {\n\t\t\twriteSync(output, heading);\n\t\t}\n\t\treturn Bun.spawn(command, {\n\t\t\t...spawnOptions,\n\t\t\tstdio: [\"ignore\", output, output],\n\t\t});\n\t} finally {\n\t\tcloseSync(output);\n\t}\n};\n\n/** Appends one JSON line to `file`, on a line of its own after any partial line a crash left. */\nexport const appendJsonLine = async (file: string, value: unknown) => {\n\tconst log = await open(file, \"a+\");\n\ttry {\n\t\tconst { size } = await log.stat();\n\t\tconst last = Buffer.alloc(1);\n\t\tif (size) {\n\t\t\tawait log.read(last, 0, 1, size - 1);\n\t\t}\n\t\tconst separator = size && last[0] !== 10 ? \"\\n\" : \"\";\n\t\tawait log.writeFile(`${separator}${JSON.stringify(value)}\\n`);\n\t} finally {\n\t\tawait log.close();\n\t}\n};\n\n/** An append-only log rotates once it reaches this size. */\nconst appendOnlyBytes = 5 * 2 ** 20;\n\n/** Appends one JSON line to an append-only log, keeping it and its rotated copy bounded. */\nexport const appendJsonl = async (file: string, value: unknown) => {\n\trotateLog(file, appendOnlyBytes);\n\tawait appendJsonLine(file, value);\n};\n\nexport const parsesAsJson = (line: string): { json: unknown } | null => {\n\ttry {\n\t\treturn { json: JSON.parse(line) };\n\t} catch {\n\t\treturn null;\n\t}\n};\n\n/**\n * The newest `limit` lines of a log, oldest first. A line a crash left half written isn't JSON\n * and is skipped; a whole line its schema refuses is an error.\n */\nexport const readJsonl = async <T>(\n\tfile: string,\n\tschema: z.ZodType<T>,\n\tlimit: number,\n) => {\n\tconst text = await readTextIfPresent(file);\n\tif (text === null) {\n\t\treturn [];\n\t}\n\treturn text\n\t\t.split(\"\\n\")\n\t\t.map((line, index) => ({ line, number: index + 1 }))\n\t\t.filter(({ line }) => line)\n\t\t.slice(-limit)\n\t\t.flatMap(({ line, number }) => {\n\t\t\tconst parsed = parsesAsJson(line);\n\t\t\tif (!parsed) {\n\t\t\t\treturn [];\n\t\t\t}\n\t\t\tconst entry = schema.safeParse(parsed.json);\n\t\t\tif (!entry.success) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Line ${number} of ${file} isn't a valid entry: ${z.prettifyError(entry.error)}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn [entry.data];\n\t\t});\n};\n",
9
+ "import { randomUUID } from \"node:crypto\";\nimport { renameSync, writeFileSync } from \"node:fs\";\nimport { mkdir, readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { z } from \"zod\";\nimport { AgentError } from \"./errors\";\nimport {\n\ttype Release,\n\treleaseSchema,\n\ttype Target,\n\ttargetSchema,\n} from \"./protocol\";\nimport { loadRelease } from \"./releases\";\n\n/** The text of the file at `path`, or null when there is none. Failing to read it is an error. */\nexport const readTextIfPresent = (path: string) =>\n\treadFile(path, \"utf8\").catch((error: unknown) => {\n\t\tif (error instanceof Error && \"code\" in error && error.code === \"ENOENT\") {\n\t\t\treturn null;\n\t\t}\n\t\tthrow error;\n\t});\n\n/** The JSON file at `path`, checked against `schema`, or null when there is none. */\nexport const readJsonFile = async <T>(path: string, schema: z.ZodType<T>) => {\n\tconst text = await readTextIfPresent(path);\n\treturn text === null ? null : schema.parse(JSON.parse(text));\n};\n\n/**\n * The JSON file at `path`, or null when there is none or its content isn't `schema`'s, such as a\n * record an agent of another version wrote. Failing to read it is an error.\n */\nexport const readJsonFileIfValid = <T>(path: string, schema: z.ZodType<T>) =>\n\treadJsonFile(path, schema).catch((error: unknown) => {\n\t\tif (error instanceof SyntaxError || error instanceof z.ZodError) {\n\t\t\treturn null;\n\t\t}\n\t\tthrow error;\n\t});\n\n/**\n * Replaces the JSON file at `path` whole, before anything else runs: a reader never sees half of\n * it, and each write has a temporary file of its own, so writers in other processes don't collide.\n */\nexport const writeJsonFile = (path: string, value: unknown) => {\n\tconst temporary = `${path}.${randomUUID()}.tmp`;\n\twriteFileSync(temporary, JSON.stringify(value, null, 2));\n\trenameSync(temporary, path);\n};\n\n/** Each file and directory of the agent's state directory `directory`. */\nexport const statePaths = (directory: string) => ({\n\treleases: join(directory, \"releases\"),\n\tcontroller: join(directory, \"controller\"),\n\t/** The deploying release's ST with its secrets filled in. */\n\tsources: join(directory, \"sources\"),\n\trelease: join(directory, \"release.json\"),\n\ttarget: join(directory, \"target.json\"),\n\tdeployments: join(directory, \"deployments.jsonl\"),\n\t/** Each deployment's record and log, under its id. */\n\tdeploymentRecords: join(directory, \"deployments\"),\n\taudit: join(directory, \"audit.jsonl\"),\n\t/** Who on the tailnet has which role. */\n\taccess: join(directory, \"access.json\"),\n\t/**\n\t * The names the dashboard stored by Bun.secrets service, since Bun.secrets can't list a\n\t * service's names. Never a value.\n\t */\n\tenvironment: join(directory, \"environment.json\"),\n\t/** The plain variables set on this PC, by name. */\n\tvariables: join(directory, \"variables.json\"),\n\tdebug: join(directory, \"debug\"),\n\t/** The running server's process, for the agent that takes it over. */\n\tserver: join(directory, \"server.json\"),\n\t/** The running agent: its process, address and serve arguments. */\n\tagent: join(directory, \"agent.json\"),\n\tlogs: join(directory, \"logs\"),\n\t/** The server's output. */\n\tserverLog: join(directory, \"logs\", \"server.log\"),\n\t/** The agent's output when `tsplc-agent service run` or `upgrade` starts it. */\n\tagentLog: join(directory, \"logs\", \"agent.log\"),\n});\n\n/**\n * The agent's state directory: releases, the controller's download baseline, the selected\n * target, the deployed release and the logs.\n */\nexport const openState = async (directory: string) => {\n\tconst paths = statePaths(directory);\n\tawait mkdir(paths.logs, { recursive: true });\n\n\tconst target = () => readJsonFile(paths.target, targetSchema);\n\tconst release = () => readJsonFile(paths.release, releaseSchema);\n\n\treturn {\n\t\tpaths,\n\t\t/** The selected controller, or null before `tsplc target`. */\n\t\ttarget,\n\t\tsetTarget: async (selected: Target) =>\n\t\t\twriteJsonFile(paths.target, selected),\n\t\trequireTarget: async () => {\n\t\t\tconst selected = await target();\n\t\t\tif (!selected) {\n\t\t\t\tthrow new AgentError(\"Select the controller first: tsplc target\", 409);\n\t\t\t}\n\t\t\treturn selected;\n\t\t},\n\t\t/** The deployed release, or null before the first deployment. */\n\t\trelease,\n\t\tsetRelease: async (deployed: Release) =>\n\t\t\twriteJsonFile(paths.release, deployed),\n\t\t/** The deployed release's files and manifest. */\n\t\trequireRelease: async () => {\n\t\t\tconst deployed = await release();\n\t\t\tif (!deployed) {\n\t\t\t\tthrow new AgentError(\n\t\t\t\t\t\"Nothing has been deployed yet: tsplc deploy\",\n\t\t\t\t\t409,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn loadRelease(paths.releases, deployed.id);\n\t\t},\n\t};\n};\nexport type AgentState = Awaited<ReturnType<typeof openState>>;\n",
10
+ "/** A request the agent refuses, answered with `status` and the message. */\nexport class AgentError extends Error {\n\tconstructor(\n\t\tmessage: string,\n\t\treadonly status: number,\n\t) {\n\t\tsuper(message);\n\t}\n}\n\nexport const errorMessage = (error: unknown) =>\n\terror instanceof Error ? error.message : String(error);\n",
11
+ "import {\n\tcontrollerCredentialsSchema,\n\tcontrollerIdsSchema,\n\tloginStateSchema,\n\tonlineChangeFindingSchema,\n\trollbackSchema,\n} from \"@tsplc/build\";\nimport { plainValue, secretValue, tsplcConfigSchema } from \"@tsplc/config\";\nimport { envName, releaseConfigSchema, tcpPort } from \"@tsplc/config/build\";\nimport { z } from \"zod\";\nimport { version } from \"../package.json\";\n\n/** The tsPLC version a client and the agent it deploys through must share. */\nexport const tsplcVersion = version;\n\n/** The controller the agent deploys to, as its runtime's TCP block driver address. */\nexport const targetSchema = z.strictObject({\n\thost: z.string().nonempty(),\n\tport: tcpPort,\n});\nexport type Target = z.infer<typeof targetSchema>;\n\nexport const networkInterfaceSchema = z.strictObject({\n\tname: z.string(),\n\taddress: z.ipv4(),\n\tprefixLength: z.number().int().min(0).max(32),\n});\nexport type NetworkInterface = z.infer<typeof networkInterfaceSchema>;\n\n/** A host on the scanned subnet that accepts connections on the CODESYS runtime port. */\nexport const discoveredControllerSchema = z.strictObject({\n\taddress: z.ipv4(),\n\tport: z.number().int(),\n\thostname: z.string().nullable(),\n});\nexport type DiscoveredController = z.infer<typeof discoveredControllerSchema>;\n\n/** `POST /discover`: the network interface to scan for controllers. */\nexport const discoverSchema = z.strictObject({ name: z.string() });\n\n/**\n * The controller's user, which the agent passes to CODESYS for one operation. A request sends\n * null instead to use the one stored on the agent's PC.\n */\nexport type Credentials = z.infer<typeof controllerCredentialsSchema>;\n\n/** A published leaf of the deployed program, as CODESYS expressions name it. */\nexport const variableSchema = z.strictObject({\n\tpath: z.string(),\n\ttype: z.string(),\n});\nexport type Variable = z.infer<typeof variableSchema>;\n\n/** A target's plain values, by variable name. */\nconst targetValuesSchema = z.record(envName, z.string());\n\n/**\n * What `tsplc deploy` uploads beside its files. `config` is the build config with paths\n * relative to the release: `st/`, `template.project` and `libraries/`.\n */\nexport const releaseManifestSchema = z.strictObject({\n\t// Checked against the owner's schema but kept as uploaded: the release id hashes the manifest.\n\tconfig: z.record(z.string(), z.unknown()).superRefine((config, context) => {\n\t\tconst release = releaseConfigSchema.safeParse(config);\n\t\tif (!release.success) {\n\t\t\tcontext.addIssue({\n\t\t\t\tcode: \"custom\",\n\t\t\t\tmessage: `Invalid release config: ${z.prettifyError(release.error)}`,\n\t\t\t});\n\t\t}\n\t}),\n\tvariables: z.array(variableSchema),\n\t/** The server executable's path in the release, when the project builds one. */\n\tserver: z.string().nonempty().optional(),\n\t/** The project's `debug` section; the program's debug manifest is the release's `debug.json`. */\n\tdebug: tsplcConfigSchema.shape.debug,\n\t/** The variable in the agent's environment holding the server's bearer token, for its telemetry and request trace. */\n\tserverTokenEnv: z.string().nonempty().optional(),\n\t/** The project's `secrets`, whose placeholders in the ST the agent fills in from Bun.secrets. */\n\tsecrets: tsplcConfigSchema.shape.secrets,\n\t/** The values of the target it was built for, which its server starts with; none in a release from before 0.5.12. */\n\tvalues: targetValuesSchema.default({}),\n});\nexport type ReleaseManifest = z.infer<typeof releaseManifestSchema>;\n\n/** How `tsplc deploy` compresses each file of a multipart upload, the only form agents without `POST /releases/compare` accept. */\nexport const uploadEncoding = \"gzip\";\n\n/** The commit a deployment was built from, when `tsplc deploy` ran in a git checkout. */\nexport const gitSourceSchema = z.strictObject({\n\tcommit: z.string().nonempty(),\n\tbranch: z.string().nullable(),\n\t/** Uncommitted changes went into the build. */\n\tdirty: z.boolean(),\n\t/** The commit's subject line. */\n\tmessage: z.string().nullable(),\n});\nexport type GitSource = z.infer<typeof gitSourceSchema>;\n\n/**\n * How a deployment applies: `apply` runs it as soon as it is its turn; `review` builds it and\n * checks what an online change would do, then waits for someone to approve it.\n */\nexport const deploymentModeSchema = z.enum([\"apply\", \"review\"]);\nexport type DeploymentMode = z.infer<typeof deploymentModeSchema>;\n\n/**\n * What `tsplc deploy` sends with a release to `POST /api/deployments`, in the upload's `options`\n * beside the existing deploy options.\n */\nexport const deploymentRequestSchema = z.strictObject({\n\tmode: deploymentModeSchema,\n\tgit: gitSourceSchema.nullable(),\n});\n\nexport const deployOptionsSchema = z\n\t.strictObject({\n\t\tcredentials: controllerCredentialsSchema.nullable(),\n\t\t/** A full download stops the application; without it only an online change is applied. */\n\t\tdownload: z.boolean(),\n\t\tinitializeUser: z.boolean(),\n\t\t/** How `POST /api/deployments` queues it; `POST /deploy` runs it at once and ignores this. */\n\t\tdeployment: deploymentRequestSchema.optional(),\n\t})\n\t.refine(\n\t\t(options) => options.credentials || !options.initializeUser,\n\t\t\"Initializing the controller's user needs the user's credentials.\",\n\t);\nexport type DeployOptions = z.infer<typeof deployOptionsSchema>;\n\n/** How many buckets a release's files fall into for `POST /releases/compare`. */\nexport const releaseBuckets = 256;\n\n/** A release id, or the start of a SHA-256 of content: 16 lowercase hex digits. */\nconst shortHex = z.string().regex(/^[a-f0-9]{16}$/);\n\n/** `POST /releases/compare`: the digest of each bucket of the release about to be deployed. */\nexport const compareRequestSchema = z.strictObject({\n\tbuckets: z.array(shortHex).length(releaseBuckets),\n});\n\n/**\n * Its answer: the stored release the upload can build on, and that release's files, by path and\n * digest, in each bucket that differs. Without a base the whole release is uploaded.\n */\nexport const comparisonSchema = z.strictObject({\n\tbase: shortHex.nullable(),\n\tchanged: z.array(\n\t\tz.strictObject({\n\t\t\tbucket: z\n\t\t\t\t.number()\n\t\t\t\t.int()\n\t\t\t\t.min(0)\n\t\t\t\t.max(releaseBuckets - 1),\n\t\t\tfiles: z.record(z.string(), shortHex),\n\t\t}),\n\t),\n});\nexport type Comparison = z.infer<typeof comparisonSchema>;\n\n/** A `POST /deploy` body in this form is one release upload rather than a multipart form. */\nexport const releaseUploadType = \"application/vnd.tsplc.release+zstd\";\n\n/**\n * A release upload's header. The release is `base`'s files without the `remove` paths, with the\n * uploaded files added or replacing theirs; `buckets` are the digests it must then have.\n */\nexport const releaseUploadSchema = z.strictObject({\n\tmanifest: releaseManifestSchema,\n\toptions: deployOptionsSchema,\n\tbase: shortHex.nullable(),\n\tbuckets: compareRequestSchema.shape.buckets,\n\tremove: z.array(z.string()),\n});\nexport type ReleaseUpload = z.infer<typeof releaseUploadSchema>;\n\n/** Long operations stream one of these per line. */\nexport const eventSchema = z.discriminatedUnion(\"kind\", [\n\tz.strictObject({ kind: z.literal(\"progress\"), message: z.string() }),\n\tz.strictObject({ kind: z.literal(\"done\"), result: z.unknown() }),\n\tz.strictObject({\n\t\tkind: z.literal(\"error\"),\n\t\tmessage: z.string(),\n\t\t/** The controller has no application from this agent yet, so only a full download can deploy. */\n\t\tdownloadRequired: z.boolean(),\n\t\t/**\n\t\t * What became of the controller after a download failed mid-transfer. Sent only to clients that\n\t\t * send their version, since earlier clients reject an event with fields they don't know.\n\t\t */\n\t\trollback: rollbackSchema.optional(),\n\t}),\n]);\nexport type AgentEvent = z.infer<typeof eventSchema>;\n\nconst deployOperationSchema = z.enum([\"download\", \"online-change\"]);\n\nexport const releaseSchema = z.strictObject({\n\tid: z.string(),\n\tdeployedAt: z.iso.datetime(),\n\toperation: deployOperationSchema,\n\tcontrollerIds: controllerIdsSchema,\n\t/** The running server executable, relative to the releases directory. */\n\tserver: z.string().optional(),\n});\nexport type Release = z.infer<typeof releaseSchema>;\n\nexport const statusSchema = z.strictObject({\n\ttarget: targetSchema.nullable(),\n\trelease: releaseSchema.nullable(),\n\tserver: z\n\t\t.strictObject({ executable: z.string(), running: z.boolean() })\n\t\t.nullable(),\n\t/** The open login's application state and forced expressions, or why it can't report them. */\n\tlogin: z\n\t\t.union([loginStateSchema, z.strictObject({ error: z.string() })])\n\t\t.nullable(),\n\t/** A controller user is stored on the agent's PC, so requests may leave theirs out. */\n\tcredentialsStored: z.boolean(),\n});\nexport type AgentStatus = z.infer<typeof statusSchema>;\n\n/** The agent's status, which names the agent's version even to a request it refuses. */\nexport const statusPath = \"/status\";\n\n/** `POST` holds the agent for an upgrade, so it takes no operations; `DELETE` lets it take them again. */\nexport const agentHoldPath = \"/agent/hold\";\n\n/** `POST`: a held agent exits, as `exitSchema` asks. */\nexport const agentExitPath = \"/agent/exit\";\n\n/**\n * How a held agent exits: leaving the line's server running for the next agent or stopping it,\n * and whether whatever started it should start it again.\n */\nexport const exitSchema = z.strictObject({\n\tserver: z.enum([\"leave\", \"stop\"]),\n\trestart: z.boolean(),\n});\nexport type AgentExit = z.infer<typeof exitSchema>;\n\n/** A logout's result: why the login couldn't log out, when its container had to be removed instead. */\nexport const logoutSchema = z.strictObject({ failure: z.string().optional() });\n\n/** Who ran a command, and with which tsPLC, as the client reports it in these headers. */\nexport const clientHeaders = {\n\tuser: \"x-tsplc-user\",\n\thost: \"x-tsplc-host\",\n\tversion: \"x-tsplc-version\",\n\t/** The client's `workerScriptsDigest`, which tells a local build from a release of its version. */\n\tscripts: \"x-tsplc-scripts\",\n} as const;\n\n/** The header each agent response names the agent's tsPLC version in; agents before 0.3.0 send none. */\nexport const agentVersionHeader = \"x-tsplc-agent-version\";\n\n/** Whether `version` is at least `minimum`, comparing major, minor and patch. */\nconst atLeast = (version: string, minimum: [number, number, number]) => {\n\tconst parts = version.split(/[.+-]/).slice(0, 3).map(Number);\n\tfor (const [index, wanted] of minimum.entries()) {\n\t\tconst part = parts[index] ?? 0;\n\t\tif (part !== wanted) {\n\t\t\treturn part > wanted;\n\t\t}\n\t}\n\treturn true;\n};\n\n/** Whether an agent of `version` has `tsplc-agent upgrade`, which arrived in 0.5.0. */\nexport const upgradesItself = (version: string | null) =>\n\tversion !== null && atLeast(version, [0, 5, 0]);\n\n/** Why a client and an agent of different tsPLC versions don't deploy, and what to do about it. */\nexport const versionMismatch = (versions: {\n\tagent: string | null;\n\tclient: string;\n\t/** The agent has `tsplc-agent upgrade`. */\n\tagentUpgrades: boolean;\n}) =>\n\t`The plant agent runs ${versions.agent ? `tsPLC ${versions.agent}` : \"a tsPLC older than 0.3.0\"}, but this deployment comes from tsPLC ${versions.client}. A release is compiled by the agent's own CODESYS scripts, so the two must match: on the plant PC, run ${versions.agentUpgrades ? `tsplc-agent upgrade ${versions.client}` : `bun add --global @tsplc/agent@${versions.client}, then restart tsplc-agent serve`}${versions.agent ? `, or deploy with tsPLC ${versions.agent}` : \"\"}`;\n\n/** Who sent a request, as the client reports it. */\nexport const clientIdentity = (request: Request) => {\n\tconst header = (name: string) =>\n\t\trequest.headers.get(name)?.slice(0, 200) || undefined;\n\treturn { user: header(clientHeaders.user), host: header(clientHeaders.host) };\n};\nexport type ClientIdentity = ReturnType<typeof clientIdentity>;\n\n/** The tsPLC a request's client runs, as it reports it; clients before 0.3.0 report none. */\nexport const clientRelease = (request: Request) => ({\n\tversion:\n\t\trequest.headers.get(clientHeaders.version)?.slice(0, 50) || undefined,\n\tscripts:\n\t\trequest.headers.get(clientHeaders.scripts)?.slice(0, 100) || undefined,\n});\nexport type ClientRelease = ReturnType<typeof clientRelease>;\n\n/** A line of the agent's `deployments.jsonl`. */\nexport const deploymentSchema = z.strictObject({\n\tat: z.iso.datetime(),\n\trelease: z.string(),\n\t/** The debug manifest's build id, when the release has one. */\n\tbuild: z.string().optional(),\n\toperation: deployOperationSchema,\n\t/** Whether the request sent the controller user or the agent used its stored one; lines from before 0.2.18 lack it. */\n\tcredentials: z.enum([\"provided\", \"stored\"]).optional(),\n\tuser: z.string().optional(),\n\thost: z.string().optional(),\n});\nexport type Deployment = z.infer<typeof deploymentSchema>;\n\n/** A line of the agent's `audit.jsonl`: a login command that changed the controller. */\nexport const auditSchema = z.strictObject({\n\tat: z.iso.datetime(),\n\t/** As typed after `tsplc`, such as `force` or `reset cold`. */\n\tcommand: z.string(),\n\t/** Expressions written or forced, with their values; unforced expressions map to \"\". */\n\tvalues: z.record(z.string(), z.string()),\n\t/** The values read just before the command, when the read succeeded. */\n\tprevious: z.record(z.string(), z.string()).optional(),\n\tuser: z.string().optional(),\n\thost: z.string().optional(),\n\trelease: z.string().optional(),\n\terror: z.string().optional(),\n});\nexport type Audit = z.infer<typeof auditSchema>;\n\n/**\n * Who may do what on the agent's dashboard and API, each role including the ones before it: a\n * viewer reads deployments, logs, the debugger and the audit log; a deployer also deploys,\n * approves, cancels, redeploys, rolls back and restarts the server; an admin also manages the\n * environment's secrets and who has which role.\n */\nexport const roles = [\"viewer\", \"deployer\", \"admin\"] as const;\nexport const roleSchema = z.enum(roles);\nexport type Role = z.infer<typeof roleSchema>;\n\nexport const allows = (role: Role, required: Role) =>\n\troles.indexOf(role) >= roles.indexOf(required);\n\n/** Who made a request, and how the agent knows. */\nexport const identitySchema = z.strictObject({\n\t/** The Tailscale login, or null for a token or a request from the agent's own PC. */\n\tlogin: z.string().nullable(),\n\t/** A name to show: the Tailscale display name, or how the token or PC is known. */\n\tname: z.string(),\n\trole: roleSchema,\n\t/** `server`: the deployed server, with the token the agent started it with. */\n\tvia: z.enum([\"tailscale\", \"token\", \"local\", \"server\"]),\n});\nexport type Identity = z.infer<typeof identitySchema>;\n\n/**\n * Where a deployment is. `awaitingApproval` waits on a person: a review to apply, or a full\n * download that would stop the line. A finished deployment is `ready`, `error` or `canceled`.\n */\nexport const deploymentStateSchema = z.enum([\n\t\"queued\",\n\t\"building\",\n\t\"awaitingApproval\",\n\t\"applying\",\n\t\"starting\",\n\t\"verifying\",\n\t\"ready\",\n\t\"error\",\n\t\"canceled\",\n]);\nexport type DeploymentState = z.infer<typeof deploymentStateSchema>;\n\n/** States a deployment never leaves. */\nexport const finalStates: readonly DeploymentState[] = [\n\t\"ready\",\n\t\"error\",\n\t\"canceled\",\n];\n\n/** States a deployment may still be canceled in: anything before it applies. */\nexport const cancelableStates: readonly DeploymentState[] = [\n\t\"queued\",\n\t\"building\",\n\t\"awaitingApproval\",\n];\n\n/** The steps a deployment goes through, in order; a deployment skips the ones it doesn't need. */\nexport const deploymentPhaseNameSchema = z.enum([\n\t\"queue\",\n\t\"build\",\n\t\"review\",\n\t\"apply\",\n\t\"server\",\n\t\"health\",\n]);\n\nconst deploymentIdSchema = z.string().regex(/^dpl_[a-z0-9]{16,32}$/);\n\n/**\n * A deployment as the agent keeps it, in `deployments/<id>/record.json` of its state directory.\n * Every record of the last 14 days is kept, and always the running one and the last that was\n * healthy, with their releases.\n */\nexport const deploymentRecordSchema = z.strictObject({\n\tid: deploymentIdSchema,\n\trelease: z.string(),\n\t/** The debug manifest's build id, when the release has one. */\n\tbuild: z.string().nullable(),\n\tcreatedAt: z.iso.datetime(),\n\tupdatedAt: z.iso.datetime(),\n\t/** An upload from `tsplc deploy`, or a release the agent already had, deployed again. */\n\torigin: z.discriminatedUnion(\"kind\", [\n\t\tz.strictObject({ kind: z.literal(\"upload\") }),\n\t\tz.strictObject({ kind: z.literal(\"redeploy\"), from: deploymentIdSchema }),\n\t\tz.strictObject({ kind: z.literal(\"rollback\"), from: deploymentIdSchema }),\n\t]),\n\tgit: gitSourceSchema.nullable(),\n\t/** Who asked for it: the identity behind the request, with the deploying machine's user and host. */\n\trequestedBy: z.strictObject({\n\t\tidentity: identitySchema.omit({ role: true }),\n\t\tuser: z.string().nullable(),\n\t\thost: z.string().nullable(),\n\t}),\n\tmode: deploymentModeSchema,\n\t/** What it applies or applied: an online change unless a full download was asked for or approved. */\n\toperation: deployOperationSchema,\n\tstate: deploymentStateSchema,\n\tphases: z.array(\n\t\tz.strictObject({\n\t\t\tname: deploymentPhaseNameSchema,\n\t\t\tstartedAt: z.iso.datetime(),\n\t\t\tfinishedAt: z.iso.datetime().nullable(),\n\t\t\toutcome: z.enum([\"running\", \"ok\", \"failed\", \"skipped\"]),\n\t\t}),\n\t),\n\t/** What the online-change check found: refusals, and what the change restarts. */\n\tfindings: z.array(onlineChangeFindingSchema),\n\t/** What it waits on while `awaitingApproval`. */\n\tapproval: z\n\t\t.strictObject({\n\t\t\treason: z.enum([\"review\", \"downloadRequired\"]),\n\t\t\tmessage: z.string(),\n\t\t})\n\t\t.nullable(),\n\terror: z\n\t\t.strictObject({\n\t\t\tmessage: z.string(),\n\t\t\tdownloadRequired: z.boolean(),\n\t\t\trollback: rollbackSchema.optional(),\n\t\t})\n\t\t.nullable(),\n\tcontrollerIds: controllerIdsSchema.nullable(),\n\t/** What the check after applying found; null until it ran. */\n\thealth: z\n\t\t.strictObject({\n\t\t\tcontroller: z.enum([\"ok\", \"failed\"]),\n\t\t\tserver: z.enum([\"ok\", \"failed\", \"none\"]),\n\t\t\tplc: z.enum([\"ok\", \"failed\", \"unknown\"]),\n\t\t\tdetail: z.string().nullable(),\n\t\t})\n\t\t.nullable(),\n\t/** When it became the running deployment, and when another replaced it; null until and while. */\n\tactiveFrom: z.iso.datetime().nullable(),\n\tactiveUntil: z.iso.datetime().nullable(),\n});\nexport type DeploymentRecord = z.infer<typeof deploymentRecordSchema>;\n\n/** One line of a deployment's log, `deployments/<id>/log.jsonl`. */\nexport const deploymentLogLineSchema = z.strictObject({\n\t/** Counts from 1 within the deployment; `?after=` resumes from it. */\n\tseq: z.number().int().positive(),\n\tat: z.iso.datetime(),\n\tlevel: z.enum([\"info\", \"warning\", \"error\"]),\n\tphase: deploymentPhaseNameSchema.nullable(),\n\tmessage: z.string(),\n});\nexport type DeploymentLogLine = z.infer<typeof deploymentLogLineSchema>;\n\n/** A change to a deployment, as its subscribers and its server-sent events carry it. */\nexport type DeploymentEvent =\n\t| { kind: \"record\"; record: DeploymentRecord }\n\t| { kind: \"log\"; line: DeploymentLogLine };\n\n/** The deployments API: `POST` queues a release, `GET` lists the deployments. */\nexport const deploymentsApiPath = \"/api/deployments\";\n\n/** Deployment `id` in the deployments API; its actions and views are below it. */\nexport const deploymentApiPath = (id: string) =>\n\t`${deploymentsApiPath}/${encodeURIComponent(id)}`;\n\n/** Deployment `id`'s page on the dashboard. */\nexport const deploymentPagePath = (id: string) =>\n\t`/deployments/${encodeURIComponent(id)}`;\n\n/** Where the agent serves the debugger. */\nexport const debuggerMount = \"/debug/\";\n\n/** `POST /api/deployments`'s answer: the queued deployment and the dashboard page that shows it. */\nexport const deploymentCreatedSchema = z.strictObject({\n\tid: deploymentIdSchema,\n\turl: z.string(),\n});\n\n/** `GET /api/deployments`: newest first, with the running and last healthy ones named. */\nexport const deploymentListSchema = z.strictObject({\n\tdeployments: z.array(deploymentRecordSchema),\n\tcurrent: deploymentIdSchema.nullable(),\n\tlastGood: deploymentIdSchema.nullable(),\n});\n\n/** `POST /api/deployments/:id/approve`: apply it, as a full download when one is required. */\nexport const approveSchema = z.strictObject({ download: z.boolean() });\n\n/** `POST /api/deployments/:id/redeploy`: deploy its release again. */\nexport const redeploySchema = z.strictObject({ mode: deploymentModeSchema });\n\n/** `GET /api/deployments/:id/source`: the release's files, by path, with their sizes in bytes. */\nexport const deploymentSourceSchema = z.strictObject({\n\tfiles: z.array(\n\t\tz.strictObject({ path: z.string(), size: z.number().int().nonnegative() }),\n\t),\n});\n\n/** A secret the deployed release's config declares, or one stored without a declaration: never its value. */\nconst environmentEntrySchema = z.strictObject({\n\tname: z.string(),\n\tdeclared: z.boolean(),\n\tset: z.boolean(),\n});\nexport type EnvironmentEntry = z.infer<typeof environmentEntrySchema>;\n\n/** `GET /api/environment`: the plant PC's variables, and what the running release was built with. */\nexport const environmentSchema = z.strictObject({\n\t/** The plain values the running release was built with, from the config's target and this PC. */\n\tvalues: targetValuesSchema,\n\t/** The plain variables stored on this PC, which the next deployment is built with. */\n\tvariables: z.record(envName, z.string()),\n\tsecrets: z.array(environmentEntrySchema),\n});\nexport type EnvironmentListing = z.infer<typeof environmentSchema>;\n\n/**\n * `access.json` in the agent's state directory, and the body of `GET` and `PUT /api/access`: the\n * role of each Tailscale login, and the role a tailnet member without one gets, none by default.\n */\nexport const accessConfigSchema = z.strictObject({\n\troles: z.record(z.string().nonempty(), roleSchema),\n\ttailnetDefault: roleSchema.nullable(),\n});\nexport type AccessConfig = z.infer<typeof accessConfigSchema>;\n\n/** `POST /api/session`: the agent's full or read token, which signs a browser in. */\nexport const sessionRequestSchema = z.strictObject({ token: z.string() });\n\n/** `PUT /api/environment/:name`: a plain variable's new value, shown and built with, or a secret's. */\nexport const environmentValueSchema = z.discriminatedUnion(\"secret\", [\n\tz.strictObject({ secret: z.literal(false), value: plainValue }),\n\tz.strictObject({ secret: z.literal(true), value: secretValue }),\n]);\nexport type EnvironmentValue = z.infer<typeof environmentValueSchema>;\n",
12
+ "import { createHash } from \"node:crypto\";\nimport { existsSync } from \"node:fs\";\nimport {\n\tmkdir,\n\tmkdtemp,\n\treaddir,\n\treadFile,\n\trename,\n\trm,\n\tstat,\n\twriteFile,\n} from \"node:fs/promises\";\nimport {\n\tdirname,\n\tisAbsolute,\n\tjoin,\n\tposix,\n\trelative,\n\tresolve,\n\tsep,\n} from \"node:path\";\nimport { z } from \"zod\";\nimport { AgentError } from \"./errors\";\nimport {\n\ttype Comparison,\n\ttype DeployOptions,\n\tdeployOptionsSchema,\n\ttype ReleaseManifest,\n\ttype ReleaseUpload,\n\treleaseManifestSchema,\n\treleaseUploadSchema,\n\treleaseUploadType,\n\tuploadEncoding,\n} from \"./protocol\";\nimport {\n\tbucketDigests,\n\tdecodeUpload,\n\tfileBucket,\n\ttype ReleaseContent,\n\tshortDigest,\n} from \"./transfer\";\n\n/** Uploaded files are named `files/<path in the release>`. */\nconst filePrefix = \"files/\";\n\nconst releasePath = (name: string) => {\n\tconst path = posix.normalize(name);\n\tif (posix.isAbsolute(path) || path.startsWith(\"..\") || path.includes(\"\\\\\")) {\n\t\tthrow new Error(`Invalid release file name: ${name}`);\n\t}\n\treturn path;\n};\n\n/** A release to store: its manifest and every file. */\nexport interface Upload {\n\tmanifest: ReleaseManifest;\n\tfiles: ReleaseContent[];\n}\n\nconst checkServer = ({ manifest, files }: Upload) => {\n\tif (manifest.server && !files.some((file) => file.path === manifest.server)) {\n\t\tthrow new Error(\n\t\t\t`The release names a server ${manifest.server} it doesn't contain`,\n\t\t);\n\t}\n};\n\n/** An uploaded release, from the multipart form `tsplc deploy` sends an agent that can't compare releases. */\nexport const readUpload = async (form: FormData): Promise<Upload> => {\n\tif (form.get(\"encoding\") !== uploadEncoding) {\n\t\tthrow new Error(\n\t\t\t\"This deployment came from an older tsplc: update tsplc where you deploy from.\",\n\t\t);\n\t}\n\tconst manifest = releaseManifestSchema.parse(\n\t\tJSON.parse(z.string().parse(form.get(\"manifest\"))),\n\t);\n\tconst files = await Promise.all(\n\t\t[...form.entries()]\n\t\t\t.filter(([name]) => name.startsWith(filePrefix))\n\t\t\t.map(async ([name, value]) => ({\n\t\t\t\tpath: releasePath(name.slice(filePrefix.length)),\n\t\t\t\tcontent: Bun.gunzipSync(await z.instanceof(File).parse(value).bytes()),\n\t\t\t})),\n\t);\n\tconst upload = { manifest, files };\n\tcheckServer(upload);\n\treturn upload;\n};\n\n/** A deployment's options and release, from either form of `POST /deploy`. */\nexport interface DeployRequest {\n\tsettings: DeployOptions;\n\tupload: Upload;\n}\n\n/**\n * Reads `POST /deploy`: a release upload built on a stored release, or the multipart form of a\n * tsplc from before `POST /releases/compare`.\n */\nexport const readDeployRequest = async (\n\treleases: ReleaseStore,\n\trequest: Request,\n): Promise<DeployRequest> => {\n\tconst type = request.headers.get(\"content-type\") ?? \"\";\n\tif (type.split(\";\")[0]?.trim() === releaseUploadType) {\n\t\tconst { header, files } = await decodeUpload(await request.bytes());\n\t\tconst upload = releaseUploadSchema.parse(header);\n\t\treturn {\n\t\t\tsettings: upload.options,\n\t\t\tupload: await releases.assemble(upload, files),\n\t\t};\n\t}\n\tif (type.startsWith(\"multipart/form-data\")) {\n\t\tconst form = await request.formData();\n\t\treturn {\n\t\t\tsettings: deployOptionsSchema.parse(\n\t\t\t\tJSON.parse(z.string().parse(form.get(\"options\"))),\n\t\t\t),\n\t\t\tupload: await readUpload(form),\n\t\t};\n\t}\n\tthrow new AgentError(`Unsupported deployment content type ${type}`, 415);\n};\n\n/** A stored release's manifest, which `tsplc deploy` uploads beside its files. */\nexport const manifestFile = \"manifest.json\";\n\n/** Whether release `id` is stored, complete, under `releases`. */\nexport const isStored = (releases: string, id: string) =>\n\texistsSync(join(releases, id, manifestFile));\n\n/** The ids of the releases stored under `releases`, leaving out uploads still being stored. */\nconst storedIds = async (releases: string) =>\n\texistsSync(releases)\n\t\t? (await readdir(releases, { withFileTypes: true }))\n\t\t\t\t.filter((entry) => entry.isDirectory() && !entry.name.startsWith(\".\"))\n\t\t\t\t.map((entry) => entry.name)\n\t\t: [];\n\n/** Each file of the release in `directory`: its path in the release, and where it is. */\nasync function* releaseFiles(directory: string) {\n\tfor await (const found of new Bun.Glob(\"**/*\").scan({\n\t\tcwd: directory,\n\t\tdot: true,\n\t})) {\n\t\tyield { path: found.split(sep).join(\"/\"), file: join(directory, found) };\n\t}\n}\n\n/** A release in the releases directory. */\nexport interface StoredRelease {\n\tid: string;\n\tdirectory: string;\n\tmanifest: ReleaseManifest;\n}\n\n/**\n * Stores a release under `releases/<id>`, where the id hashes its contents, so the same\n * upload twice is one release. Each release is complete before it appears.\n */\nexport const saveRelease = async (\n\treleases: string,\n\t{ manifest, files }: Upload,\n): Promise<StoredRelease> => {\n\tconst hash = createHash(\"sha256\").update(JSON.stringify(manifest));\n\tfor (const file of [...files].sort((a, b) => a.path.localeCompare(b.path))) {\n\t\thash\n\t\t\t.update(file.path)\n\t\t\t.update(createHash(\"sha256\").update(file.content).digest(\"hex\"));\n\t}\n\tconst id = hash.digest(\"hex\").slice(0, 16);\n\tconst directory = join(releases, id);\n\tif (!existsSync(directory)) {\n\t\tawait mkdir(releases, { recursive: true });\n\t\tconst staging = await mkdtemp(join(releases, \".upload-\"));\n\t\ttry {\n\t\t\tfor (const file of files) {\n\t\t\t\tawait mkdir(dirname(join(staging, file.path)), { recursive: true });\n\t\t\t\t// Uploads lose their mode; the server must stay executable outside Windows.\n\t\t\t\tawait writeFile(join(staging, file.path), file.content, {\n\t\t\t\t\tmode: file.path === manifest.server ? 0o755 : 0o644,\n\t\t\t\t});\n\t\t\t}\n\t\t\tawait writeFile(\n\t\t\t\tjoin(staging, manifestFile),\n\t\t\t\tJSON.stringify(manifest, null, 2),\n\t\t\t);\n\t\t\tawait rename(staging, directory);\n\t\t} catch (cause) {\n\t\t\tawait rm(staging, { recursive: true, force: true });\n\t\t\tthrow cause;\n\t\t}\n\t}\n\treturn { id, directory, manifest };\n};\n\nexport const loadRelease = async (\n\treleases: string,\n\tid: string,\n): Promise<StoredRelease> => {\n\tconst directory = join(releases, id);\n\tconst manifest = releaseManifestSchema.parse(\n\t\tJSON.parse(await readFile(join(directory, manifestFile), \"utf8\")),\n\t);\n\treturn { id, directory, manifest };\n};\n\n/** The release's server as `Release.server` records it: relative to the releases directory. */\nexport const releaseServerPath = (release: StoredRelease) =>\n\trelease.manifest.server && `${release.id}/${release.manifest.server}`;\n\n/** The release a `Release.server` path is in, which may be an earlier one than the deployed release. */\nexport const serverReleaseId = (serverPath: string) => {\n\tconst slash = serverPath.indexOf(\"/\");\n\treturn slash === -1 ? serverPath : serverPath.slice(0, slash);\n};\n\n/** Where the server at `serverPath`, as `Release.server` records it, is stored under `releases`. */\nexport const releaseServerFile = (releases: string, serverPath: string) =>\n\tjoin(releases, serverPath);\n\n/** The stored release under `releases` that `file`, a server `releaseServerFile` named, lies in. */\nexport const storedReleaseOf = (releases: string, file: string) => {\n\tconst id = serverReleaseId(relative(releases, file).split(sep).join(\"/\"));\n\tif (!id) {\n\t\tthrow new Error(`${file} lies in no release under ${releases}`);\n\t}\n\treturn loadRelease(releases, id);\n};\n\n/** A stored release's files, by path in the release, with their sizes in bytes. */\nexport const listReleaseFiles = async (releases: string, id: string) => {\n\tif (!isStored(releases, id)) {\n\t\tthrow new AgentError(`The release ${id} is no longer stored`, 404);\n\t}\n\tconst files: { path: string; size: number }[] = [];\n\tfor await (const { path, file } of releaseFiles(join(releases, id))) {\n\t\tfiles.push({ path, size: (await stat(file)).size });\n\t}\n\treturn files.sort((left, right) => left.path.localeCompare(right.path));\n};\n\n/** One file of a stored release; a path that leaves the release is refused. */\nexport const readReleaseFile = async (\n\treleases: string,\n\tid: string,\n\tpath: string,\n) => {\n\tconst directory = resolve(releases, id);\n\tconst file = resolve(directory, path);\n\tconst inside = relative(directory, file);\n\tif (inside === \"\" || inside.startsWith(\"..\") || isAbsolute(inside)) {\n\t\tthrow new AgentError(`${path} isn't a path in a release`, 400);\n\t}\n\tif (\n\t\t!(await stat(file).then(\n\t\t\t(found) => found.isFile(),\n\t\t\t() => false,\n\t\t))\n\t) {\n\t\tthrow new AgentError(`The release ${id} has no file ${path}`, 404);\n\t}\n\treturn Bun.file(file);\n};\n\n/** Deletes every stored release but the `kept` ones; uploads still being stored are left alone. */\nexport const pruneReleases = async (\n\treleases: string,\n\tkept: ReadonlySet<string>,\n) => {\n\tconst removed = (await storedIds(releases)).filter((id) => !kept.has(id));\n\tfor (const id of removed) {\n\t\tawait rm(join(releases, id), { recursive: true, force: true });\n\t}\n\treturn removed;\n};\n\n/** A stored release's files by path, with their digests, and its bucket digests. */\ninterface ReleaseIndex {\n\tfiles: Map<string, string>;\n\tbuckets: string[];\n}\n\n/**\n * Compares uploads with the stored releases and builds releases from them. Stored releases never\n * change, so each one's index is read once.\n */\nexport const createReleaseStore = (releases: string) => {\n\tconst indexes = new Map<string, Promise<ReleaseIndex>>();\n\n\tconst readIndex = async (id: string): Promise<ReleaseIndex> => {\n\t\tconst files = new Map<string, string>();\n\t\tfor await (const { path, file } of releaseFiles(join(releases, id))) {\n\t\t\t// The release's manifest travels in the upload's header, not as one of its files.\n\t\t\tif (path !== manifestFile) {\n\t\t\t\tfiles.set(path, shortDigest(await readFile(file)));\n\t\t\t}\n\t\t}\n\t\tconst digests = [...files].map(([path, digest]) => ({ path, digest }));\n\t\treturn { files, buckets: bucketDigests(digests) };\n\t};\n\tconst index = (id: string) => {\n\t\tconst known = indexes.get(id);\n\t\tif (known) {\n\t\t\treturn known;\n\t\t}\n\t\tconst reading = readIndex(id);\n\t\tindexes.set(id, reading);\n\t\treading.catch(() => indexes.delete(id));\n\t\treturn reading;\n\t};\n\n\t/** The most recently stored release, which a failed deployment of the same program leaves behind. */\n\tconst newest = async () => {\n\t\tconst stored = await Promise.all(\n\t\t\t(await storedIds(releases)).map(async (id) => ({\n\t\t\t\tid,\n\t\t\t\tcreated: (await stat(join(releases, id))).mtimeMs,\n\t\t\t})),\n\t\t);\n\t\treturn stored.sort((left, right) => right.created - left.created)[0]?.id;\n\t};\n\n\treturn {\n\t\t/** The candidate, of the deployed release and the newest stored one, that differs from `buckets` least. */\n\t\tcompare: async (\n\t\t\tbuckets: readonly string[],\n\t\t\tdeployed: string | null,\n\t\t): Promise<Comparison> => {\n\t\t\tconst candidates = [\n\t\t\t\t...new Set([deployed, await newest()].filter((id) => id != null)),\n\t\t\t].filter((id) => isStored(releases, id));\n\t\t\tconst compared = await Promise.all(\n\t\t\t\tcandidates.map(async (id) => {\n\t\t\t\t\tconst { files, buckets: stored } = await index(id);\n\t\t\t\t\tconst changed = buckets.flatMap((digest, bucket) =>\n\t\t\t\t\t\tstored[bucket] === digest ? [] : [bucket],\n\t\t\t\t\t);\n\t\t\t\t\treturn { id, files, changed };\n\t\t\t\t}),\n\t\t\t);\n\t\t\tconst [best] = compared.sort(\n\t\t\t\t(left, right) => left.changed.length - right.changed.length,\n\t\t\t);\n\t\t\tif (!best) {\n\t\t\t\treturn { base: null, changed: [] };\n\t\t\t}\n\t\t\tconst changed = new Map<number, Record<string, string>>(\n\t\t\t\tbest.changed.map((bucket) => [bucket, {}]),\n\t\t\t);\n\t\t\tfor (const [path, digest] of best.files) {\n\t\t\t\tconst held = changed.get(fileBucket(path));\n\t\t\t\tif (held) {\n\t\t\t\t\theld[path] = digest;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tbase: best.id,\n\t\t\t\tchanged: [...changed].map(([bucket, files]) => ({ bucket, files })),\n\t\t\t};\n\t\t},\n\n\t\t/** The release an upload describes, checked against the bucket digests it was sent with. */\n\t\tassemble: async (\n\t\t\t{ manifest, base, buckets, remove }: ReleaseUpload,\n\t\t\tuploaded: readonly ReleaseContent[],\n\t\t): Promise<Upload> => {\n\t\t\tconst files = new Map(\n\t\t\t\tuploaded.map(({ path, content }) => [releasePath(path), content]),\n\t\t\t);\n\t\t\tif (files.size !== uploaded.length) {\n\t\t\t\tthrow new AgentError(\"The release upload sends a file twice\", 400);\n\t\t\t}\n\t\t\tif (base !== null) {\n\t\t\t\tif (!isStored(releases, base)) {\n\t\t\t\t\tthrow new AgentError(\n\t\t\t\t\t\t`The release ${base} this upload builds on is gone; deploy again`,\n\t\t\t\t\t\t409,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst removed = new Set(remove);\n\t\t\t\tconst reused = [...(await index(base)).files.keys()].filter(\n\t\t\t\t\t(path) => !removed.has(path) && !files.has(path),\n\t\t\t\t);\n\t\t\t\tfor (const path of reused) {\n\t\t\t\t\tfiles.set(\n\t\t\t\t\t\tpath,\n\t\t\t\t\t\tnew Uint8Array(await readFile(join(releases, base, path))),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst assembled = bucketDigests(\n\t\t\t\t[...files].map(([path, content]) => ({\n\t\t\t\t\tpath,\n\t\t\t\t\tdigest: shortDigest(content),\n\t\t\t\t})),\n\t\t\t);\n\t\t\tif (assembled.some((digest, bucket) => digest !== buckets[bucket])) {\n\t\t\t\tthrow new AgentError(\n\t\t\t\t\t\"The release upload doesn't match the release it describes; deploy again\",\n\t\t\t\t\t400,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst upload = {\n\t\t\t\tmanifest,\n\t\t\t\tfiles: [...files].map(([path, content]) => ({ path, content })),\n\t\t\t};\n\t\t\tcheckServer(upload);\n\t\t\treturn upload;\n\t\t},\n\t};\n};\nexport type ReleaseStore = ReturnType<typeof createReleaseStore>;\n",
13
+ "import { createHash } from \"node:crypto\";\nimport { releaseBuckets } from \"./protocol\";\n\n/**\n * How `tsplc deploy` sends a release the agent can build from one it already holds. The release's\n * files fall into buckets by path, and each bucket has a digest; the agent answers which buckets\n * differ from a release it stores and that release's files in them, and the client sends only the\n * files the agent lacks, with the release's other parts named rather than sent. The whole upload\n * is one zstd stream: the release's ST files are thousands of small, similar files.\n */\n\n/** A file of a release, at its path in the release. */\nexport interface ReleaseContent {\n\tpath: string;\n\tcontent: Uint8Array<ArrayBuffer>;\n}\n\n/** The first 16 hex digits of a SHA-256: enough to tell a release's files apart, and short on the wire. */\nexport const shortDigest = (data: Uint8Array | string) =>\n\tcreateHash(\"sha256\").update(data).digest(\"hex\").slice(0, 16);\n\n/** The bucket a release path falls in, the same in every release. */\nexport const fileBucket = (path: string) =>\n\tcreateHash(\"sha256\").update(path).digest().readUInt8(0) % releaseBuckets;\n\n/** Each bucket's digest over the paths and contents of its files, from each file's `shortDigest`. */\nexport const bucketDigests = (\n\tfiles: Iterable<{ path: string; digest: string }>,\n): string[] => {\n\tconst buckets = Array.from({ length: releaseBuckets }, (): string[] => []);\n\tfor (const { path, digest } of files) {\n\t\tbuckets[fileBucket(path)]?.push(`${path}\\0${digest}`);\n\t}\n\treturn buckets.map((entries) => shortDigest(entries.sort().join(\"\\n\")));\n};\n\n/** A frame's length prefix: an unsigned 32-bit big-endian byte count. */\nconst lengthBytes = 4;\n\n/** Frames the upload's header and then each file's path and content, and compresses the lot. */\nexport const encodeUpload = async (\n\theader: unknown,\n\tfiles: readonly ReleaseContent[],\n): Promise<Uint8Array<ArrayBuffer>> => {\n\tconst encoder = new TextEncoder();\n\tconst frames = [\n\t\tencoder.encode(JSON.stringify(header)),\n\t\t...files.flatMap(({ path, content }) => [encoder.encode(path), content]),\n\t];\n\tconst body = new Uint8Array(\n\t\tframes.reduce((total, frame) => total + lengthBytes + frame.length, 0),\n\t);\n\tconst view = new DataView(body.buffer);\n\tlet offset = 0;\n\tfor (const frame of frames) {\n\t\tview.setUint32(offset, frame.length);\n\t\tbody.set(frame, offset + lengthBytes);\n\t\toffset += lengthBytes + frame.length;\n\t}\n\treturn new Uint8Array(await Bun.zstdCompress(body, { level: 12 }));\n};\n\n/** An upload's header, still to be validated, and its files. */\nexport const decodeUpload = async (\n\tcompressed: Uint8Array,\n): Promise<{ header: unknown; files: ReleaseContent[] }> => {\n\tconst body = new Uint8Array(await Bun.zstdDecompress(compressed));\n\tconst view = new DataView(body.buffer, body.byteOffset, body.byteLength);\n\tconst frames: Uint8Array<ArrayBuffer>[] = [];\n\tlet offset = 0;\n\twhile (offset < body.length) {\n\t\tif (offset + lengthBytes > body.length) {\n\t\t\tthrow new Error(\"The release upload ends inside a frame\");\n\t\t}\n\t\tconst end = offset + lengthBytes + view.getUint32(offset);\n\t\tif (end > body.length) {\n\t\t\tthrow new Error(\"The release upload ends inside a frame\");\n\t\t}\n\t\tframes.push(body.subarray(offset + lengthBytes, end));\n\t\toffset = end;\n\t}\n\tconst [header, ...rest] = frames;\n\tif (!header || rest.length % 2 !== 0) {\n\t\tthrow new Error(\n\t\t\t\"The release upload has no header or a file without content\",\n\t\t);\n\t}\n\tconst decoder = new TextDecoder();\n\tconst files = Array.from({ length: rest.length / 2 }, (_, index) => ({\n\t\tpath: decoder.decode(rest[2 * index]),\n\t\tcontent: rest[2 * index + 1] ?? new Uint8Array(),\n\t}));\n\treturn { header: JSON.parse(decoder.decode(header)), files };\n};\n",
14
+ "import { randomBytes } from \"node:crypto\";\nimport type { Identity } from \"./protocol\";\n\n/** The cookie a signed-in browser sends: a random session id, never a token. */\nexport const sessionCookie = \"tsplc_session\";\n\n/** How long a browser stays signed in. */\nexport const sessionLifetimeMs = 12 * 60 * 60 * 1000;\n\n/**\n * Browsers signed in with a token, kept in memory: restarting the agent signs every browser out.\n */\nexport const createSessions = (now: () => number) => {\n\tconst sessions = new Map<string, { identity: Identity; expires: number }>();\n\n\tconst sessionId = (request: Request) =>\n\t\tnew Bun.CookieMap(request.headers.get(\"cookie\") ?? \"\").get(sessionCookie);\n\n\tconst cookie = (value: string, maxAgeMs: number) =>\n\t\tnew Bun.Cookie(sessionCookie, value, {\n\t\t\thttpOnly: true,\n\t\t\tsameSite: \"strict\",\n\t\t\tpath: \"/\",\n\t\t\tmaxAge: Math.floor(maxAgeMs / 1000),\n\t\t}).serialize();\n\n\treturn {\n\t\t/** Signs a browser in as `identity`; the answer sets the returned cookie. */\n\t\topen: (identity: Identity) => {\n\t\t\tconst time = now();\n\t\t\tfor (const [id, { expires }] of sessions) {\n\t\t\t\tif (expires <= time) {\n\t\t\t\t\tsessions.delete(id);\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst id = randomBytes(32).toString(\"base64url\");\n\t\t\tsessions.set(id, { identity, expires: time + sessionLifetimeMs });\n\t\t\treturn cookie(id, sessionLifetimeMs);\n\t\t},\n\t\t/** Who the request's cookie signed in, while the session lasts. */\n\t\tfind: (request: Request) => {\n\t\t\tconst id = sessionId(request);\n\t\t\tconst session = id === null ? undefined : sessions.get(id);\n\t\t\tif (!session || session.expires <= now()) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\treturn session.identity;\n\t\t},\n\t\t/** Ends the request's session; the answer sets the returned cookie, which clears it. */\n\t\tclose: (request: Request) => {\n\t\t\tconst id = sessionId(request);\n\t\t\tif (id !== null) {\n\t\t\t\tsessions.delete(id);\n\t\t\t}\n\t\t\treturn cookie(\"\", 0);\n\t\t},\n\t};\n};\n",
15
+ "import { BlockList, isIP } from \"node:net\";\nimport { z } from \"zod\";\nimport { errorMessage } from \"./errors\";\n\nconst tailnet = new BlockList();\ntailnet.addSubnet(\"100.64.0.0\", 10, \"ipv4\");\ntailnet.addSubnet(\"fd7a:115c:a1e0::\", 48, \"ipv6\");\nconst loopback = new BlockList();\nloopback.addSubnet(\"127.0.0.0\", 8, \"ipv4\");\nloopback.addAddress(\"::1\", \"ipv6\");\n\n/** Where a peer address is: this PC, a Tailscale address, or anywhere else. */\nexport const peerKind = (address: string) => {\n\tconst version = isIP(address);\n\tif (version === 0) {\n\t\treturn \"other\";\n\t}\n\tconst family = version === 6 ? \"ipv6\" : \"ipv4\";\n\tif (loopback.check(address, family)) {\n\t\treturn \"loopback\";\n\t}\n\treturn tailnet.check(address, family) ? \"tailnet\" : \"other\";\n};\n\n/** A Tailscale user, as `tailscale whois` names them. */\nexport interface TailnetUser {\n\tlogin: string;\n\tname: string;\n}\n\n/** The part of `tailscale whois --json` the agent reads; Tailscale adds fields between versions. */\nconst whoisSchema = z.object({\n\tUserProfile: z.object({\n\t\tLoginName: z.string().nonempty(),\n\t\tDisplayName: z.string(),\n\t}),\n});\n\n/** Runs a command to completion, with its standard output. */\nexport type RunCommand = (\n\tcommand: string[],\n) => Promise<{ exitCode: number; stdout: string }>;\n\nexport const runCommand: RunCommand = async (command) => {\n\tconst child = Bun.spawn(command, {\n\t\tstdout: \"pipe\",\n\t\tstderr: \"ignore\",\n\t\ttimeout: 5000,\n\t});\n\tconst [stdout, exitCode] = await Promise.all([\n\t\tnew Response(child.stdout).text(),\n\t\tchild.exited,\n\t]);\n\treturn { stdout, exitCode };\n};\n\n/** How long a lookup's answer, a user or none, is reused. */\nexport const whoisCacheMs = 60_000;\n\n/**\n * Who owns a tailnet address, from the local `tailscale` CLI, or null when it can't say: the\n * address isn't a member's, or Tailscale isn't installed or running.\n */\nexport const createWhois = (context: {\n\trun: RunCommand;\n\tnow: () => number;\n\tlog: (message: string) => void;\n}) => {\n\tconst cache = new Map<\n\t\tstring,\n\t\t{ expires: number; user: Promise<TailnetUser | null> }\n\t>();\n\n\tconst lookUp = async (address: string) => {\n\t\ttry {\n\t\t\tconst { exitCode, stdout } = await context.run([\n\t\t\t\t\"tailscale\",\n\t\t\t\t\"whois\",\n\t\t\t\t\"--json\",\n\t\t\t\taddress,\n\t\t\t]);\n\t\t\tif (exitCode !== 0) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tconst { UserProfile } = whoisSchema.parse(JSON.parse(stdout));\n\t\t\treturn {\n\t\t\t\tlogin: UserProfile.LoginName,\n\t\t\t\tname: UserProfile.DisplayName || UserProfile.LoginName,\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tcontext.log(`tailscale whois ${address} failed: ${errorMessage(error)}`);\n\t\t\treturn null;\n\t\t}\n\t};\n\n\treturn (address: string): Promise<TailnetUser | null> => {\n\t\tconst now = context.now();\n\t\tfor (const [cached, { expires }] of cache) {\n\t\t\tif (expires <= now) {\n\t\t\t\tcache.delete(cached);\n\t\t\t}\n\t\t}\n\t\tconst known = cache.get(address);\n\t\tif (known) {\n\t\t\treturn known.user;\n\t\t}\n\t\tconst user = lookUp(address);\n\t\tcache.set(address, { expires: now + whoisCacheMs, user });\n\t\treturn user;\n\t};\n};\nexport type Whois = ReturnType<typeof createWhois>;\n",
16
+ "import { controllerCredentialsSchema, loginCommandSchema } from \"@tsplc/build\";\nimport type { Environment } from \"@tsplc/config\";\nimport { runtimePort } from \"@tsplc/config/build\";\nimport { plantAgentEnv } from \"@tsplc/server/plant-agent\";\nimport { createAccess, type Peer } from \"./access\";\nimport { createAudit } from \"./audit\";\nimport { type CodesysSettings, describeBuilder } from \"./codesys\";\nimport { createDashboard } from \"./dashboard\";\nimport { createDebugging } from \"./debugging\";\nimport { createDeployments } from \"./deploy\";\nimport { createDeploymentRoutes } from \"./deployments/routes\";\nimport { discoverControllers, networkInterfaces } from \"./discovery\";\nimport { createEnvironment } from \"./environment\";\nimport { AgentError, errorMessage } from \"./errors\";\nimport { createLogin } from \"./login\";\nimport { createOperations } from \"./operations\";\nimport {\n\ttype AgentExit,\n\ttype AgentStatus,\n\tagentExitPath,\n\tagentHoldPath,\n\tagentVersionHeader,\n\tclientIdentity,\n\tclientRelease,\n\tcompareRequestSchema,\n\tdebuggerMount,\n\tdiscoverSchema,\n\texitSchema,\n\tstatusPath,\n\ttargetSchema,\n\ttsplcVersion,\n} from \"./protocol\";\nimport {\n\tcreateReleaseStore,\n\ttype ReleaseStore,\n\treadDeployRequest,\n\treleaseServerFile,\n\tstoredReleaseOf,\n} from \"./releases\";\nimport { createRestartRoutes } from \"./restarts\";\nimport {\n\ttype ApiRoute,\n\tanswer,\n\ttype Destination,\n\trouteDestination,\n} from \"./routes\";\nimport { serverEnvironment, storedCredentials } from \"./secrets\";\nimport {\n\tcreateServerSupervisor,\n\ttype ServerSupervisor,\n} from \"./server-process\";\nimport { type AgentState, openState } from \"./state\";\nimport { createWhois, runCommand } from \"./tailscale\";\n\nexport interface AgentOptions {\n\t/** Releases, the controller's download baseline and the selected target live here. */\n\tstate: string;\n\ttoken: string;\n\t/** A viewer's: the debugger (`/debug/*`), `GET /status` and the dashboard's reading routes. */\n\treadToken: string | null;\n\t/** The deployed server's health route; without one a server that stays up 5 s counts as started. */\n\tserverHealthUrl: string | null;\n\t/** Where a release's `serverTokenEnv` is read from, and what the deployed server starts with. */\n\tenvironment: Environment;\n\t/**\n\t * How the deployed server reaches this agent: its URL, and the token that lets the server restart\n\t * the controller, which the server is started with. Without it the server can't.\n\t */\n\tserverAccess: { url: string; token: string } | null;\n\t/** Experimental: downloads without a baseline import their POUs in one PLCopenXML import. */\n\tbulkImport: boolean;\n\tlog: (message: string) => void;\n\t/**\n\t * Ends this process once `POST /agent/exit` has been answered, after the agent has stopped or\n\t * left the line's server as asked.\n\t */\n\texit: (exit: AgentExit) => void;\n}\n\n/** `GET /status`: the selected controller, the deployed release, and the server's and login's state. */\nconst statusRoute = (context: {\n\tstate: AgentState;\n\tserver: ServerSupervisor;\n\tloginStatus: () => Promise<AgentStatus[\"login\"]>;\n}): ApiRoute => ({\n\tmethod: \"GET\",\n\tpattern: statusPath,\n\trole: \"viewer\",\n\thandle: async () =>\n\t\tResponse.json({\n\t\t\ttarget: await context.state.target(),\n\t\t\trelease: await context.state.release(),\n\t\t\tserver: context.server.status(),\n\t\t\tlogin: await context.loginStatus(),\n\t\t\tcredentialsStored: (await storedCredentials()) !== null,\n\t\t} satisfies AgentStatus),\n});\n\n/** `POST /releases/compare`: which of a release's buckets the stored releases lack. */\nexport const compareRoute = (context: {\n\tstate: AgentState;\n\treleases: ReleaseStore;\n}): ApiRoute => ({\n\tmethod: \"POST\",\n\tpattern: \"/releases/compare\",\n\trole: \"admin\",\n\thandle: async (request) => {\n\t\tconst { buckets } = compareRequestSchema.parse(await request.json());\n\t\tconst comparison = await context.releases.compare(\n\t\t\tbuckets,\n\t\t\t(await context.state.release())?.id ?? null,\n\t\t);\n\t\t// The answer lists every stored path in the differing buckets, which compresses tenfold; fetch inflates it.\n\t\treturn new Response(Bun.gzipSync(JSON.stringify(comparison)), {\n\t\t\theaders: {\n\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\"Content-Encoding\": \"gzip\",\n\t\t\t},\n\t\t});\n\t},\n});\n\n/** The routes a browser calls: the dashboard's API, and the status it shows too. */\nexport const createBrowserRoutes = (\n\tcontext: Parameters<typeof statusRoute>[0] &\n\t\tParameters<typeof createDeploymentRoutes>[0] &\n\t\tParameters<typeof createEnvironment>[0] &\n\t\tParameters<typeof createRestartRoutes>[0] & {\n\t\t\taccess: { routes: ApiRoute[] };\n\t\t},\n): ApiRoute[] => [\n\tstatusRoute(context),\n\t...createDeploymentRoutes(context),\n\t...context.access.routes,\n\t...createEnvironment(context).routes,\n\t...createRestartRoutes(context),\n\t...context.audit.routes,\n];\n\n/** Answers a dashboard page, a step of signing in, or the route `destination` finds, as whoever `request` is. */\nexport const answerRequest = async (\n\trequest: Request,\n\tpeer: Peer | null,\n\tcontext: {\n\t\tdashboard: ReturnType<typeof createDashboard>;\n\t\taccess: ReturnType<typeof createAccess>;\n\t\tdestination: (request: Request) => Destination | undefined;\n\t\tlog: (message: string) => void;\n\t},\n): Promise<Response> => {\n\t// The dashboard's pages hold no data; what they show comes from `/api` as whoever is signed in.\n\tconst page = await context.dashboard.handle(request);\n\tif (page) {\n\t\treturn page;\n\t}\n\tconst signing = await context.access.handle(request);\n\tif (signing) {\n\t\treturn signing;\n\t}\n\tconst target = context.destination(request);\n\tconst identity = await context.access.identify(request, peer, {\n\t\t// An unknown route is taken as the dashboard's under `/api` and as the CLI's elsewhere.\n\t\tbrowser:\n\t\t\ttarget?.browser ?? new URL(request.url).pathname.startsWith(\"/api/\"),\n\t});\n\tif (identity instanceof Response) {\n\t\treturn identity;\n\t}\n\treturn answer(request, target, identity, context.log);\n};\n\n/** The debugger's own path for `pathname` under `debuggerMount`, from its leading slash. */\nconst debugRoute = (pathname: string) =>\n\tpathname.slice(debuggerMount.length - 1);\n\n/** The plant agent's routes. It runs one deployment or login operation at a time. */\nexport const createAgent = async (options: AgentOptions) => {\n\tconst { log } = options;\n\tconst state = await openState(options.state);\n\tconst server = createServerSupervisor({\n\t\thealthUrl: options.serverHealthUrl,\n\t\trecord: state.paths.server,\n\t\toutput: state.paths.serverLog,\n\t\t// The agent's own address and token for the server win over anything a release sets.\n\t\tenvironment: async (executable) => ({\n\t\t\t...(await serverEnvironment(\n\t\t\t\tawait storedReleaseOf(state.paths.releases, executable),\n\t\t\t\toptions.environment,\n\t\t\t)),\n\t\t\t...(options.serverAccess && {\n\t\t\t\t[plantAgentEnv.url]: options.serverAccess.url,\n\t\t\t\t[plantAgentEnv.token]: options.serverAccess.token,\n\t\t\t}),\n\t\t}),\n\t\tlog,\n\t});\n\tconst deployed = await state.release();\n\tif (deployed?.server) {\n\t\tawait server.resume(\n\t\t\treleaseServerFile(state.paths.releases, deployed.server),\n\t\t);\n\t}\n\t// Whether deployments can run, said once at start; each deployment and login checks again.\n\tvoid describeBuilder().then(log, (error: unknown) =>\n\t\tlog(`Can't check the CODESYS builder image yet: ${errorMessage(error)}`),\n\t);\n\tconst operations = createOperations(log);\n\tconst codesys: CodesysSettings = { bulkImport: options.bulkImport };\n\tconst releases = createReleaseStore(state.paths.releases);\n\tconst audit = createAudit({\n\t\tfile: state.paths.audit,\n\t\tonRecord: (entry) => debugging.record(entry),\n\t});\n\tconst login = createLogin({ state, operations, codesys, audit, log });\n\tconst debugging = createDebugging({\n\t\tstate,\n\t\treadLogin: login.read,\n\t\tloginStatus: login.status,\n\t\tserverHealthUrl: options.serverHealthUrl,\n\t\tenvironment: options.environment,\n\t\tlog,\n\t});\n\tconst deployments = await createDeployments({\n\t\tstate,\n\t\toperations,\n\t\tcodesys,\n\t\tserver,\n\t\tdebugging,\n\t\tlogin,\n\t\tnow: () => new Date(),\n\t\tlog,\n\t});\n\tconst access = createAccess({\n\t\ttoken: options.token,\n\t\treadToken: options.readToken,\n\t\tserverToken: options.serverAccess?.token ?? null,\n\t\tfile: state.paths.access,\n\t\twhois: createWhois({ run: runCommand, now: Date.now, log }),\n\t\taudit,\n\t\tnow: Date.now,\n\t\tlog,\n\t});\n\tconst dashboard = createDashboard();\n\n\t/** Stops the debugger and the supervised server; a login container keeps running for the next agent. */\n\tconst stop = async () => {\n\t\tawait debugging.close();\n\t\tawait server.stop();\n\t};\n\t/** Stops the debugger and leaves the server running for the agent that replaces this one. */\n\tconst leave = async () => {\n\t\tawait debugging.close();\n\t\tserver.leave();\n\t};\n\n\tconst browserRoutes = createBrowserRoutes({\n\t\tstate,\n\t\tserver,\n\t\tloginStatus: login.status,\n\t\trunner: deployments.runner,\n\t\treleases,\n\t\taccess,\n\t\trestartController: deployments.restart,\n\t\toperations,\n\t\taudit,\n\t\tlog,\n\t});\n\n\t/** The CLI's routes, which only an admin's token reaches. */\n\tconst cliRoutes: ApiRoute[] = [\n\t\t{\n\t\t\tmethod: \"GET\",\n\t\t\tpattern: \"/interfaces\",\n\t\t\trole: \"admin\",\n\t\t\thandle: async () => Response.json(networkInterfaces()),\n\t\t},\n\t\t{\n\t\t\tmethod: \"POST\",\n\t\t\tpattern: \"/discover\",\n\t\t\trole: \"admin\",\n\t\t\thandle: async (request) => {\n\t\t\t\tconst { name } = discoverSchema.parse(await request.json());\n\t\t\t\tconst selected = networkInterfaces().find(\n\t\t\t\t\t(network) => network.name === name,\n\t\t\t\t);\n\t\t\t\tif (!selected) {\n\t\t\t\t\tthrow new AgentError(`No IPv4 interface named ${name}`, 404);\n\t\t\t\t}\n\t\t\t\treturn Response.json(await discoverControllers(selected, runtimePort));\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tmethod: \"PUT\",\n\t\t\tpattern: \"/target\",\n\t\t\trole: \"admin\",\n\t\t\thandle: async (request) => {\n\t\t\t\tconst target = targetSchema.parse(await request.json());\n\t\t\t\tawait state.setTarget(target);\n\t\t\t\treturn Response.json(target);\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tmethod: \"GET\",\n\t\t\tpattern: \"/variables\",\n\t\t\trole: \"admin\",\n\t\t\thandle: async () =>\n\t\t\t\tResponse.json((await state.requireRelease()).manifest.variables),\n\t\t},\n\t\tcompareRoute({ state, releases }),\n\t\t{\n\t\t\tmethod: \"POST\",\n\t\t\tpattern: \"/deploy\",\n\t\t\trole: \"admin\",\n\t\t\thandle: async (request, { identity }) =>\n\t\t\t\tdeployments.deploy(\n\t\t\t\t\t() => readDeployRequest(releases, request),\n\t\t\t\t\tidentity,\n\t\t\t\t\tclientIdentity(request),\n\t\t\t\t\tclientRelease(request),\n\t\t\t\t),\n\t\t},\n\t\t{\n\t\t\tmethod: \"POST\",\n\t\t\tpattern: \"/login\",\n\t\t\trole: \"admin\",\n\t\t\thandle: async (request) =>\n\t\t\t\tlogin.open(\n\t\t\t\t\tcontrollerCredentialsSchema.nullable().parse(await request.json()),\n\t\t\t\t),\n\t\t},\n\t\t{\n\t\t\tmethod: \"POST\",\n\t\t\tpattern: \"/login/command\",\n\t\t\trole: \"admin\",\n\t\t\thandle: async (request) =>\n\t\t\t\tResponse.json(\n\t\t\t\t\tawait login.command(\n\t\t\t\t\t\tloginCommandSchema.parse(await request.json()),\n\t\t\t\t\t\tclientIdentity(request),\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t},\n\t\t{\n\t\t\tmethod: \"DELETE\",\n\t\t\tpattern: \"/login\",\n\t\t\trole: \"admin\",\n\t\t\thandle: async () => Response.json(await login.logout()),\n\t\t},\n\t\t{\n\t\t\tmethod: \"POST\",\n\t\t\tpattern: agentHoldPath,\n\t\t\trole: \"admin\",\n\t\t\thandle: async () => {\n\t\t\t\toperations.hold();\n\t\t\t\ttry {\n\t\t\t\t\t// A login's container outlives the agent and runs the code it started with.\n\t\t\t\t\tif (await login.isOpen()) {\n\t\t\t\t\t\tthrow new AgentError(\n\t\t\t\t\t\t\t\"A login is open; log out before upgrading the agent: tsplc logout\",\n\t\t\t\t\t\t\t409,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tawait deployments.retire();\n\t\t\t\t} catch (error) {\n\t\t\t\t\toperations.release();\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\treturn Response.json({ held: true });\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tmethod: \"DELETE\",\n\t\t\tpattern: agentHoldPath,\n\t\t\trole: \"admin\",\n\t\t\thandle: async () => {\n\t\t\t\toperations.release();\n\t\t\t\treturn Response.json({ held: false });\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tmethod: \"POST\",\n\t\t\tpattern: agentExitPath,\n\t\t\trole: \"admin\",\n\t\t\thandle: async (request) => {\n\t\t\t\tconst exit = exitSchema.parse(await request.json());\n\t\t\t\tif (!operations.held()) {\n\t\t\t\t\tthrow new AgentError(\n\t\t\t\t\t\t\"Hold the agent before it exits, so no operation is cut short\",\n\t\t\t\t\t\t409,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\t// Answered first: the caller waits for this process to end.\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tvoid (exit.server === \"leave\" ? leave() : stop()).then(() =>\n\t\t\t\t\t\toptions.exit(exit),\n\t\t\t\t\t);\n\t\t\t\t}, 100);\n\t\t\t\treturn Response.json({ exiting: true });\n\t\t\t},\n\t\t},\n\t];\n\n\tconst destination = (request: Request): Destination | undefined => {\n\t\tconst { pathname } = new URL(request.url);\n\t\tif (pathname.startsWith(debuggerMount)) {\n\t\t\treturn {\n\t\t\t\tbrowser: true,\n\t\t\t\trole: \"viewer\",\n\t\t\t\thandle: () => debugging.handle(request, debugRoute(pathname)),\n\t\t\t};\n\t\t}\n\t\treturn (\n\t\t\trouteDestination(request, { routes: browserRoutes, browser: true }) ??\n\t\t\trouteDestination(request, { routes: cliRoutes, browser: false })\n\t\t);\n\t};\n\n\tconst respond = async (\n\t\trequest: Request,\n\t\tpeer: Peer | null,\n\t): Promise<Response> => {\n\t\tconst { pathname, search } = new URL(request.url);\n\t\t// The UI's relative links need the trailing slash.\n\t\tif (pathname === debuggerMount.slice(0, -1)) {\n\t\t\treturn new Response(null, {\n\t\t\t\tstatus: 308,\n\t\t\t\theaders: { Location: `${debuggerMount}${search}` },\n\t\t\t});\n\t\t}\n\t\t// The page and its script hold no data, and a browser loads the script without the token.\n\t\tif (\n\t\t\trequest.method === \"GET\" &&\n\t\t\t(pathname === debuggerMount || pathname === `${debuggerMount}ui.js`)\n\t\t) {\n\t\t\treturn debugging.handle(request, debugRoute(pathname));\n\t\t}\n\t\treturn answerRequest(request, peer, {\n\t\t\tdashboard,\n\t\t\taccess,\n\t\t\tdestination,\n\t\t\tlog,\n\t\t});\n\t};\n\n\treturn {\n\t\t/** Answers `request`, naming the agent's tsPLC version so a client can refuse a mismatched agent. */\n\t\tfetch: async (request: Request, peer: Peer | null = null) => {\n\t\t\tconst response = await respond(request, peer);\n\t\t\t// A proxied debugger response's headers are immutable.\n\t\t\tconst headers = new Headers(response.headers);\n\t\t\theaders.set(agentVersionHeader, tsplcVersion);\n\t\t\treturn new Response(response.body, {\n\t\t\t\tstatus: response.status,\n\t\t\t\tstatusText: response.statusText,\n\t\t\t\theaders,\n\t\t\t});\n\t\t},\n\t\tstop,\n\t\tleave,\n\t};\n};\n",
17
+ "import { createHash, timingSafeEqual } from \"node:crypto\";\nimport { isIP } from \"node:net\";\nimport { dashboardHeader, tokenQueryParameter } from \"@tsplc/debug/api\";\nimport { controllerRestartPath } from \"@tsplc/server/plant-agent\";\nimport { type AuditLog, authorOf } from \"./audit\";\nimport { errorMessage } from \"./errors\";\nimport {\n\ttype AccessConfig,\n\taccessConfigSchema,\n\tdebuggerMount,\n\ttype Identity,\n\tsessionRequestSchema,\n} from \"./protocol\";\nimport type { ApiRoute } from \"./routes\";\nimport { createSessions } from \"./sessions\";\nimport { readJsonFile, writeJsonFile } from \"./state\";\nimport { peerKind, type Whois } from \"./tailscale\";\n\nconst noAccess: AccessConfig = { roles: {}, tailnetDefault: null };\n\nexport const readAccessConfig = async (file: string) =>\n\t(await readJsonFile(file, accessConfigSchema)) ?? noAccess;\n\n/** Compares digests, so the time taken says nothing about the token, not even its length. */\nconst matches = (presented: string, token: string) =>\n\ttimingSafeEqual(\n\t\tcreateHash(\"sha256\").update(presented).digest(),\n\t\tcreateHash(\"sha256\").update(token).digest(),\n\t);\n\n/** Where a request came from, as the HTTP server reports it. */\nexport interface Peer {\n\taddress: string;\n}\n\nconst refuse = (status: 401 | 403, error: string) =>\n\tResponse.json({ error }, { status });\nconst unauthorized = () => refuse(401, \"Unauthorized\");\n\n/** A proxy on the agent's PC would make every request it forwards look local. */\nconst forwardingHeaders = [\n\t\"forwarded\",\n\t\"x-forwarded-for\",\n\t\"tailscale-user-login\",\n];\n\n/**\n * Whether the request names the agent by an address, a single-label name or a MagicDNS name.\n * Another site that points its own name at the agent (DNS rebinding) names it by that, and gets\n * no identity from where the browser runs.\n */\nconst namesAgentDirectly = (request: Request) => {\n\tconst host = new URL(request.url).hostname.replace(/^\\[(.*)\\]$/, \"$1\");\n\treturn (\n\t\tisIP(host) !== 0 ||\n\t\t!host.includes(\".\") ||\n\t\thost.endsWith(\".ts.net\") ||\n\t\thost === \"localhost\"\n\t);\n};\n\n/** Anything but `GET` may change something, so another site must not be able to send it. */\nconst changes = (request: Request) => request.method !== \"GET\";\nconst fromDashboard = (request: Request) =>\n\trequest.headers.get(dashboardHeader) === \"1\";\nconst crossSite = () =>\n\trefuse(\n\t\t403,\n\t\t`A browser's request that changes something needs the ${dashboardHeader}: 1 header`,\n\t);\n\n/**\n * Who a request is from, and the role that gives them. The full token is an admin and the read\n * token a viewer, as a bearer token or a browser session signed in with one. The deployed server's\n * token restarts the controller and does nothing else; no browser signs in with it. Under `/api` and\n * `/debug`, a request from the agent's own PC is an admin, and one from a tailnet member has the\n * role `access.json` gives their login.\n */\nexport const createAccess = (options: {\n\ttoken: string;\n\treadToken: string | null;\n\t/** The token the agent starts the deployed server with, which may only restart the controller. */\n\tserverToken: string | null;\n\t/** `access.json`, read on each tailnet request so `tsplc-agent access` applies at once. */\n\tfile: string;\n\twhois: Whois;\n\taudit: AuditLog;\n\tnow: () => number;\n\tlog: (message: string) => void;\n}) => {\n\tconst sessions = createSessions(options.now);\n\n\tconst tokenIdentity = (presented: string): Identity | null => {\n\t\tif (matches(presented, options.token)) {\n\t\t\treturn { login: null, name: \"Agent token\", role: \"admin\", via: \"token\" };\n\t\t}\n\t\tif (options.readToken !== null && matches(presented, options.readToken)) {\n\t\t\treturn {\n\t\t\t\tlogin: null,\n\t\t\t\tname: \"Read token\",\n\t\t\t\trole: \"viewer\",\n\t\t\t\tvia: \"token\",\n\t\t\t};\n\t\t}\n\t\treturn null;\n\t};\n\n\tconst serverIdentity: Identity = {\n\t\tlogin: null,\n\t\tname: \"Line server\",\n\t\trole: \"deployer\",\n\t\tvia: \"server\",\n\t};\n\n\tconst peerIdentity = async (\n\t\trequest: Request,\n\t\tpeer: Peer | null,\n\t): Promise<Identity | null> => {\n\t\tif (\n\t\t\t!peer ||\n\t\t\t!namesAgentDirectly(request) ||\n\t\t\tforwardingHeaders.some((name) => request.headers.has(name))\n\t\t) {\n\t\t\treturn null;\n\t\t}\n\t\tconst kind = peerKind(peer.address);\n\t\tif (kind === \"loopback\") {\n\t\t\treturn { login: null, name: \"This PC\", role: \"admin\", via: \"local\" };\n\t\t}\n\t\tif (kind !== \"tailnet\") {\n\t\t\treturn null;\n\t\t}\n\t\tconst user = await options.whois(peer.address);\n\t\tif (!user) {\n\t\t\treturn null;\n\t\t}\n\t\t// A hand-edited file that doesn't parse gives no one a role until it is fixed.\n\t\tconst config = await readAccessConfig(options.file).catch(\n\t\t\t(error: unknown) => {\n\t\t\t\toptions.log(`Can't read ${options.file}: ${errorMessage(error)}`);\n\t\t\t\treturn noAccess;\n\t\t\t},\n\t\t);\n\t\tconst role = config.roles[user.login] ?? config.tailnetDefault;\n\t\treturn (\n\t\t\trole && { login: user.login, name: user.name, role, via: \"tailscale\" }\n\t\t);\n\t};\n\n\t/**\n\t * The request's identity, or the refusal to answer it with. A route a browser calls also takes\n\t * a browser's session or where the request comes from; the CLI's take only a token.\n\t */\n\tconst identify = async (\n\t\trequest: Request,\n\t\tpeer: Peer | null,\n\t\troute: { browser: boolean },\n\t): Promise<Identity | Response> => {\n\t\tconst { searchParams, pathname } = new URL(request.url);\n\t\t// EventSource can't send headers, so the debugger also takes the token in the query.\n\t\tconst presented =\n\t\t\t/^Bearer (.+)$/.exec(request.headers.get(\"authorization\") ?? \"\")?.[1] ??\n\t\t\t(pathname.startsWith(debuggerMount)\n\t\t\t\t? searchParams.get(tokenQueryParameter)\n\t\t\t\t: null);\n\t\tif (presented !== null) {\n\t\t\tif (\n\t\t\t\toptions.serverToken !== null &&\n\t\t\t\tmatches(presented, options.serverToken)\n\t\t\t) {\n\t\t\t\treturn request.method === \"POST\" && pathname === controllerRestartPath\n\t\t\t\t\t? serverIdentity\n\t\t\t\t\t: refuse(403, \"The server's token only restarts the controller\");\n\t\t\t}\n\t\t\treturn tokenIdentity(presented) ?? unauthorized();\n\t\t}\n\t\tif (!route.browser) {\n\t\t\treturn unauthorized();\n\t\t}\n\t\tconst identity =\n\t\t\tsessions.find(request) ?? (await peerIdentity(request, peer));\n\t\tif (!identity) {\n\t\t\treturn unauthorized();\n\t\t}\n\t\treturn changes(request) && !fromDashboard(request) ? crossSite() : identity;\n\t};\n\n\t/** Signs a browser in and out, which needs no identity: the answer, or null for another route. */\n\tconst handle = async (request: Request): Promise<Response | null> => {\n\t\tconst { pathname } = new URL(request.url);\n\t\tif (\n\t\t\tpathname !== \"/api/session\" ||\n\t\t\t(request.method !== \"POST\" && request.method !== \"DELETE\")\n\t\t) {\n\t\t\treturn null;\n\t\t}\n\t\tif (!fromDashboard(request)) {\n\t\t\treturn crossSite();\n\t\t}\n\t\tif (request.method === \"DELETE\") {\n\t\t\treturn new Response(null, {\n\t\t\t\tstatus: 204,\n\t\t\t\theaders: { \"Set-Cookie\": sessions.close(request) },\n\t\t\t});\n\t\t}\n\t\tconst body = sessionRequestSchema.safeParse(\n\t\t\tawait request.json().catch(() => null),\n\t\t);\n\t\tif (!body.success) {\n\t\t\treturn Response.json({ error: \"Send { token }\" }, { status: 400 });\n\t\t}\n\t\tconst identity = tokenIdentity(body.data.token);\n\t\tif (!identity) {\n\t\t\treturn unauthorized();\n\t\t}\n\t\treturn Response.json(identity, {\n\t\t\theaders: { \"Set-Cookie\": sessions.open(identity) },\n\t\t});\n\t};\n\n\tconst routes: ApiRoute[] = [\n\t\t{\n\t\t\tmethod: \"GET\",\n\t\t\tpattern: \"/api/session\",\n\t\t\trole: \"viewer\",\n\t\t\thandle: async (_request, { identity }) => Response.json(identity),\n\t\t},\n\t\t{\n\t\t\tmethod: \"GET\",\n\t\t\tpattern: \"/api/access\",\n\t\t\trole: \"admin\",\n\t\t\thandle: async () => Response.json(await readAccessConfig(options.file)),\n\t\t},\n\t\t{\n\t\t\tmethod: \"PUT\",\n\t\t\tpattern: \"/api/access\",\n\t\t\trole: \"admin\",\n\t\t\thandle: async (request, { identity }) => {\n\t\t\t\tconst config = accessConfigSchema.parse(await request.json());\n\t\t\t\tconst previous = await readAccessConfig(options.file);\n\t\t\t\twriteJsonFile(options.file, config);\n\t\t\t\tawait options.audit.record({\n\t\t\t\t\tby: authorOf(identity),\n\t\t\t\t\tcommand: \"access\",\n\t\t\t\t\tvalues: auditedAccess(config),\n\t\t\t\t\tprevious: auditedAccess(previous),\n\t\t\t\t\terror: null,\n\t\t\t\t});\n\t\t\t\treturn Response.json(config);\n\t\t\t},\n\t\t},\n\t];\n\treturn { identify, handle, routes };\n};\n\n/** Who has which role, as the audit log lists it: each login's role, and the tailnet default. */\nconst auditedAccess = (config: AccessConfig) => ({\n\t...config.roles,\n\t\"(tailnet default)\": config.tailnetDefault ?? \"none\",\n});\n",
18
+ "import { join } from \"node:path\";\nimport {\n\tbuilderImageStatus,\n\tcaptureDocker,\n\tgatewayImage,\n\tsetupReason,\n} from \"@tsplc/build\";\nimport { gatewayPort, resolveConfig } from \"@tsplc/config/build\";\nimport { AgentError, errorMessage } from \"./errors\";\nimport type { Credentials, Target } from \"./protocol\";\nimport { loadRelease, manifestFile, type StoredRelease } from \"./releases\";\nimport type { AgentState } from \"./state\";\n\n/** How the agent runs CODESYS, whichever release it deploys. */\nexport interface CodesysSettings {\n\t/** Downloads without a baseline import their POUs in one PLCopenXML import; experimental. */\n\tbulkImport: boolean;\n}\n\n/** The gateway reaches controllers through this Docker network. */\nconst network = \"tsplc-agent\";\n/**\n * Builder containers reach the gateway by name on this internal network, which has no internet.\n * With internet, CODESYS asks a certificate authority about each DLL it loads, without caching\n * the answer, and opening a project takes minutes instead of seconds.\n */\nconst codesysNetwork = \"tsplc-agent-codesys\";\nconst gateway = { host: \"tsplc-agent-gateway\", port: gatewayPort };\nexport const loginContainer = \"tsplc-agent-login\";\n/** Keeps CODESYS running between deployments, so each skips starting it. */\nexport const deployContainer = \"tsplc-agent-deploy\";\n/** Every Docker container and network the agent creates: one agent per Docker server uses them. */\nexport const agentDockerResources = {\n\tcontainers: [gateway.host, deployContainer, loginContainer],\n\tnetworks: [network, codesysNetwork],\n};\n/** CODESYS reads the controller user from these for one operation; the agent never stores it. */\nconst credentialNames = {\n\tusernameEnv: \"TSPLC_DEVICE_USERNAME\",\n\tpasswordEnv: \"TSPLC_DEVICE_PASSWORD\",\n};\n\n/** Network and gateway commands return at once; one still running after this has hung. */\nconst dockerTimeout = 60_000;\n\nconst docker = async (...args: string[]) =>\n\t(await captureDocker(args, dockerTimeout)).stdout.trim();\n\nconst ensureNetwork = async (name: string, ...options: string[]) => {\n\tif (\n\t\t!(await docker(\"network\", \"ls\", \"--quiet\", \"--filter\", `name=^${name}$`))\n\t) {\n\t\tawait docker(\"network\", \"create\", ...options, name);\n\t}\n};\n\n/**\n * Why the images can't serve a deployment or login, or null when they can. Containers run the\n * installed tsPLC's code, so only a new image recipe or a missing image needs setup.\n */\nconst setupNeeded = async () => {\n\tconst status = await builderImageStatus();\n\tconst reason =\n\t\tsetupReason(status) ??\n\t\t((await docker(\"image\", \"ls\", \"--quiet\", gatewayImage))\n\t\t\t? null\n\t\t\t: `the CODESYS gateway image ${gatewayImage} is missing`);\n\treturn { status, reason };\n};\n\n/**\n * Checks that the images can serve a deployment or login, naming what to run on the plant PC\n * when they can't, and returns the builder image's status.\n */\nexport const requireBuilder = async () => {\n\tconst { status, reason } = await setupNeeded().catch((cause: unknown) => {\n\t\tthrow new AgentError(\n\t\t\t`Docker doesn't answer on the plant PC; start Docker Desktop there: ${errorMessage(cause)}`,\n\t\t\t503,\n\t\t);\n\t});\n\tif (reason) {\n\t\tthrow new AgentError(\n\t\t\t`The plant PC needs tsplc-agent setup: ${reason}. Run tsplc-agent setup there; the line's server keeps running meanwhile`,\n\t\t\t409,\n\t\t);\n\t}\n\treturn status;\n};\n\n/** What the agent says about its images when it starts. */\nexport const describeBuilder = async () => {\n\tconst { status, reason } = await setupNeeded();\n\tif (reason) {\n\t\treturn `Deployments and logins need tsplc-agent setup first: ${reason}`;\n\t}\n\tif (status.kind === \"unverified\") {\n\t\treturn `Warning: ${status.reason}. Deployments use it; run tsplc-agent setup once to rebuild and label it`;\n\t}\n\treturn \"The CODESYS images match this tsPLC\";\n};\n\n/** Removes container `name`, which need not exist. */\nexport const removeContainer = (name: string) => docker(\"rm\", \"--force\", name);\n\n/** The gateway container stays up between operations, as a CODESYS gateway service would. */\nexport const ensureGateway = async () => {\n\tawait ensureNetwork(network);\n\tawait ensureNetwork(codesysNetwork, \"--internal\");\n\tif (\n\t\t!(await docker(\n\t\t\t\"container\",\n\t\t\t\"ls\",\n\t\t\t\"--quiet\",\n\t\t\t\"--filter\",\n\t\t\t`name=^${gateway.host}$`,\n\t\t))\n\t) {\n\t\tawait docker(\"rm\", \"--force\", gateway.host);\n\t\tawait docker(\n\t\t\t\"run\",\n\t\t\t\"--detach\",\n\t\t\t\"--restart\",\n\t\t\t\"unless-stopped\",\n\t\t\t\"--platform\",\n\t\t\t\"linux/amd64\",\n\t\t\t\"--network\",\n\t\t\tnetwork,\n\t\t\t\"--name\",\n\t\t\tgateway.host,\n\t\t\tgatewayImage,\n\t\t);\n\t}\n\t// Gateways started by earlier agents are only on `network`.\n\tconst networks = await docker(\n\t\t\"inspect\",\n\t\t\"--format\",\n\t\t\"{{json .NetworkSettings.Networks}}\",\n\t\tgateway.host,\n\t);\n\tif (!(codesysNetwork in JSON.parse(networks))) {\n\t\tawait docker(\"network\", \"connect\", codesysNetwork, gateway.host);\n\t}\n};\n\n/** The controller user as the variables one operation's container passes to CODESYS. */\nexport const credentialEnvironment = (credentials: Credentials) => ({\n\t[credentialNames.usernameEnv]: credentials.username,\n\t[credentialNames.passwordEnv]: credentials.password,\n});\n\n/**\n * The release's build config, aimed at `target` through the agent's gateway, with the agent's own\n * CODESYS settings. The download baseline in `controllerDirectory` outlives releases: an online\n * change compares against the last download.\n */\nexport const controllerConfig = (\n\trelease: StoredRelease,\n\ttarget: Target,\n\tcontrollerDirectory: string,\n\tsettings: CodesysSettings,\n) => ({\n\t...resolveConfig(\n\t\t{\n\t\t\t...release.manifest.config,\n\t\t\t...(settings.bulkImport && { bulkImport: true }),\n\t\t\tonline: {\n\t\t\t\tnetwork: codesysNetwork,\n\t\t\t\tgateway,\n\t\t\t\tdevice: target,\n\t\t\t\tcredentials: credentialNames,\n\t\t\t},\n\t\t},\n\t\tjoin(release.directory, manifestFile),\n\t),\n\toutDir: controllerDirectory,\n});\n\n/** The deployed release's build config for the selected controller, or null before a deployment to one. */\nexport const deployedControllerConfig = async (\n\tstate: AgentState,\n\tsettings: CodesysSettings,\n) => {\n\tconst deployed = await state.release();\n\tconst target = await state.target();\n\tif (!deployed || !target) {\n\t\treturn null;\n\t}\n\treturn controllerConfig(\n\t\tawait loadRelease(state.paths.releases, deployed.id),\n\t\ttarget,\n\t\tstate.paths.controller,\n\t\tsettings,\n\t);\n};\n",
19
+ "import { createRequire } from \"node:module\";\nimport { basename, dirname, resolve } from \"node:path\";\nimport { envName } from \"@tsplc/config/build\";\nimport { dashboardHeader } from \"@tsplc/debug/api\";\nimport { z } from \"zod\";\nimport { auditLimits } from \"../audit\";\nimport { errorMessage } from \"../errors\";\nimport {\n\tagentVersionHeader,\n\tallows,\n\tcancelableStates,\n\tdebuggerMount,\n\tdeploymentPagePath,\n\tdeploymentsApiPath,\n\tfinalStates,\n\ttype Role,\n\troles,\n\tstatusPath,\n} from \"../protocol\";\n\n/**\n * The pages a browser loads, each with the paths under it, and the role its link shows to; `/` is the\n * first. They hold no data, which they fetch from `/api` as whoever is signed in.\n */\nconst pages = [\n\t{ path: \"/deployments\", label: \"Deployments\", role: \"viewer\" },\n\t{ path: \"/environment\", label: \"Environment\", role: \"viewer\" },\n\t{ path: \"/audit\", label: \"Audit\", role: \"viewer\" },\n\t{ path: \"/access\", label: \"Access\", role: \"admin\" },\n] as const satisfies readonly { path: string; label: string; role: Role }[];\n\n/** Where the pages' script and stylesheet are served; like the pages, they hold no data. */\nexport const dashboardAssets = \"/dashboard-assets/\";\n\n/** The browser's local storage key for the chosen theme, read before the page first paints. */\nconst themeKey = \"tsplc-theme\";\n\nconst page = `<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><title>tsPLC</title><script>document.documentElement.dataset.theme=localStorage.getItem(${JSON.stringify(themeKey)})||\"\"</script><link rel=\"stylesheet\" href=\"${dashboardAssets}dashboard.css\"><script type=\"module\" src=\"${dashboardAssets}main.js\"></script></head><body><main id=\"app\"></main></body></html>`;\n\n/** The config's rule for an environment variable's name, as an input's `pattern`. */\nconst envNamePattern = () => {\n\tconst { pattern } = z.toJSONSchema(envName);\n\tif (pattern === undefined) {\n\t\tthrow new Error(\"The config's environment variable name has no pattern\");\n\t}\n\treturn pattern;\n};\n\nexport const dashboardContract = () => ({\n\troles,\n\tpermissions: Object.fromEntries(\n\t\troles.map((role) => [\n\t\t\trole,\n\t\t\tObject.fromEntries(\n\t\t\t\troles.map((required) => [required, allows(role, required)]),\n\t\t\t),\n\t\t]),\n\t),\n\tpages,\n\tthemeKey,\n\tauditLimits,\n\tfinalStates,\n\tcancelableStates,\n\tenvNamePattern: envNamePattern(),\n\tdashboardHeader,\n\tagentVersionHeader,\n\tdebuggerMount,\n\tstatusPath,\n\tdeploymentsApiPath,\n\t/** `deploymentPagePath`'s prefix, which the deployment's id follows. */\n\tdeploymentPages: deploymentPagePath(\"\"),\n});\nexport type DashboardContract = ReturnType<typeof dashboardContract>;\n\ninterface Asset {\n\ttext: string;\n\ttype: string;\n}\n\nconst bundle = async () => {\n\t// Resolved through the package, so a published `dist/` bundle finds the shipped sources.\n\tconst sources = resolve(\n\t\tdirname(createRequire(import.meta.url).resolve(\"@tsplc/agent\")),\n\t\t\"../src/dashboard/ui\",\n\t);\n\tconst result = await Bun.build({\n\t\tentrypoints: [\n\t\t\tresolve(sources, \"main.ts\"),\n\t\t\tresolve(sources, \"dashboard.css\"),\n\t\t],\n\t\ttarget: \"browser\",\n\t\t// Workspace packages resolve to their sources, as they do for the host, so no build is needed first.\n\t\tconditions: [\"bun\"],\n\t\tminify: true,\n\t\tnaming: \"[name].[ext]\",\n\t\tdefine: { TSPLC_CONTRACT: JSON.stringify(dashboardContract()) },\n\t});\n\tif (!result.success) {\n\t\tthrow new Error(\n\t\t\t`Bundling the dashboard failed:\\n${result.logs.map(String).join(\"\\n\")}`,\n\t\t);\n\t}\n\tconst assets = new Map<string, Asset>();\n\tfor (const output of result.outputs) {\n\t\tassets.set(basename(output.path), {\n\t\t\ttext: await output.text(),\n\t\t\ttype: output.type,\n\t\t});\n\t}\n\treturn assets;\n};\n\nconst isPage = (pathname: string) =>\n\tpathname === \"/\" ||\n\tpages.some(\n\t\t({ path }) => pathname === path || pathname.startsWith(`${path}/`),\n\t);\n\n/**\n * The agent's dashboard: its pages, answered for any path under them, and their script and\n * stylesheet, bundled on first request and then kept.\n */\nexport const createDashboard = () => {\n\tlet assets: Promise<Map<string, Asset>> | undefined;\n\treturn {\n\t\thandle: async (request: Request): Promise<Response | undefined> => {\n\t\t\tconst { pathname } = new URL(request.url);\n\t\t\tif (request.method !== \"GET\") {\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\tif (isPage(pathname)) {\n\t\t\t\treturn new Response(page, {\n\t\t\t\t\theaders: {\n\t\t\t\t\t\t\"Content-Type\": \"text/html; charset=utf-8\",\n\t\t\t\t\t\t\"Cache-Control\": \"no-cache\",\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (!pathname.startsWith(dashboardAssets)) {\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\tassets ??= bundle();\n\t\t\ttry {\n\t\t\t\tconst asset = (await assets).get(\n\t\t\t\t\tpathname.slice(dashboardAssets.length),\n\t\t\t\t);\n\t\t\t\tif (!asset) {\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\t\t\t\treturn new Response(asset.text, {\n\t\t\t\t\theaders: { \"Content-Type\": asset.type, \"Cache-Control\": \"no-cache\" },\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tassets = undefined;\n\t\t\t\treturn new Response(errorMessage(error), { status: 500 });\n\t\t\t}\n\t\t},\n\t};\n};\n",
20
+ "import { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { Environment } from \"@tsplc/config\";\nimport {\n\tcreateDebugger,\n\tcreateDebugHandler,\n\ttype Debugger,\n\tloadDebugBuild,\n\tloginReader,\n\ttimelineEntries,\n} from \"@tsplc/debug\";\nimport { debugManifestFile } from \"@tsplc/debug/manifest\";\nimport { errorMessage } from \"./errors\";\nimport { readJsonl } from \"./logs\";\nimport {\n\ttype AgentStatus,\n\ttype Audit,\n\tauditSchema,\n\tdeploymentSchema,\n} from \"./protocol\";\nimport { loadRelease } from \"./releases\";\nimport { serverEnvironment } from \"./secrets\";\nimport type { AgentState } from \"./state\";\n\n/** Log entries a new debugger starts its timeline with. */\nconst recentEntries = 500;\n\ninterface RunningDebugger {\n\tdebug: Debugger;\n\thandle: ReturnType<typeof createDebugHandler>;\n}\n\n/**\n * The deployed release's debugger, when it has a debug manifest. It reads the controller\n * through the agent's engineering login, and the server's telemetry and requests through the\n * server's health origin.\n */\nexport const createDebugging = (context: {\n\tstate: AgentState;\n\treadLogin: (expressions: string[]) => Promise<Record<string, string>>;\n\t/** The login's state, with the expressions the controller forces. */\n\tloginStatus: () => Promise<AgentStatus[\"login\"]>;\n\tserverHealthUrl: string | null;\n\tenvironment: Environment;\n\tlog: (message: string) => void;\n}) => {\n\tconst { state, log } = context;\n\n\tconst start = async (): Promise<RunningDebugger | null> => {\n\t\tconst release = await state.release();\n\t\tif (!release) {\n\t\t\treturn null;\n\t\t}\n\t\tconst stored = await loadRelease(state.paths.releases, release.id);\n\t\tconst manifestFile = join(stored.directory, debugManifestFile);\n\t\tif (!existsSync(manifestFile)) {\n\t\t\treturn null;\n\t\t}\n\t\tconst { serverTokenEnv, debug: settings } = stored.manifest;\n\t\tconst serverToken =\n\t\t\tserverTokenEnv &&\n\t\t\t(await serverEnvironment(stored, context.environment))[serverTokenEnv];\n\t\tconst build = await loadDebugBuild(manifestFile);\n\t\tconst debug = await createDebugger({\n\t\t\t...build,\n\t\t\t...loginReader(build.manifest, {\n\t\t\t\tread: context.readLogin,\n\t\t\t\tstatus: context.loginStatus,\n\t\t\t\tendpoint: \"the agent's login\",\n\t\t\t}),\n\t\t\tstateDirectory: state.paths.debug,\n\t\t\twatch: settings?.watch ?? {},\n\t\t\t...(context.serverHealthUrl &&\n\t\t\t\tserverToken && {\n\t\t\t\t\tserver: {\n\t\t\t\t\t\turl: new URL(context.serverHealthUrl).origin,\n\t\t\t\t\t\ttoken: serverToken,\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\trelease: {\n\t\t\t\tid: release.id,\n\t\t\t\tdeployedAt: release.deployedAt,\n\t\t\t\toperation: release.operation,\n\t\t\t},\n\t\t\ttimeline: [\n\t\t\t\t...(\n\t\t\t\t\tawait readJsonl(\n\t\t\t\t\t\tstate.paths.deployments,\n\t\t\t\t\t\tdeploymentSchema,\n\t\t\t\t\t\trecentEntries,\n\t\t\t\t\t)\n\t\t\t\t).map(({ at, ...deployment }) =>\n\t\t\t\t\ttimelineEntries.deploy(at, deployment),\n\t\t\t\t),\n\t\t\t\t...(await readJsonl(state.paths.audit, auditSchema, recentEntries)).map(\n\t\t\t\t\t({ at, ...audit }) => timelineEntries.audit(at, audit),\n\t\t\t\t),\n\t\t\t],\n\t\t\tlog,\n\t\t});\n\t\treturn { debug, handle: createDebugHandler(debug, log) };\n\t};\n\tconst startOrLog = () =>\n\t\tstart().catch((error: unknown) => {\n\t\t\tlog(`Starting the debugger failed: ${errorMessage(error)}`);\n\t\t\treturn null;\n\t\t});\n\n\tlet current = startOrLog();\n\n\treturn {\n\t\t/** Answers a request under `/debug`, at `route` within it. */\n\t\thandle: async (request: Request, route: string) => {\n\t\t\tconst debugging = await current;\n\t\t\tif (!debugging) {\n\t\t\t\treturn Response.json(\n\t\t\t\t\t{\n\t\t\t\t\t\terror:\n\t\t\t\t\t\t\t\"The deployed release has no debug manifest, or the debugger failed to start\",\n\t\t\t\t\t},\n\t\t\t\t\t{ status: 503 },\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn debugging.handle(request, route);\n\t\t},\n\t\t/** Adds an audited command to the debugger's timeline. */\n\t\trecord: async ({ at, ...audit }: Audit) => {\n\t\t\t(await current)?.debug.record(timelineEntries.audit(at, audit));\n\t\t},\n\t\t/** Replaces the debugger after the release changes. */\n\t\trestart: () => {\n\t\t\tcurrent = current.then(async (debugging) => {\n\t\t\t\tawait debugging?.debug.close();\n\t\t\t\treturn startOrLog();\n\t\t\t});\n\t\t},\n\t\tclose: async () => {\n\t\t\tawait (await current)?.debug.close();\n\t\t},\n\t};\n};\nexport type Debugging = ReturnType<typeof createDebugging>;\n",
21
+ "import { randomBytes } from \"node:crypto\";\nimport { mkdir, readFile, rm, writeFile } from \"node:fs/promises\";\nimport { dirname, join, relative } from \"node:path\";\nimport {\n\ttype agentTokenEnv,\n\ttype Environment,\n\tsecretPlaceholder,\n\tsecretValue,\n} from \"@tsplc/config\";\nimport type { ResolvedConfig } from \"@tsplc/config/build\";\nimport { escapeString } from \"@tsplc/iec/st\";\nimport { AgentError } from \"./errors\";\nimport type { Credentials, ReleaseManifest } from \"./protocol\";\nimport type { StoredRelease } from \"./releases\";\n\n/** The agent's own Bun.secrets service, which holds the controller user and the agent's tokens. */\nexport const agentService = \"tsplc-agent\";\n/** Where the dashboard stores the environment's secrets while the deployed release declares none. */\nexport const environmentService = \"tsplc-agent-env\";\n/** The token that only reads from the agent. */\nexport const agentReadTokenEnv = \"TSPLC_AGENT_READ_TOKEN\";\nexport const controllerSecretNames = {\n\tusername: \"controller-username\",\n\tpassword: \"controller-password\",\n};\n\n/** Agent setting `name`: its variable in `environment` when set, otherwise the value stored under the agent's service, or null. */\nexport const agentSetting = async (\n\tname: typeof agentTokenEnv | typeof agentReadTokenEnv,\n\tenvironment: Environment,\n) =>\n\tenvironment[name] ?? (await Bun.secrets.get({ service: agentService, name }));\n\n/**\n * The token the deployed server is started with, made once and kept under the agent's service, so\n * a server an earlier agent started still has a valid one.\n */\nexport const serverToken = async () => {\n\tconst name = \"server-token\";\n\tconst stored = await Bun.secrets.get({ service: agentService, name });\n\tif (stored) {\n\t\treturn stored;\n\t}\n\tconst token = randomBytes(32).toString(\"hex\");\n\tawait Bun.secrets.set({ service: agentService, name, value: token });\n\treturn token;\n};\n\n/** The controller user stored with `tsplc-agent secrets set-controller`, or null. */\nexport const storedCredentials = async (): Promise<Credentials | null> => {\n\tconst [username, password] = await Promise.all([\n\t\tBun.secrets.get({\n\t\t\tservice: agentService,\n\t\t\tname: controllerSecretNames.username,\n\t\t}),\n\t\tBun.secrets.get({\n\t\t\tservice: agentService,\n\t\t\tname: controllerSecretNames.password,\n\t\t}),\n\t]);\n\treturn username && password ? { username, password } : null;\n};\n\n/** The controller user a request sent, or the stored one when it sent null. */\nexport const controllerCredentials = async (sent: Credentials | null) => {\n\tconst credentials = sent ?? (await storedCredentials());\n\tif (!credentials) {\n\t\tthrow new AgentError(\n\t\t\t\"No controller user is stored on the plant PC: run tsplc-agent secrets set-controller there\",\n\t\t\t409,\n\t\t);\n\t}\n\treturn credentials;\n};\n\n/** The release's secrets from Bun.secrets, by name. Fails naming every one that is missing. */\nexport const readSecrets = async (secrets: ReleaseManifest[\"secrets\"]) => {\n\tconst values = new Map<string, string>();\n\tif (!secrets) {\n\t\treturn values;\n\t}\n\tconst { service } = secrets;\n\tconst missing: string[] = [];\n\tfor (const name of secrets.names) {\n\t\tconst value = await Bun.secrets.get({ service, name });\n\t\tconst valid = secretValue.safeParse(value);\n\t\tif (!value) {\n\t\t\tmissing.push(name);\n\t\t} else if (!valid.success) {\n\t\t\tthrow new AgentError(\n\t\t\t\t`Secret ${name} in Bun.secrets service ${service} ${valid.error.issues.map((issue) => issue.message).join(\" and \")}`,\n\t\t\t\t409,\n\t\t\t);\n\t\t} else {\n\t\t\tvalues.set(name, value);\n\t\t}\n\t}\n\tif (missing.length) {\n\t\tthrow new AgentError(\n\t\t\t`The plant PC has no ${missing.join(\", \")} in Bun.secrets service ${service}: run tsplc-agent secrets set <name> --service ${service} there`,\n\t\t\t409,\n\t\t);\n\t}\n\treturn values;\n};\n\n/** The release's secrets that Bun.secrets holds, by name. */\nconst storedSecrets = async (secrets: ReleaseManifest[\"secrets\"]) => {\n\tif (!secrets) {\n\t\treturn {};\n\t}\n\tconst stored = await Promise.all(\n\t\tsecrets.names.map(async (name) => ({\n\t\t\tname,\n\t\t\tvalue: await Bun.secrets.get({ service: secrets.service, name }),\n\t\t})),\n\t);\n\treturn Object.fromEntries(\n\t\tstored.flatMap(({ name, value }): [string, string][] =>\n\t\t\tvalue === null ? [] : [[name, value]],\n\t\t),\n\t);\n};\n\n/**\n * The environment the server of `release` runs in, and so what the agent reads a variable of the\n * release's as: `environment`, then the values of the target the release was built for, as the\n * PLC's program got them, then the release's secrets that Bun.secrets holds.\n */\nexport const serverEnvironment = async (\n\t{ manifest }: StoredRelease,\n\tenvironment: Environment,\n): Promise<Environment> => ({\n\t...environment,\n\t...manifest.values,\n\t...(await storedSecrets(manifest.secrets)),\n});\n\n/** Structured Text with each secret's placeholder replaced by its value, inside the STRING literal that holds it. */\nconst fillSecrets = (st: string, secrets: ReadonlyMap<string, string>) =>\n\t[...secrets].reduce(\n\t\t// A replacer function, since a replacement string would read `$'` and `$$` as patterns.\n\t\t(text, [name, value]) =>\n\t\t\ttext.replaceAll(secretPlaceholder(name), () => escapeString(value, \"'\")),\n\t\tst,\n\t);\n\n/** The config with its ST copied to `directory`, the secrets filled in. */\nexport const withSecrets = async (\n\tconfig: ResolvedConfig,\n\tsecrets: ReadonlyMap<string, string>,\n\tdirectory: string,\n): Promise<ResolvedConfig> => {\n\tawait rm(directory, { recursive: true, force: true });\n\tfor await (const path of new Bun.Glob(\"**/*\").scan({\n\t\tcwd: config.sourceDir,\n\t\tdot: true,\n\t})) {\n\t\tconst file = join(directory, path);\n\t\tawait mkdir(dirname(file), { recursive: true });\n\t\tawait writeFile(\n\t\t\tfile,\n\t\t\tfillSecrets(\n\t\t\t\tawait readFile(join(config.sourceDir, path), \"utf8\"),\n\t\t\t\tsecrets,\n\t\t\t),\n\t\t);\n\t}\n\treturn {\n\t\t...config,\n\t\tsourceDir: directory,\n\t\tentry: join(directory, relative(config.sourceDir, config.entry)),\n\t};\n};\n",
22
+ "import {\n\tcontrollerBaseline,\n\ttype ResetKind,\n\trestartWarmController,\n\treviewWarmController,\n\tsettleWarmController,\n\tstartWarmController,\n\tupdateWarmController,\n} from \"@tsplc/build\";\nimport {\n\ttype CodesysSettings,\n\tdeployContainer,\n\tdeployedControllerConfig,\n\tensureGateway,\n\tremoveContainer,\n\trequireBuilder,\n} from \"./codesys\";\nimport type { Debugging } from \"./debugging\";\nimport {\n\tcreateDeploymentRunner,\n\ttype DeploymentController,\n} from \"./deployments/runner\";\nimport { openDeploymentStore } from \"./deployments/store\";\nimport {\n\tcheckSubmission,\n\tclientWarnings,\n\tsubmissionFrom,\n} from \"./deployments/submission\";\nimport { AgentError, errorMessage } from \"./errors\";\nimport type { Login } from \"./login\";\nimport type { Operations } from \"./operations\";\nimport type { ClientIdentity, ClientRelease, Identity } from \"./protocol\";\nimport type { DeployRequest } from \"./releases\";\nimport { controllerCredentials, readSecrets } from \"./secrets\";\nimport type { ServerSupervisor } from \"./server-process\";\nimport type { AgentState } from \"./state\";\n\n/**\n * Deployments of uploaded releases: a download or online change through the CODESYS that stays\n * running between them, then the release's server once the controller has its program.\n */\nexport const createDeployments = async (context: {\n\tstate: AgentState;\n\toperations: Operations;\n\tcodesys: CodesysSettings;\n\tserver: ServerSupervisor;\n\tdebugging: Debugging;\n\tlogin: Pick<Login, \"isOpen\" | \"restart\">;\n\tnow: () => Date;\n\tlog: (message: string) => void;\n}) => {\n\tconst { state } = context;\n\n\t/** CODESYS starts for the deployed release in the background, so the first deployment finds it running. */\n\tconst warming = (async () => {\n\t\tconst config = await deployedControllerConfig(state, context.codesys);\n\t\tif (!config) {\n\t\t\treturn;\n\t\t}\n\t\tawait requireBuilder();\n\t\tawait ensureGateway();\n\t\tawait startWarmController(config, deployContainer);\n\t})().catch((error: unknown) => {\n\t\tcontext.log(`Starting CODESYS failed: ${errorMessage(error)}`);\n\t});\n\n\t/** Starts the gateway, and waits for CODESYS to have started for the deployed release. */\n\tconst warmed = async () => {\n\t\tawait ensureGateway();\n\t\tawait warming;\n\t};\n\n\tconst controller: DeploymentController = {\n\t\tready: async () => {\n\t\t\tconst builder = await requireBuilder();\n\t\t\tif (await context.login.isOpen()) {\n\t\t\t\tthrow new AgentError(\n\t\t\t\t\t\"A login is open; log out before deploying: tsplc logout\",\n\t\t\t\t\t409,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn builder.kind === \"unverified\"\n\t\t\t\t? [\n\t\t\t\t\t\t`${builder.reason}. Run tsplc-agent setup on the plant PC once to rebuild and label it`,\n\t\t\t\t\t]\n\t\t\t\t: [];\n\t\t},\n\t\tsettle: (config) => settleWarmController(config, deployContainer),\n\t\tbaseline: () => controllerBaseline(state.paths.controller),\n\t\treview: async (config, options) => {\n\t\t\tawait warmed();\n\t\t\treturn reviewWarmController(config, deployContainer, options);\n\t\t},\n\t\t// The previous server keeps running until the controller has the new program, so a failed\n\t\t// transfer leaves both as they were.\n\t\tapply: async (config, operation, options) => {\n\t\t\tawait warmed();\n\t\t\treturn updateWarmController(config, deployContainer, operation, options);\n\t\t},\n\t};\n\n\tconst runner = createDeploymentRunner({\n\t\tstore: await openDeploymentStore({\n\t\t\tdirectory: state.paths.deploymentRecords,\n\t\t\tnow: context.now,\n\t\t\tlog: context.log,\n\t\t}),\n\t\tstate,\n\t\toperations: context.operations,\n\t\tcodesys: context.codesys,\n\t\tserver: context.server,\n\t\tcontroller,\n\t\tonActivated: () => context.debugging.restart(),\n\t\tnow: context.now,\n\t\tlog: context.log,\n\t});\n\tawait runner.start();\n\n\treturn {\n\t\trunner,\n\t\t/**\n\t\t * Resets the deployed application and starts it again, as the agent's one operation: through\n\t\t * the open login when there is one, which a deployment would also wait for, else through the\n\t\t * CODESYS that stays running for deployments, so it takes seconds and needs no login.\n\t\t */\n\t\trestart: (reset: ResetKind) =>\n\t\t\tcontext.operations.exclusive(\"a controller restart\", async () => {\n\t\t\t\tif (await context.login.isOpen()) {\n\t\t\t\t\treturn context.login.restart(reset);\n\t\t\t\t}\n\t\t\t\tconst config = await deployedControllerConfig(state, context.codesys);\n\t\t\t\tif (!config) {\n\t\t\t\t\tthrow new AgentError(\n\t\t\t\t\t\t\"Nothing is deployed to the controller yet\",\n\t\t\t\t\t\t409,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tawait requireBuilder();\n\t\t\t\tawait warmed();\n\t\t\t\treturn restartWarmController(config, deployContainer, reset, {\n\t\t\t\t\tcredentials: await controllerCredentials(null),\n\t\t\t\t});\n\t\t\t}),\n\t\t/**\n\t\t * Stops the warm container once it has committed the last deployment, so an upgraded agent\n\t\t * starts one running its own code and none keeps the installed package's files in use.\n\t\t */\n\t\tretire: async () => {\n\t\t\tawait warming;\n\t\t\tconst config = await deployedControllerConfig(state, context.codesys);\n\t\t\tif (config) {\n\t\t\t\tawait settleWarmController(config, deployContainer);\n\t\t\t}\n\t\t\tawait removeContainer(deployContainer);\n\t\t},\n\t\t/**\n\t\t * `POST /deploy`: runs a deployment at once and streams its progress, as clients from before\n\t\t * `/api/deployments` expect. One that needs a download fails, for the client to ask again.\n\t\t */\n\t\tdeploy: async (\n\t\t\t/** Reads the upload once the client's version is checked, so a mismatch is reported before a large body is read. */\n\t\t\treadRequest: () => Promise<DeployRequest>,\n\t\t\tidentity: Identity,\n\t\t\tclient: ClientIdentity,\n\t\t\tclientTsplc: ClientRelease,\n\t\t) => {\n\t\t\tconst warnings = await clientWarnings(clientTsplc);\n\t\t\tcontext.operations.requireIdle();\n\t\t\trunner.requireIdle();\n\t\t\tawait requireBuilder();\n\t\t\tconst { settings, upload } = await readRequest();\n\t\t\tawait checkSubmission(state, settings.credentials);\n\t\t\t// A missing secret fails before anything stops.\n\t\t\tawait readSecrets(upload.manifest.secrets);\n\t\t\treturn context.operations.stream(\n\t\t\t\t\"a deployment\",\n\t\t\t\t(emit) =>\n\t\t\t\t\trunner.runNow(\n\t\t\t\t\t\tupload,\n\t\t\t\t\t\t// It runs at once, whatever mode the upload asks to be queued in.\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t...submissionFrom(settings, identity, client, warnings),\n\t\t\t\t\t\t\tmode: \"apply\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\t(line) => {\n\t\t\t\t\t\t\t// The failure itself ends the stream as its error.\n\t\t\t\t\t\t\tif (line.level === \"error\") {\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\temit({\n\t\t\t\t\t\t\t\tkind: \"progress\",\n\t\t\t\t\t\t\t\tmessage:\n\t\t\t\t\t\t\t\t\tline.level === \"warning\"\n\t\t\t\t\t\t\t\t\t\t? `Warning: ${line.message}`\n\t\t\t\t\t\t\t\t\t\t: line.message,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t},\n\t\t\t\t\t),\n\t\t\t\t{ reportsRollback: clientTsplc.version !== undefined },\n\t\t\t);\n\t\t},\n\t};\n};\n",
23
+ "import { once } from \"node:events\";\nimport { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport {\n\ttype ControllerResult,\n\tDownloadRequiredError,\n\tdescribeFinding,\n\ttype OnlineChangeReview,\n\trequiresDownload,\n} from \"@tsplc/build\";\nimport type { ResolvedConfig } from \"@tsplc/config/build\";\nimport { loadManifest } from \"@tsplc/debug\";\nimport { debugManifestFile } from \"@tsplc/debug/manifest\";\nimport { type CodesysSettings, controllerConfig } from \"../codesys\";\nimport { AgentError, errorMessage } from \"../errors\";\nimport { appendJsonl } from \"../logs\";\nimport { failureReport, type Operations } from \"../operations\";\nimport {\n\ttype Credentials,\n\tcancelableStates,\n\ttype Deployment,\n\ttype DeploymentEvent,\n\ttype DeploymentLogLine,\n\ttype DeploymentMode,\n\ttype DeploymentRecord,\n\ttype DeploymentState,\n\ttype GitSource,\n\ttype Release,\n} from \"../protocol\";\nimport {\n\tisStored,\n\tlistReleaseFiles,\n\tloadRelease,\n\treadReleaseFile,\n\treleaseServerFile,\n\treleaseServerPath,\n\ttype StoredRelease,\n\tsaveRelease,\n\ttype Upload,\n} from \"../releases\";\nimport { controllerCredentials, readSecrets, withSecrets } from \"../secrets\";\nimport type { ServerSupervisor } from \"../server-process\";\nimport type { AgentState } from \"../state\";\nimport { checkHealth, healthy } from \"./health\";\nimport { pruneDeployments } from \"./retention\";\nimport { activeDeployments, type DeploymentStore, isFinished } from \"./store\";\nimport { checkSubmission } from \"./submission\";\n\ntype Operation = DeploymentRecord[\"operation\"];\ntype PhaseName = DeploymentRecord[\"phases\"][number][\"name\"];\ntype Outcome = DeploymentRecord[\"phases\"][number][\"outcome\"];\ntype ApprovalReason = NonNullable<DeploymentRecord[\"approval\"]>[\"reason\"];\ntype Phase = DeploymentRecord[\"phases\"][number];\n\n/** What a deployment asks of CODESYS and Docker, which the runner sequences. */\nexport interface DeploymentController {\n\t/** Checks that Docker answers, the images can deploy and no login holds the controller; returns what to warn about. */\n\tready: () => Promise<string[]>;\n\t/** Waits until the last deployment's project is committed, which decides the download baseline. */\n\tsettle: (config: ResolvedConfig) => Promise<void>;\n\t/** Whether the controller has a download from this agent that an online change can build on. */\n\tbaseline: () => Promise<\"valid\" | \"missing\" | \"malformed\">;\n\treview: (\n\t\tconfig: ResolvedConfig,\n\t\toptions: {\n\t\t\tcredentials: Credentials;\n\t\t\tonProgress: (message: string) => void;\n\t\t},\n\t) => Promise<OnlineChangeReview>;\n\tapply: (\n\t\tconfig: ResolvedConfig,\n\t\toperation: Operation,\n\t\toptions: {\n\t\t\tinitializeUser: boolean;\n\t\t\tcredentials: Credentials;\n\t\t\tonProgress: (message: string) => void;\n\t\t},\n\t) => Promise<ControllerResult>;\n}\n\n/** A deployment to queue, and who asked for it. */\nexport interface Submission {\n\tgit: GitSource | null;\n\trequestedBy: DeploymentRecord[\"requestedBy\"];\n\tmode: DeploymentMode;\n\t/** A full download was asked for up front. */\n\tdownload: boolean;\n\t/** The controller user the request sent, held in memory only; null uses the one stored on the PC. */\n\tcredentials: Credentials | null;\n\tinitializeUser: boolean;\n\t/** Said first in the deployment's log. */\n\twarnings: string[];\n}\n\n/** What a deployment keeps only in memory, and how it is run. */\ninterface Handling {\n\tcredentials: Credentials | null;\n\tinitializeUser: boolean;\n\t/** A deployment that needs a download waits for approval; `POST /deploy`'s fail instead, as their clients expect. */\n\twaitsForApproval: boolean;\n}\n\n/** An unfinished deployment, with what it keeps only in memory. */\ninterface Pending extends Handling {\n\tid: string;\n\trelease: StoredRelease;\n\tcancellation: AbortController;\n\t/** Approved while `awaitingApproval`, and not yet picked up. */\n\tapproved: boolean;\n\t/** Being advanced right now, so a cancel takes effect at its next step. */\n\trunning: boolean;\n}\n\n/** Where `advance` left a deployment: the release it deployed, or the error it failed with; neither while it waits or once canceled. */\ninterface Advanced {\n\tdeployed: Release | null;\n\tfailure: { error: unknown } | null;\n}\n\nclass Canceled extends Error {}\n\nconst releaseBuild = async (release: StoredRelease) => {\n\tconst file = join(release.directory, debugManifestFile);\n\treturn existsSync(file) ? (await loadManifest(file)).build.id : null;\n};\n\n/**\n * Runs deployments one at a time, in the order they were queued, each as the agent's one\n * operation: build, review, apply, start the server, check health. A deployment waiting for\n * approval holds its place, but not the agent, so logins still open meanwhile.\n */\nexport const createDeploymentRunner = (context: {\n\tstore: DeploymentStore;\n\tstate: AgentState;\n\toperations: Operations;\n\tcodesys: CodesysSettings;\n\tserver: ServerSupervisor;\n\tcontroller: DeploymentController;\n\t/** Called once a deployment's release runs on the line, to replace what depends on it. */\n\tonActivated: () => void;\n\tnow: () => Date;\n\tlog: (message: string) => void;\n}) => {\n\tconst { store, state, operations, controller } = context;\n\tconst pending = new Map<string, Pending>();\n\t/** Deployments from `/api/deployments`, oldest first; `POST /deploy`'s run at once instead. */\n\tconst queue: Pending[] = [];\n\tlet draining = false;\n\t/** Saving a release and naming it in a record happen together, never between a prune's reads and deletes. */\n\tlet releasesTurn: Promise<unknown> = Promise.resolve();\n\n\tconst withReleases = <Result>(run: () => Promise<Result>) => {\n\t\tconst next = releasesTurn.then(run);\n\t\treleasesTurn = next.catch(() => undefined);\n\t\treturn next;\n\t};\n\n\tconst timestamp = () => context.now().toISOString();\n\n\tconst recordOf = store.get;\n\n\tconst say = (\n\t\titem: Pending,\n\t\tlevel: DeploymentLogLine[\"level\"],\n\t\tmessage: string,\n\t) => {\n\t\tconst phase =\n\t\t\trecordOf(item.id).phases.find((entry) => entry.outcome === \"running\")\n\t\t\t\t?.name ?? null;\n\t\t// The store logs a write that fails.\n\t\tstore.log(item.id, { level, phase, message }).catch(() => undefined);\n\t};\n\n\tconst update = (\n\t\titem: Pending,\n\t\tchange: (record: DeploymentRecord) => DeploymentRecord,\n\t) => store.update(item.id, change);\n\n\tconst startPhase = (item: Pending, name: PhaseName) =>\n\t\tupdate(item, (record) => ({\n\t\t\t...record,\n\t\t\tphases: [\n\t\t\t\t...record.phases,\n\t\t\t\t{ name, startedAt: timestamp(), finishedAt: null, outcome: \"running\" },\n\t\t\t],\n\t\t}));\n\n\tconst closeRunning = (\n\t\tphases: readonly Phase[],\n\t\toutcome: Exclude<Outcome, \"running\">,\n\t) => {\n\t\tconst at = timestamp();\n\t\treturn phases.map((phase) =>\n\t\t\tphase.outcome === \"running\"\n\t\t\t\t? { ...phase, finishedAt: at, outcome }\n\t\t\t\t: phase,\n\t\t);\n\t};\n\n\tconst finishPhase = (item: Pending, outcome: Exclude<Outcome, \"running\">) =>\n\t\tupdate(item, (record) => ({\n\t\t\t...record,\n\t\t\tphases: closeRunning(record.phases, outcome),\n\t\t}));\n\n\tconst skipPhase = (item: Pending, name: PhaseName) =>\n\t\tupdate(item, (record) => ({\n\t\t\t...record,\n\t\t\tphases: [\n\t\t\t\t...record.phases,\n\t\t\t\t{\n\t\t\t\t\tname,\n\t\t\t\t\tstartedAt: timestamp(),\n\t\t\t\t\tfinishedAt: timestamp(),\n\t\t\t\t\toutcome: \"skipped\",\n\t\t\t\t},\n\t\t\t],\n\t\t}));\n\n\tconst enter = (\n\t\titem: Pending,\n\t\tstate: DeploymentState,\n\t\tchanges: Partial<DeploymentRecord> = {},\n\t) => update(item, (record) => ({ ...record, ...changes, state }));\n\n\tconst requireNotCanceled = (item: Pending) => {\n\t\tif (item.cancellation.signal.aborted) {\n\t\t\tthrow new Canceled();\n\t\t}\n\t};\n\n\t/** Runs `run` as the agent's one operation once no login, logout or upgrade holds it. */\n\tconst whenFree = async <Result>(\n\t\titem: Pending,\n\t\trun: () => Promise<Result>,\n\t) => {\n\t\tconst waitingFor = operations.blockedBy();\n\t\tif (waitingFor) {\n\t\t\tsay(item, \"info\", `Waiting for ${waitingFor} to finish`);\n\t\t}\n\t\twhile (operations.blockedBy()) {\n\t\t\trequireNotCanceled(item);\n\t\t\tawait Promise.race([\n\t\t\t\toperations.whenIdle(),\n\t\t\t\tonce(item.cancellation.signal, \"abort\"),\n\t\t\t]);\n\t\t}\n\t\treturn operations.exclusive(\"a deployment\", run);\n\t};\n\n\t/** Stops to wait for a person; `POST /deploy`'s deployments fail instead. */\n\tconst awaitApproval = async (\n\t\titem: Pending,\n\t\treason: ApprovalReason,\n\t\tmessage: string,\n\t) => {\n\t\tif (!item.waitsForApproval) {\n\t\t\tthrow reason === \"downloadRequired\"\n\t\t\t\t? new DownloadRequiredError(message)\n\t\t\t\t: new AgentError(message, 409);\n\t\t}\n\t\titem.approved = false;\n\t\t// Waiting holds nothing, so a cancel from now on takes effect at once.\n\t\titem.running = false;\n\t\tsay(item, \"warning\", message);\n\t\tawait enter(item, \"awaitingApproval\", { approval: { reason, message } });\n\t\treturn null;\n\t};\n\n\tconst announce = (item: Pending, warnings: readonly string[]) => {\n\t\tfor (const warning of warnings) {\n\t\t\tsay(item, \"warning\", warning);\n\t\t}\n\t};\n\n\t/** The release's config for the selected controller with its secrets, once the last deployment is committed. */\n\tconst prepare = async (item: Pending) => {\n\t\tconst warnings = await controller.ready();\n\t\tconst target = await state.requireTarget();\n\t\tconst config = await withSecrets(\n\t\t\tcontrollerConfig(\n\t\t\t\titem.release,\n\t\t\t\ttarget,\n\t\t\t\tstate.paths.controller,\n\t\t\t\tcontext.codesys,\n\t\t\t),\n\t\t\tawait readSecrets(item.release.manifest.secrets),\n\t\t\tstate.paths.sources,\n\t\t);\n\t\tawait controller.settle(config);\n\t\treturn { config, warnings };\n\t};\n\n\tconst progress = (item: Pending) => (message: string) =>\n\t\tsay(item, \"info\", message);\n\n\tconst review = async (item: Pending, config: ResolvedConfig) => {\n\t\tconst { mode } = recordOf(item.id);\n\t\tawait startPhase(item, \"review\");\n\t\tconst result = await controller.review(config, {\n\t\t\tcredentials: await controllerCredentials(item.credentials),\n\t\t\tonProgress: progress(item),\n\t\t});\n\t\tawait update(item, (record) => ({ ...record, findings: result.findings }));\n\t\tawait finishPhase(item, \"ok\");\n\t\tfor (const finding of result.findings) {\n\t\t\tsay(item, finding.refuses ? \"warning\" : \"info\", describeFinding(finding));\n\t\t}\n\t\trequireNotCanceled(item);\n\t\tif (!result.possible) {\n\t\t\treturn awaitApproval(\n\t\t\t\titem,\n\t\t\t\t\"downloadRequired\",\n\t\t\t\t`CODESYS can't apply this as an online change${result.messages.length ? `: ${result.messages.join(\" \")}` : \"\"}. Only a full download, which stops the application, can deploy it`,\n\t\t\t);\n\t\t}\n\t\tif (mode === \"review\") {\n\t\t\treturn awaitApproval(\n\t\t\t\titem,\n\t\t\t\t\"review\",\n\t\t\t\t\"Review the online change's findings, then approve it to apply\",\n\t\t\t);\n\t\t}\n\t\treturn config;\n\t};\n\n\t/** Builds the deployment and reviews it; the config to apply, or null when it waits for approval. */\n\tconst build = async (item: Pending) => {\n\t\tawait finishPhase(item, \"ok\");\n\t\tawait enter(item, \"building\");\n\t\tawait startPhase(item, \"build\");\n\t\tconst { config, warnings } = await prepare(item);\n\t\tannounce(item, warnings);\n\t\tconst { operation, mode } = recordOf(item.id);\n\t\tconst baseline =\n\t\t\toperation === \"download\" ? \"valid\" : await controller.baseline();\n\t\tawait finishPhase(item, \"ok\");\n\t\trequireNotCanceled(item);\n\t\tif (baseline !== \"valid\") {\n\t\t\tawait skipPhase(item, \"review\");\n\t\t\treturn awaitApproval(\n\t\t\t\titem,\n\t\t\t\t\"downloadRequired\",\n\t\t\t\tbaseline === \"missing\"\n\t\t\t\t\t? \"The controller has no application downloaded by this agent; only a full download can deploy\"\n\t\t\t\t\t: \"This agent's record of the controller's download can't be read; only a full download can deploy\",\n\t\t\t);\n\t\t}\n\t\tif (operation === \"online-change\") {\n\t\t\treturn review(item, config);\n\t\t}\n\t\tawait skipPhase(item, \"review\");\n\t\tif (mode === \"review\") {\n\t\t\treturn awaitApproval(\n\t\t\t\titem,\n\t\t\t\t\"review\",\n\t\t\t\t\"Approve it to apply as a full download, which stops the application\",\n\t\t\t);\n\t\t}\n\t\treturn config;\n\t};\n\n\t/** Applies the release; the receipt, or null when an online change turned out to need a download. */\n\tconst apply = async (item: Pending, config: ResolvedConfig) => {\n\t\trequireNotCanceled(item);\n\t\tconst { operation } = recordOf(item.id);\n\t\tawait enter(item, \"applying\", { approval: null });\n\t\tawait startPhase(item, \"apply\");\n\t\tsay(item, \"info\", `Starting the ${operation}`);\n\t\tconst receipt = await controller\n\t\t\t.apply(config, operation, {\n\t\t\t\tinitializeUser: item.initializeUser,\n\t\t\t\tcredentials: await controllerCredentials(item.credentials),\n\t\t\t\tonProgress: progress(item),\n\t\t\t})\n\t\t\t.catch(async (error: unknown) => {\n\t\t\t\tif (operation === \"download\" || !requiresDownload(error)) {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tawait finishPhase(item, \"failed\");\n\t\t\t\tif (error instanceof DownloadRequiredError) {\n\t\t\t\t\tawait update(item, (record) => ({\n\t\t\t\t\t\t...record,\n\t\t\t\t\t\tfindings: error.findings,\n\t\t\t\t\t}));\n\t\t\t\t}\n\t\t\t\treturn awaitApproval(item, \"downloadRequired\", errorMessage(error));\n\t\t\t});\n\t\tif (!receipt) {\n\t\t\treturn null;\n\t\t}\n\t\tawait update(item, (record) => ({\n\t\t\t...record,\n\t\t\tcontrollerIds: receipt.controllerIds,\n\t\t}));\n\t\tawait finishPhase(item, \"ok\");\n\t\treturn receipt;\n\t};\n\n\t/** Starts the release's server, if it has one; why it failed, or undefined. */\n\tconst startServer = async (item: Pending, serverPath: string | undefined) => {\n\t\tif (!serverPath) {\n\t\t\tawait skipPhase(item, \"server\");\n\t\t\treturn undefined;\n\t\t}\n\t\tawait startPhase(item, \"server\");\n\t\tsay(item, \"info\", \"Starting the new server\");\n\t\t// A server that fails to start is replaced by the previous one again.\n\t\tconst failure = await context.server\n\t\t\t.replace(releaseServerFile(state.paths.releases, serverPath))\n\t\t\t.then(\n\t\t\t\t() => undefined,\n\t\t\t\t(error: unknown) => errorMessage(error),\n\t\t\t);\n\t\tawait finishPhase(item, failure === undefined ? \"ok\" : \"failed\");\n\t\treturn failure;\n\t};\n\n\t/** Marks the deployment as the one running on the line, and ends the previous one's time. */\n\tconst activate = async (item: Pending) => {\n\t\tconst at = timestamp();\n\t\tconst { current } = activeDeployments(store.list());\n\t\tif (current && current !== item.id) {\n\t\t\tawait store.update(current, (record) => ({\n\t\t\t\t...record,\n\t\t\t\tactiveUntil: at,\n\t\t\t}));\n\t\t}\n\t\tawait update(item, (record) => ({\n\t\t\t...record,\n\t\t\tactiveFrom: at,\n\t\t\tactiveUntil: null,\n\t\t}));\n\t};\n\n\t/** Starts the server and records the release as deployed; the controller already runs it. */\n\tconst startRelease = async (item: Pending, receipt: ControllerResult) => {\n\t\tconst { release } = item;\n\t\tconst record = recordOf(item.id);\n\t\tawait enter(item, \"starting\");\n\t\tconst serverPath = releaseServerPath(release);\n\t\tconst previous = await state.release();\n\t\tconst serverFailure = await startServer(item, serverPath);\n\t\tconst deployed: Release = {\n\t\t\tid: release.id,\n\t\t\tdeployedAt: timestamp(),\n\t\t\toperation: record.operation,\n\t\t\tcontrollerIds: receipt.controllerIds,\n\t\t\t// A release without a server, or whose server failed, leaves the previous one running.\n\t\t\tserver:\n\t\t\t\tserverFailure === undefined\n\t\t\t\t\t? (serverPath ?? previous?.server)\n\t\t\t\t\t: previous?.server,\n\t\t};\n\t\tawait state.setRelease(deployed);\n\t\tconst line: Deployment = {\n\t\t\tat: deployed.deployedAt,\n\t\t\trelease: release.id,\n\t\t\t...(record.build !== null && { build: record.build }),\n\t\t\toperation: record.operation,\n\t\t\tcredentials: item.credentials ? \"provided\" : \"stored\",\n\t\t\t...(record.requestedBy.user !== null && {\n\t\t\t\tuser: record.requestedBy.user,\n\t\t\t}),\n\t\t\t...(record.requestedBy.host !== null && {\n\t\t\t\thost: record.requestedBy.host,\n\t\t\t}),\n\t\t};\n\t\tawait appendJsonl(state.paths.deployments, line);\n\t\tawait activate(item);\n\t\tcontext.onActivated();\n\t\tif (serverFailure !== undefined) {\n\t\t\tthrow new Error(\n\t\t\t\t`The controller runs release ${release.id}. ${serverFailure}`,\n\t\t\t);\n\t\t}\n\t\treturn deployed;\n\t};\n\n\tconst verify = async (item: Pending, receipt: ControllerResult) => {\n\t\tawait enter(item, \"verifying\");\n\t\tawait startPhase(item, \"health\");\n\t\tconst health = await checkHealth({\n\t\t\tcontrollerState: receipt.state,\n\t\t\thasServer: item.release.manifest.server !== undefined,\n\t\t\tserver: context.server,\n\t\t});\n\t\tawait update(item, (record) => ({ ...record, health }));\n\t\tif (!healthy(health)) {\n\t\t\tthrow new Error(health.detail ?? \"The deployment isn't healthy\");\n\t\t}\n\t\tawait finishPhase(item, \"ok\");\n\t\tsay(item, \"info\", health.detail ? `Ready. ${health.detail}` : \"Ready\");\n\t\tawait enter(item, \"ready\");\n\t};\n\n\tconst fail = async (item: Pending, error: unknown) => {\n\t\tif (error instanceof Canceled) {\n\t\t\tawait finishPhase(item, \"skipped\");\n\t\t\tawait enter(item, \"canceled\", { approval: null });\n\t\t\treturn;\n\t\t}\n\t\tcontext.log(\n\t\t\t`Deployment ${item.id} failed: ${error instanceof Error ? error.stack : String(error)}`,\n\t\t);\n\t\tawait finishPhase(item, \"failed\");\n\t\tsay(item, \"error\", errorMessage(error));\n\t\tawait enter(item, \"error\", { approval: null, error: failureReport(error) });\n\t};\n\n\tconst prune = () =>\n\t\twithReleases(async () => {\n\t\t\tconst pruned = await pruneDeployments({\n\t\t\t\tstore,\n\t\t\t\treleases: state.paths.releases,\n\t\t\t\tdeployed: await state.release(),\n\t\t\t\tnow: context.now,\n\t\t\t});\n\t\t\tif (pruned.deployments.length || pruned.releases.length) {\n\t\t\t\tcontext.log(\n\t\t\t\t\t`Removed ${pruned.deployments.length} deployments and ${pruned.releases.length} releases older than the retention`,\n\t\t\t\t);\n\t\t\t}\n\t\t}).catch((error: unknown) =>\n\t\t\tcontext.log(`Pruning deployments failed: ${errorMessage(error)}`),\n\t\t);\n\n\tconst waitsForPerson = (item: Pending) =>\n\t\trecordOf(item.id).state === \"awaitingApproval\" && !item.approved;\n\n\tconst conclude = (item: Pending) => {\n\t\tif (recordOf(item.id).state === \"awaitingApproval\") {\n\t\t\treturn;\n\t\t}\n\t\tpending.delete(item.id);\n\t\tconst index = queue.indexOf(item);\n\t\tif (index >= 0) {\n\t\t\tqueue.splice(index, 1);\n\t\t}\n\t\tvoid prune();\n\t};\n\n\t/** Takes the deployment as far as it goes: finished, or waiting for approval. */\n\tconst advance = async (\n\t\titem: Pending,\n\t\tlock: (run: () => Promise<Release | null>) => Promise<Release | null>,\n\t): Promise<Advanced> => {\n\t\titem.running = true;\n\t\ttry {\n\t\t\tconst deployed = await lock(async () => {\n\t\t\t\trequireNotCanceled(item);\n\t\t\t\tconst config =\n\t\t\t\t\trecordOf(item.id).state === \"queued\"\n\t\t\t\t\t\t? await build(item)\n\t\t\t\t\t\t: (await prepare(item)).config;\n\t\t\t\tif (!config) {\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t\tconst receipt = await apply(item, config);\n\t\t\t\tif (!receipt) {\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t\tconst release = await startRelease(item, receipt);\n\t\t\t\tawait verify(item, receipt);\n\t\t\t\treturn release;\n\t\t\t});\n\t\t\treturn { deployed, failure: null };\n\t\t} catch (error) {\n\t\t\tawait fail(item, error).catch((failure: unknown) =>\n\t\t\t\tcontext.log(\n\t\t\t\t\t`Recording deployment ${item.id}'s failure failed: ${errorMessage(failure)}`,\n\t\t\t\t),\n\t\t\t);\n\t\t\treturn {\n\t\t\t\tdeployed: null,\n\t\t\t\tfailure: error instanceof Canceled ? null : { error },\n\t\t\t};\n\t\t} finally {\n\t\t\titem.running = false;\n\t\t\tconclude(item);\n\t\t}\n\t};\n\n\tconst advanceQueue = async (): Promise<void> => {\n\t\tconst [head] = queue;\n\t\tif (!head || waitsForPerson(head)) {\n\t\t\treturn;\n\t\t}\n\t\tawait advance(head, (run) => whenFree(head, run));\n\t\treturn advanceQueue();\n\t};\n\n\tconst drain = async () => {\n\t\tif (draining) {\n\t\t\treturn;\n\t\t}\n\t\tdraining = true;\n\t\ttry {\n\t\t\tawait advanceQueue();\n\t\t} finally {\n\t\t\tdraining = false;\n\t\t}\n\t};\n\n\tconst create = async (\n\t\trelease: StoredRelease,\n\t\trequested: Pick<\n\t\t\tDeploymentRecord,\n\t\t\t\"origin\" | \"git\" | \"requestedBy\" | \"mode\" | \"operation\"\n\t\t>,\n\t\thandling: Handling,\n\t) => {\n\t\tconst at = timestamp();\n\t\tconst record: DeploymentRecord = {\n\t\t\tid: store.newId(),\n\t\t\trelease: release.id,\n\t\t\tbuild: await releaseBuild(release),\n\t\t\tcreatedAt: at,\n\t\t\tupdatedAt: at,\n\t\t\t...requested,\n\t\t\tstate: \"queued\",\n\t\t\tphases: [\n\t\t\t\t{ name: \"queue\", startedAt: at, finishedAt: null, outcome: \"running\" },\n\t\t\t],\n\t\t\tfindings: [],\n\t\t\tapproval: null,\n\t\t\terror: null,\n\t\t\tcontrollerIds: null,\n\t\t\thealth: null,\n\t\t\tactiveFrom: null,\n\t\t\tactiveUntil: null,\n\t\t};\n\t\tawait store.create(record);\n\t\tconst item: Pending = {\n\t\t\tid: record.id,\n\t\t\trelease,\n\t\t\t...handling,\n\t\t\tcancellation: new AbortController(),\n\t\t\tapproved: false,\n\t\t\trunning: false,\n\t\t};\n\t\tpending.set(item.id, item);\n\t\treturn item;\n\t};\n\n\tconst createUpload = (\n\t\trelease: StoredRelease,\n\t\tsubmission: Submission,\n\t\toptions: { waitsForApproval: boolean },\n\t) =>\n\t\tcreate(\n\t\t\trelease,\n\t\t\t{\n\t\t\t\torigin: { kind: \"upload\" },\n\t\t\t\tgit: submission.git,\n\t\t\t\trequestedBy: submission.requestedBy,\n\t\t\t\tmode: submission.mode,\n\t\t\t\toperation: submission.download ? \"download\" : \"online-change\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tcredentials: submission.credentials,\n\t\t\t\tinitializeUser: submission.initializeUser,\n\t\t\t\twaitsForApproval: options.waitsForApproval,\n\t\t\t},\n\t\t);\n\n\tconst enqueue = (item: Pending, warnings: readonly string[]) => {\n\t\tannounce(item, warnings);\n\t\tqueue.push(item);\n\t\tvoid drain();\n\t\treturn recordOf(item.id);\n\t};\n\n\t/** A new deployment of `source`'s release, with the controller user stored on the PC. */\n\tconst again = async (\n\t\tsource: DeploymentRecord,\n\t\torigin: DeploymentRecord[\"origin\"],\n\t\tmode: DeploymentMode,\n\t\trequestedBy: DeploymentRecord[\"requestedBy\"],\n\t) => {\n\t\tawait checkSubmission(state, null);\n\t\treturn withReleases(async () => {\n\t\t\tif (!isStored(state.paths.releases, source.release)) {\n\t\t\t\tthrow new AgentError(\n\t\t\t\t\t`The release of ${source.id}, ${source.release}, is no longer stored`,\n\t\t\t\t\t409,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst release = await loadRelease(state.paths.releases, source.release);\n\t\t\tconst item = await create(\n\t\t\t\trelease,\n\t\t\t\t{\n\t\t\t\t\torigin,\n\t\t\t\t\tgit: source.git,\n\t\t\t\t\trequestedBy,\n\t\t\t\t\tmode,\n\t\t\t\t\toperation: \"online-change\",\n\t\t\t\t},\n\t\t\t\t{ credentials: null, initializeUser: false, waitsForApproval: true },\n\t\t\t);\n\t\t\treturn enqueue(item, []);\n\t\t});\n\t};\n\n\treturn {\n\t\t/** Ends what a previous agent left unfinished, then prunes. */\n\t\tstart: async () => {\n\t\t\tfor (const record of store.list().filter((entry) => !isFinished(entry))) {\n\t\t\t\tawait store.update(record.id, (unfinished) => ({\n\t\t\t\t\t...unfinished,\n\t\t\t\t\tstate: \"error\",\n\t\t\t\t\tapproval: null,\n\t\t\t\t\tphases: closeRunning(unfinished.phases, \"failed\"),\n\t\t\t\t\terror: {\n\t\t\t\t\t\tmessage: \"The plant agent stopped before this deployment finished\",\n\t\t\t\t\t\tdownloadRequired: false,\n\t\t\t\t\t},\n\t\t\t\t}));\n\t\t\t}\n\t\t\tawait prune();\n\t\t},\n\t\t/** Stores an uploaded release and queues its deployment. */\n\t\tsubmit: async (upload: Upload, submission: Submission) => {\n\t\t\tawait checkSubmission(state, submission.credentials);\n\t\t\treturn withReleases(async () => {\n\t\t\t\tconst item = await createUpload(\n\t\t\t\t\tawait saveRelease(state.paths.releases, upload),\n\t\t\t\t\tsubmission,\n\t\t\t\t\t{ waitsForApproval: true },\n\t\t\t\t);\n\t\t\t\treturn enqueue(item, submission.warnings);\n\t\t\t});\n\t\t},\n\t\t/** Deploys a finished deployment's release again. */\n\t\tredeploy: async (\n\t\t\tid: string,\n\t\t\tmode: DeploymentMode,\n\t\t\trequestedBy: DeploymentRecord[\"requestedBy\"],\n\t\t) => {\n\t\t\tconst source = recordOf(id);\n\t\t\tif (!isFinished(source)) {\n\t\t\t\tthrow new AgentError(\n\t\t\t\t\t`Deployment ${id} is ${source.state}; only a finished deployment can be redeployed`,\n\t\t\t\t\t409,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn again(source, { kind: \"redeploy\", from: id }, mode, requestedBy);\n\t\t},\n\t\t/** Deploys again the release of a deployment that ran healthy, but not the one running now. */\n\t\trollback: async (\n\t\t\tid: string,\n\t\t\trequestedBy: DeploymentRecord[\"requestedBy\"],\n\t\t) => {\n\t\t\tconst source = recordOf(id);\n\t\t\tif (source.state !== \"ready\") {\n\t\t\t\tthrow new AgentError(\n\t\t\t\t\t`Deployment ${id} is ${source.state}; only a ready deployment can be rolled back to`,\n\t\t\t\t\t409,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (activeDeployments(store.list()).current === id) {\n\t\t\t\tthrow new AgentError(\n\t\t\t\t\t`Deployment ${id} runs now; there is nothing to roll back`,\n\t\t\t\t\t409,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn again(\n\t\t\t\tsource,\n\t\t\t\t{ kind: \"rollback\", from: id },\n\t\t\t\t\"apply\",\n\t\t\t\trequestedBy,\n\t\t\t);\n\t\t},\n\t\tapprove: async (\n\t\t\tid: string,\n\t\t\t{ download }: { download: boolean },\n\t\t\tby: string,\n\t\t) => {\n\t\t\tconst record = recordOf(id);\n\t\t\tconst item = pending.get(id);\n\t\t\tif (!item || record.state !== \"awaitingApproval\" || item.approved) {\n\t\t\t\tthrow new AgentError(`Deployment ${id} isn't awaiting approval`, 409);\n\t\t\t}\n\t\t\tif (record.approval?.reason === \"downloadRequired\" && !download) {\n\t\t\t\tthrow new AgentError(\n\t\t\t\t\t`Only a full download can apply deployment ${id}; approve it with a download`,\n\t\t\t\t\t409,\n\t\t\t\t);\n\t\t\t}\n\t\t\titem.approved = true;\n\t\t\tsay(\n\t\t\t\titem,\n\t\t\t\t\"info\",\n\t\t\t\t`${by} approved it${download ? \" as a full download\" : \"\"}`,\n\t\t\t);\n\t\t\tconst approved = await update(item, (current) => ({\n\t\t\t\t...current,\n\t\t\t\toperation: download ? \"download\" : current.operation,\n\t\t\t}));\n\t\t\tvoid drain();\n\t\t\treturn approved;\n\t\t},\n\t\t/** Cancels a deployment before it applies; one being built stops at its next step, and its record says so then. */\n\t\tcancel: async (id: string, by: string) => {\n\t\t\tconst record = recordOf(id);\n\t\t\tconst item = pending.get(id);\n\t\t\tif (!item || !cancelableStates.includes(record.state)) {\n\t\t\t\tthrow new AgentError(\n\t\t\t\t\t`Deployment ${id} is ${record.state}; a deployment can only be canceled before it applies`,\n\t\t\t\t\t409,\n\t\t\t\t);\n\t\t\t}\n\t\t\titem.cancellation.abort();\n\t\t\tsay(item, \"info\", `${by} canceled it`);\n\t\t\tif (item.running) {\n\t\t\t\treturn record;\n\t\t\t}\n\t\t\t// Off the queue before anything awaits, so the queue never picks it up.\n\t\t\tconst index = queue.indexOf(item);\n\t\t\tif (index >= 0) {\n\t\t\t\tqueue.splice(index, 1);\n\t\t\t}\n\t\t\tawait fail(item, new Canceled());\n\t\t\tconclude(item);\n\t\t\tvoid drain();\n\t\t\treturn recordOf(id);\n\t\t},\n\t\t/**\n\t\t * Refuses `POST /deploy` while deployments are queued, since it runs at once: one waiting for\n\t\t * approval would otherwise be applied over.\n\t\t */\n\t\trequireIdle: () => {\n\t\t\tconst [head] = queue;\n\t\t\tif (!head) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthrow new AgentError(\n\t\t\t\twaitsForPerson(head)\n\t\t\t\t\t? `Deployment ${head.id} waits for approval on the dashboard; approve or cancel it first`\n\t\t\t\t\t: \"The agent is busy with a deployment\",\n\t\t\t\t409,\n\t\t\t);\n\t\t},\n\t\t/**\n\t\t * Stores and runs a `POST /deploy` deployment at once, inside the caller's operation, telling\n\t\t * `onLine` each line of its log. Fails as the deployment did.\n\t\t */\n\t\trunNow: async (\n\t\t\tupload: Upload,\n\t\t\tsubmission: Submission,\n\t\t\tonLine: (line: DeploymentLogLine) => void,\n\t\t) => {\n\t\t\tconst item = await withReleases(async () =>\n\t\t\t\tcreateUpload(\n\t\t\t\t\tawait saveRelease(state.paths.releases, upload),\n\t\t\t\t\tsubmission,\n\t\t\t\t\t{ waitsForApproval: false },\n\t\t\t\t),\n\t\t\t);\n\t\t\tconst unsubscribe = store.subscribe(item.id, (event) => {\n\t\t\t\tif (event.kind === \"log\") {\n\t\t\t\t\tonLine(event.line);\n\t\t\t\t}\n\t\t\t});\n\t\t\ttry {\n\t\t\t\tannounce(item, submission.warnings);\n\t\t\t\tconst { deployed, failure } = await advance(item, (run) => run());\n\t\t\t\tawait store.flush(item.id);\n\t\t\t\tif (failure) {\n\t\t\t\t\tthrow failure.error;\n\t\t\t\t}\n\t\t\t\tif (!deployed) {\n\t\t\t\t\tthrow new AgentError(`Deployment ${item.id} was canceled`, 409);\n\t\t\t\t}\n\t\t\t\treturn deployed;\n\t\t\t} finally {\n\t\t\t\tunsubscribe();\n\t\t\t}\n\t\t},\n\t\tlist: () => {\n\t\t\tconst deployments = store.list();\n\t\t\treturn { deployments, ...activeDeployments(deployments) };\n\t\t},\n\t\tget: recordOf,\n\t\tlines: (id: string, after: number) => {\n\t\t\trecordOf(id);\n\t\t\treturn store.lines(id, after);\n\t\t},\n\t\tsubscribe: (id: string, listener: (event: DeploymentEvent) => void) => {\n\t\t\trecordOf(id);\n\t\t\treturn store.subscribe(id, listener);\n\t\t},\n\t\t/** The deployment's release files, by path, with their sizes. */\n\t\tsource: (id: string) =>\n\t\t\tlistReleaseFiles(state.paths.releases, recordOf(id).release),\n\t\tsourceFile: (id: string, path: string) =>\n\t\t\treadReleaseFile(state.paths.releases, recordOf(id).release, path),\n\t};\n};\nexport type DeploymentRunner = ReturnType<typeof createDeploymentRunner>;\n",
24
+ "import { requiresDownload, transferRollback } from \"@tsplc/build\";\nimport { AgentError, errorMessage } from \"./errors\";\nimport type { AgentEvent } from \"./protocol\";\n\n/** What the agent can be busy with, as its messages name it. */\nexport type Operation =\n\t| \"a deployment\"\n\t| \"a login\"\n\t| \"a logout\"\n\t| \"a server restart\"\n\t| \"a controller restart\";\n\n/**\n * A failed operation as its clients hear it: whether only a full download can deploy, and what\n * became of the controller after a download failed mid-transfer.\n */\nexport const failureReport = (error: unknown) => {\n\tconst rollback = transferRollback(error);\n\treturn {\n\t\tmessage: errorMessage(error),\n\t\tdownloadRequired: requiresDownload(error),\n\t\t...(rollback && { rollback }),\n\t};\n};\n\n/** The agent runs one deployment, login or logout at a time, and none while it is held for an upgrade. */\nexport const createOperations = (log: (message: string) => void) => {\n\tlet busy: Operation | undefined;\n\tlet held = false;\n\tconst waiting = new Set<() => void>();\n\n\tconst requireIdle = () => {\n\t\tif (held) {\n\t\t\tthrow new AgentError(\n\t\t\t\t\"The plant agent is being upgraded; try again once it is back\",\n\t\t\t\t503,\n\t\t\t);\n\t\t}\n\t\tif (busy) {\n\t\t\tthrow new AgentError(`The agent is busy with ${busy}`, 409);\n\t\t}\n\t};\n\n\tconst wakeWaiting = () => {\n\t\tfor (const wake of waiting) {\n\t\t\twake();\n\t\t}\n\t\twaiting.clear();\n\t};\n\n\tconst acquire = (operation: Operation) => {\n\t\trequireIdle();\n\t\tbusy = operation;\n\t};\n\n\tconst free = () => {\n\t\tbusy = undefined;\n\t\twakeWaiting();\n\t};\n\n\t/** What keeps the agent from starting an operation, as its messages name it. */\n\tconst blockedBy = () => (held ? \"the plant agent's upgrade\" : busy);\n\n\treturn {\n\t\tbusy: () => busy,\n\t\tblockedBy,\n\t\t/** Resolves once nothing blocks the agent, which another caller may take again first. */\n\t\twhenIdle: () =>\n\t\t\tblockedBy()\n\t\t\t\t? new Promise<void>((resolve) => waiting.add(resolve))\n\t\t\t\t: Promise.resolve(),\n\t\trequireIdle,\n\t\t/** Refuses every operation from now on; fails while one runs. */\n\t\thold: () => {\n\t\t\trequireIdle();\n\t\t\theld = true;\n\t\t},\n\t\trelease: () => {\n\t\t\theld = false;\n\t\t\twakeWaiting();\n\t\t},\n\t\theld: () => held,\n\t\t/** Runs `run` as the agent's one operation. */\n\t\texclusive: async <Result>(\n\t\t\toperation: Operation,\n\t\t\trun: () => Promise<Result>,\n\t\t) => {\n\t\t\tacquire(operation);\n\t\t\ttry {\n\t\t\t\treturn await run();\n\t\t\t} finally {\n\t\t\t\tfree();\n\t\t\t}\n\t\t},\n\t\t/**\n\t\t * Streams one exclusive operation's events, then its result, as newline-delimited JSON. A\n\t\t * failure names its `rollback` only to a client that `reportsRollback`.\n\t\t */\n\t\tstream: (\n\t\t\toperation: Operation,\n\t\t\trun: (emit: (event: AgentEvent) => void) => Promise<unknown>,\n\t\t\t{ reportsRollback = false }: { reportsRollback?: boolean } = {},\n\t\t) => {\n\t\t\tacquire(operation);\n\t\t\tconst encoder = new TextEncoder();\n\t\t\t// A client that disconnects doesn't stop the operation; it just stops hearing about it.\n\t\t\tlet listening = true;\n\t\t\treturn new Response(\n\t\t\t\tnew ReadableStream({\n\t\t\t\t\tstart: async (controller) => {\n\t\t\t\t\t\tconst write = (text: string) => {\n\t\t\t\t\t\t\tif (listening) {\n\t\t\t\t\t\t\t\tcontroller.enqueue(encoder.encode(text));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t};\n\t\t\t\t\t\tconst emit = (event: AgentEvent) =>\n\t\t\t\t\t\t\twrite(`${JSON.stringify(event)}\\n`);\n\t\t\t\t\t\t// CODESYS can stay silent for minutes; blank lines keep proxies from closing the stream.\n\t\t\t\t\t\tconst heartbeat = setInterval(() => write(\"\\n\"), 15_000);\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\temit({ kind: \"done\", result: await run(emit) });\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tlog(\n\t\t\t\t\t\t\t\t`${operation} failed: ${error instanceof Error ? error.stack : String(error)}`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tconst { rollback, ...failure } = failureReport(error);\n\t\t\t\t\t\t\temit({\n\t\t\t\t\t\t\t\tkind: \"error\",\n\t\t\t\t\t\t\t\t...failure,\n\t\t\t\t\t\t\t\t...(reportsRollback && rollback && { rollback }),\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t} finally {\n\t\t\t\t\t\t\tclearInterval(heartbeat);\n\t\t\t\t\t\t\tfree();\n\t\t\t\t\t\t\tif (listening) {\n\t\t\t\t\t\t\t\tcontroller.close();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\tcancel: () => {\n\t\t\t\t\t\tlistening = false;\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t\t{ headers: { \"Content-Type\": \"application/x-ndjson\" } },\n\t\t\t);\n\t\t},\n\t};\n};\nexport type Operations = ReturnType<typeof createOperations>;\n",
25
+ "import { healthReplySchema } from \"@tsplc/server/plant-agent\";\nimport { errorMessage } from \"../errors\";\nimport type { DeploymentRecord } from \"../protocol\";\nimport type { ServerSupervisor } from \"../server-process\";\n\ntype Health = NonNullable<DeploymentRecord[\"health\"]>;\n\n/** The server's and the PLC's health, and why the server failed its check. */\ninterface ServerHealth extends Pick<Health, \"server\" | \"plc\"> {\n\tfailure: string | null;\n}\n\nconst healthTimeoutMs = 5000;\n\n/** Anything but tsPLC's health reply on the server's health route leaves the PLC unknown. */\nconst plcHealth = (body: unknown): Health[\"plc\"] => {\n\tconst parsed = healthReplySchema.safeParse(body);\n\tif (!parsed.success) {\n\t\treturn \"unknown\";\n\t}\n\treturn parsed.data.plcConnected ? \"ok\" : \"failed\";\n};\n\nconst serverHealth = async (\n\tserver: ServerSupervisor,\n): Promise<ServerHealth> => {\n\tconst { healthUrl } = server;\n\tif (healthUrl === null) {\n\t\treturn server.status()?.running\n\t\t\t? { server: \"ok\", plc: \"unknown\", failure: null }\n\t\t\t: {\n\t\t\t\t\tserver: \"failed\",\n\t\t\t\t\tplc: \"unknown\",\n\t\t\t\t\tfailure: \"The server isn't running\",\n\t\t\t\t};\n\t}\n\tconst response = await fetch(healthUrl, {\n\t\tsignal: AbortSignal.timeout(healthTimeoutMs),\n\t}).catch((error: unknown) => errorMessage(error));\n\tif (typeof response === \"string\") {\n\t\treturn {\n\t\t\tserver: \"failed\",\n\t\t\tplc: \"unknown\",\n\t\t\tfailure: `The server doesn't answer on ${healthUrl}: ${response}`,\n\t\t};\n\t}\n\tif (!response.ok) {\n\t\treturn {\n\t\t\tserver: \"failed\",\n\t\t\tplc: \"unknown\",\n\t\t\tfailure: `The server answers ${response.status} on ${healthUrl}`,\n\t\t};\n\t}\n\treturn {\n\t\tserver: \"ok\",\n\t\tplc: plcHealth(await response.json().catch(() => null)),\n\t\tfailure: null,\n\t};\n};\n\nconst noServer: ServerHealth = {\n\tserver: \"none\",\n\tplc: \"unknown\",\n\tfailure: null,\n};\n\n/**\n * The check after a deployment applied: the controller runs its application, the release's server\n * answers, and the server reaches the PLC.\n */\nexport const checkHealth = async (options: {\n\t/** The application's state in the controller's receipt. */\n\tcontrollerState: string;\n\t/** The release has a server, which the agent started. */\n\thasServer: boolean;\n\tserver: ServerSupervisor;\n}): Promise<Health> => {\n\tconst controller = options.controllerState === \"run\" ? \"ok\" : \"failed\";\n\tconst { server, plc, failure } = options.hasServer\n\t\t? await serverHealth(options.server)\n\t\t: noServer;\n\tconst problems = [\n\t\tcontroller === \"failed\" &&\n\t\t\t`The controller's application is in state ${options.controllerState}`,\n\t\tfailure,\n\t\tplc === \"failed\" && \"The server isn't connected to the PLC\",\n\t].filter((problem) => typeof problem === \"string\");\n\treturn {\n\t\tcontroller,\n\t\tserver,\n\t\tplc,\n\t\tdetail: problems.length ? problems.join(\". \") : null,\n\t};\n};\n\n/** Whether a deployment with this health counts as ready; a server still connecting to the PLC doesn't fail it. */\nexport const healthy = (health: Health) =>\n\thealth.controller === \"ok\" && health.server !== \"failed\";\n",
26
+ "import { randomBytes } from \"node:crypto\";\nimport { existsSync } from \"node:fs\";\nimport { mkdir, readdir, readFile, rm } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { AgentError, errorMessage } from \"../errors\";\nimport { appendJsonLine, parsesAsJson } from \"../logs\";\nimport {\n\ttype DeploymentEvent,\n\ttype DeploymentLogLine,\n\ttype DeploymentRecord,\n\tdeploymentLogLineSchema,\n\tdeploymentRecordSchema,\n\tfinalStates,\n} from \"../protocol\";\nimport { readJsonFileIfValid, writeJsonFile } from \"../state\";\n\nexport const isFinished = (record: DeploymentRecord) =>\n\tfinalStates.includes(record.state);\n\n/**\n * The deployment running on the line, which no other has replaced yet, and the healthy one that\n * ran last.\n */\nexport const activeDeployments = (records: readonly DeploymentRecord[]) => {\n\ttype Activated = DeploymentRecord & { activeFrom: string };\n\tconst running = records.filter(\n\t\t(record): record is Activated => record.activeFrom !== null,\n\t);\n\tconst newest = (candidates: Activated[]) =>\n\t\tcandidates.reduce<Activated | null>(\n\t\t\t(best, record) =>\n\t\t\t\tbest && best.activeFrom >= record.activeFrom ? best : record,\n\t\t\tnull,\n\t\t)?.id ?? null;\n\treturn {\n\t\tcurrent: newest(running.filter((record) => record.activeUntil === null)),\n\t\tlastGood: newest(running.filter((record) => record.state === \"ready\")),\n\t};\n};\n\nconst newId = () =>\n\t`dpl_${[...randomBytes(20)].map((byte) => (byte % 36).toString(36)).join(\"\")}`;\n\n/**\n * Deployment records and logs under `directory`: `<id>/record.json`, rewritten whole through a\n * temporary file, and `<id>/log.jsonl`, appended. Records are held in memory too, so reading one\n * never waits on the disk; each deployment's writes happen in the order they were made.\n */\nexport const openDeploymentStore = async (options: {\n\tdirectory: string;\n\tnow: () => Date;\n\tlog: (message: string) => void;\n}) => {\n\tconst { directory } = options;\n\tconst records = new Map<string, DeploymentRecord>();\n\t/** The last log line's `seq` for each deployment whose log has been read or written. */\n\tconst sequences = new Map<string, number>();\n\tconst writes = new Map<string, Promise<void>>();\n\tconst listeners = new Map<string, Set<(event: DeploymentEvent) => void>>();\n\n\tawait mkdir(directory, { recursive: true });\n\tfor (const entry of await readdir(directory, { withFileTypes: true })) {\n\t\tconst file = join(directory, entry.name, \"record.json\");\n\t\tif (!entry.isDirectory() || !existsSync(file)) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst record = await readJsonFileIfValid(file, deploymentRecordSchema);\n\t\tif (record?.id === entry.name) {\n\t\t\trecords.set(record.id, record);\n\t\t} else {\n\t\t\toptions.log(`Skipping the unreadable deployment record ${file}`);\n\t\t}\n\t}\n\n\tconst recordDirectory = (id: string) => join(directory, id);\n\tconst logFile = (id: string) => join(recordDirectory(id), \"log.jsonl\");\n\n\t/** Runs `write` after the deployment's earlier writes, whether or not they failed. */\n\tconst inTurn = <Result>(id: string, write: () => Promise<Result>) => {\n\t\tconst next = (writes.get(id) ?? Promise.resolve()).then(write);\n\t\twrites.set(\n\t\t\tid,\n\t\t\tnext.then(\n\t\t\t\t() => undefined,\n\t\t\t\t(error: unknown) =>\n\t\t\t\t\toptions.log(\n\t\t\t\t\t\t`Writing deployment ${id} failed: ${errorMessage(error)}`,\n\t\t\t\t\t),\n\t\t\t),\n\t\t);\n\t\treturn next;\n\t};\n\n\tconst emit = (id: string, event: DeploymentEvent) => {\n\t\tfor (const listener of listeners.get(id) ?? []) {\n\t\t\tlistener(event);\n\t\t}\n\t};\n\n\tconst readLines = async (id: string) => {\n\t\tconst file = logFile(id);\n\t\tif (!existsSync(file)) {\n\t\t\treturn [];\n\t\t}\n\t\treturn (await readFile(file, \"utf8\"))\n\t\t\t.split(\"\\n\")\n\t\t\t.filter(Boolean)\n\t\t\t.flatMap((line) => {\n\t\t\t\t// A crash can leave the last line half written; it is skipped.\n\t\t\t\tconst parsed = deploymentLogLineSchema.safeParse(\n\t\t\t\t\tparsesAsJson(line)?.json,\n\t\t\t\t);\n\t\t\t\treturn parsed.success ? [parsed.data] : [];\n\t\t\t});\n\t};\n\n\tconst writeRecord = (record: DeploymentRecord) =>\n\t\tinTurn(record.id, async () => {\n\t\t\t// The newest state is written, which may already include later changes.\n\t\t\tconst latest = records.get(record.id);\n\t\t\tif (!latest) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait mkdir(recordDirectory(record.id), { recursive: true });\n\t\t\twriteJsonFile(join(recordDirectory(record.id), \"record.json\"), latest);\n\t\t});\n\n\tconst get = (id: string) => {\n\t\tconst record = records.get(id);\n\t\tif (!record) {\n\t\t\tthrow new AgentError(`No deployment ${id}`, 404);\n\t\t}\n\t\treturn record;\n\t};\n\n\treturn {\n\t\tnewId,\n\t\tget,\n\t\t/** Every deployment, newest first. */\n\t\tlist: () =>\n\t\t\t[...records.values()].sort((left, right) =>\n\t\t\t\tright.createdAt.localeCompare(left.createdAt),\n\t\t\t),\n\t\tcreate: async (record: DeploymentRecord) => {\n\t\t\trecords.set(record.id, record);\n\t\t\tsequences.set(record.id, 0);\n\t\t\tawait writeRecord(record);\n\t\t\treturn record;\n\t\t},\n\t\t/** Applies `change` to the deployment's record, stamping `updatedAt`, and writes it. */\n\t\tupdate: async (\n\t\t\tid: string,\n\t\t\tchange: (record: DeploymentRecord) => DeploymentRecord,\n\t\t) => {\n\t\t\tconst record = {\n\t\t\t\t...change(get(id)),\n\t\t\t\tupdatedAt: options.now().toISOString(),\n\t\t\t};\n\t\t\trecords.set(id, record);\n\t\t\temit(id, { kind: \"record\", record });\n\t\t\tawait writeRecord(record);\n\t\t\treturn record;\n\t\t},\n\t\t/** Appends a line to the deployment's log; subscribers hear it once it is on disk. */\n\t\tlog: (id: string, entry: Omit<DeploymentLogLine, \"seq\" | \"at\">) =>\n\t\t\tinTurn(id, async () => {\n\t\t\t\tconst last =\n\t\t\t\t\tsequences.get(id) ??\n\t\t\t\t\t(await readLines(id)).reduce(\n\t\t\t\t\t\t(highest, line) => Math.max(highest, line.seq),\n\t\t\t\t\t\t0,\n\t\t\t\t\t);\n\t\t\t\tconst line: DeploymentLogLine = {\n\t\t\t\t\tseq: last + 1,\n\t\t\t\t\tat: options.now().toISOString(),\n\t\t\t\t\t...entry,\n\t\t\t\t};\n\t\t\t\tsequences.set(id, line.seq);\n\t\t\t\tawait mkdir(recordDirectory(id), { recursive: true });\n\t\t\t\tawait appendJsonLine(logFile(id), line);\n\t\t\t\temit(id, { kind: \"log\", line });\n\t\t\t\treturn line;\n\t\t\t}),\n\t\t/** Waits until the deployment's changes so far are on disk and heard. */\n\t\tflush: async (id: string) => {\n\t\t\tawait writes.get(id);\n\t\t},\n\t\t/** The deployment's log lines after `seq` `after`. */\n\t\tlines: async (id: string, after: number) => {\n\t\t\tawait writes.get(id);\n\t\t\treturn (await readLines(id)).filter((line) => line.seq > after);\n\t\t},\n\t\tsubscribe: (id: string, listener: (event: DeploymentEvent) => void) => {\n\t\t\tconst subscribed = listeners.get(id) ?? new Set();\n\t\t\tsubscribed.add(listener);\n\t\t\tlisteners.set(id, subscribed);\n\t\t\treturn () => {\n\t\t\t\tsubscribed.delete(listener);\n\t\t\t};\n\t\t},\n\t\tremove: (id: string) =>\n\t\t\tinTurn(id, async () => {\n\t\t\t\trecords.delete(id);\n\t\t\t\tsequences.delete(id);\n\t\t\t\tawait rm(recordDirectory(id), { recursive: true, force: true });\n\t\t\t}),\n\t};\n};\nexport type DeploymentStore = Awaited<ReturnType<typeof openDeploymentStore>>;\n",
27
+ "import type { Release } from \"../protocol\";\nimport { pruneReleases, serverReleaseId } from \"../releases\";\nimport { activeDeployments, type DeploymentStore, isFinished } from \"./store\";\n\n/** Every deployment created within this long is kept. */\nexport const retentionMs = 14 * 24 * 60 * 60 * 1000;\n\n/**\n * Deletes the deployments created before the retention window, except the running one, the last\n * healthy one and any not yet finished, then every release that no kept deployment and not the\n * deployed release names. The deployed release's server may be an earlier release's.\n */\nexport const pruneDeployments = async (options: {\n\tstore: DeploymentStore;\n\treleases: string;\n\tdeployed: Release | null;\n\tnow: () => Date;\n}) => {\n\tconst { store } = options;\n\tconst records = store.list();\n\tconst { current, lastGood } = activeDeployments(records);\n\tconst cutoff = options.now().getTime() - retentionMs;\n\tconst expired = records.filter(\n\t\t(record) =>\n\t\t\tDate.parse(record.createdAt) < cutoff &&\n\t\t\trecord.id !== current &&\n\t\t\trecord.id !== lastGood &&\n\t\t\tisFinished(record),\n\t);\n\tfor (const record of expired) {\n\t\tawait store.remove(record.id);\n\t}\n\tconst kept = new Set(store.list().map((record) => record.release));\n\tif (options.deployed) {\n\t\tkept.add(options.deployed.id);\n\t\tif (options.deployed.server) {\n\t\t\tkept.add(serverReleaseId(options.deployed.server));\n\t\t}\n\t}\n\treturn {\n\t\tdeployments: expired.map((record) => record.id),\n\t\treleases: await pruneReleases(options.releases, kept),\n\t};\n};\n",
28
+ "import { workerScriptsDigest } from \"@tsplc/build\";\nimport { AgentError } from \"../errors\";\nimport {\n\ttype ClientIdentity,\n\ttype ClientRelease,\n\ttype Credentials,\n\ttype DeployOptions,\n\ttype Identity,\n\ttsplcVersion,\n\tversionMismatch,\n} from \"../protocol\";\nimport { controllerCredentials } from \"../secrets\";\nimport type { AgentState } from \"../state\";\nimport type { Submission } from \"./runner\";\n\n/**\n * Refuses a client of another tsPLC version, which compiles for scripts this agent doesn't run,\n * and returns what to warn the deployment about. A client from before version checks reports none\n * and is only warned, so it can still deploy.\n */\nexport const clientWarnings = async (clientTsplc: ClientRelease) => {\n\tif (clientTsplc.version === undefined) {\n\t\treturn [\n\t\t\t`the deploying tsPLC predates version checks, while this plant agent runs tsPLC ${tsplcVersion}; update the client to ${tsplcVersion}`,\n\t\t];\n\t}\n\tif (clientTsplc.version !== tsplcVersion) {\n\t\tthrow new AgentError(\n\t\t\tversionMismatch({\n\t\t\t\tagent: tsplcVersion,\n\t\t\t\tclient: clientTsplc.version,\n\t\t\t\tagentUpgrades: true,\n\t\t\t}),\n\t\t\t409,\n\t\t);\n\t}\n\tif (\n\t\tclientTsplc.scripts !== undefined &&\n\t\tclientTsplc.scripts !== (await workerScriptsDigest())\n\t) {\n\t\treturn [\n\t\t\t`the plant agent's CODESYS scripts differ from the deploying tsPLC's, though both are ${tsplcVersion}, so one is a local build. The deployment runs the agent's scripts: update the plant agent to run the client's`,\n\t\t];\n\t}\n\treturn [];\n};\n\n/** Who asked for a deployment: the identity behind the request, and the deploying machine's user and host. */\nexport const requester = (identity: Identity, client: ClientIdentity) => ({\n\tidentity: { login: identity.login, name: identity.name, via: identity.via },\n\tuser: client.user ?? null,\n\thost: client.host ?? null,\n});\n\n/** The deployment an upload's `settings` ask for. */\nexport const submissionFrom = (\n\tsettings: DeployOptions,\n\tidentity: Identity,\n\tclient: ClientIdentity,\n\twarnings: string[],\n): Submission => ({\n\tgit: settings.deployment?.git ?? null,\n\trequestedBy: requester(identity, client),\n\tmode: settings.deployment?.mode ?? \"apply\",\n\tdownload: settings.download,\n\tcredentials: settings.credentials,\n\tinitializeUser: settings.initializeUser,\n\twarnings,\n});\n\n/** Refuses what would fail anyway before a deployment starts: no controller selected, or no controller user. */\nexport const checkSubmission = async (\n\tstate: AgentState,\n\tcredentials: Credentials | null,\n) => {\n\tawait state.requireTarget();\n\tawait controllerCredentials(credentials);\n};\n",
29
+ "import { z } from \"zod\";\nimport {\n\tapproveSchema,\n\tclientIdentity,\n\tclientRelease,\n\ttype DeploymentEvent,\n\ttype DeploymentLogLine,\n\ttype DeploymentRecord,\n\ttype deploymentCreatedSchema,\n\ttype deploymentListSchema,\n\tdeploymentPagePath,\n\ttype deploymentSourceSchema,\n\tdeploymentsApiPath,\n\tredeploySchema,\n} from \"../protocol\";\nimport { type ReleaseStore, readDeployRequest } from \"../releases\";\nimport type { ApiRoute } from \"../routes\";\nimport type { DeploymentRunner } from \"./runner\";\nimport { isFinished } from \"./store\";\nimport { clientWarnings, requester, submissionFrom } from \"./submission\";\n\n/** Server-sent events stay open through proxies that close a silent connection. */\nconst heartbeatMs = 15_000;\n\n/** `?after=`, or the `Last-Event-ID` an `EventSource` reconnects with: the last log line it has. */\nconst afterSchema = z.coerce.number().int().nonnegative();\n\nconst after = (request: Request) =>\n\tafterSchema.parse(\n\t\tnew URL(request.url).searchParams.get(\"after\") ??\n\t\t\trequest.headers.get(\"last-event-id\") ??\n\t\t\t0,\n\t);\n\n/** An open event stream's progress. */\ninterface EventStreamState {\n\topen: boolean;\n\t/** The last log line sent. */\n\tsent: number;\n\t/** The log is being replayed; changes heard meanwhile wait in `held` until it has been. */\n\treplaying: boolean;\n\theld: DeploymentEvent[];\n\tstop: () => void;\n}\n\n/** A param the route's pattern names, which a matched request always has. */\nconst param = (params: Readonly<Record<string, string>>, name: string) => {\n\tconst value = params[name];\n\tif (value === undefined) {\n\t\tthrow new Error(`The route's pattern has no ${name}`);\n\t}\n\treturn value;\n};\n\n/**\n * The record, then its log after `from`, then each change until the deployment finishes, which\n * ends the stream with the finished record.\n */\nconst eventStream = (runner: DeploymentRunner, id: string, from: number) => {\n\tconst initial = runner.get(id);\n\tconst encoder = new TextEncoder();\n\tconst stream: EventStreamState = {\n\t\topen: true,\n\t\tsent: from,\n\t\treplaying: true,\n\t\theld: [],\n\t\tstop: () => {},\n\t};\n\treturn new Response(\n\t\tnew ReadableStream({\n\t\t\tstart: async (controller) => {\n\t\t\t\tconst write = (text: string) => {\n\t\t\t\t\tif (stream.open) {\n\t\t\t\t\t\tcontroller.enqueue(encoder.encode(text));\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t\tconst sendLine = (line: DeploymentLogLine) => {\n\t\t\t\t\tif (line.seq <= stream.sent) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tstream.sent = line.seq;\n\t\t\t\t\twrite(\n\t\t\t\t\t\t`id: ${line.seq}\\nevent: log\\ndata: ${JSON.stringify(line)}\\n\\n`,\n\t\t\t\t\t);\n\t\t\t\t};\n\t\t\t\tconst end = () => {\n\t\t\t\t\tif (stream.open) {\n\t\t\t\t\t\tstream.stop();\n\t\t\t\t\t\tcontroller.close();\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t\tconst sendRecord = (record: DeploymentRecord) =>\n\t\t\t\t\twrite(`event: record\\ndata: ${JSON.stringify(record)}\\n\\n`);\n\t\t\t\t/** Sends the lines still on their way to disk, then the finished record last, and ends. */\n\t\t\t\tconst finish = () =>\n\t\t\t\t\trunner.lines(id, stream.sent).then((lines) => {\n\t\t\t\t\t\tlines.forEach(sendLine);\n\t\t\t\t\t\tsendRecord(runner.get(id));\n\t\t\t\t\t\tend();\n\t\t\t\t\t}, end);\n\t\t\t\tconst deliver = (event: DeploymentEvent) => {\n\t\t\t\t\tif (event.kind === \"log\") {\n\t\t\t\t\t\tsendLine(event.line);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (isFinished(event.record)) {\n\t\t\t\t\t\tvoid finish();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tsendRecord(event.record);\n\t\t\t\t};\n\t\t\t\tconst unsubscribe = runner.subscribe(id, (event) => {\n\t\t\t\t\tif (stream.replaying) {\n\t\t\t\t\t\tstream.held.push(event);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tdeliver(event);\n\t\t\t\t});\n\t\t\t\tconst heartbeat = setInterval(\n\t\t\t\t\t() => write(\": heartbeat\\n\\n\"),\n\t\t\t\t\theartbeatMs,\n\t\t\t\t);\n\t\t\t\tstream.stop = () => {\n\t\t\t\t\tstream.open = false;\n\t\t\t\t\tclearInterval(heartbeat);\n\t\t\t\t\tunsubscribe();\n\t\t\t\t};\n\t\t\t\t// A finished deployment's record comes once, after its log.\n\t\t\t\tif (!isFinished(initial)) {\n\t\t\t\t\tsendRecord(initial);\n\t\t\t\t}\n\t\t\t\t(await runner.lines(id, from)).forEach(sendLine);\n\t\t\t\tstream.replaying = false;\n\t\t\t\tstream.held.splice(0).forEach(deliver);\n\t\t\t\tif (isFinished(runner.get(id))) {\n\t\t\t\t\tvoid finish();\n\t\t\t\t}\n\t\t\t},\n\t\t\tcancel: () => stream.stop(),\n\t\t}),\n\t\t{\n\t\t\theaders: {\n\t\t\t\t\"Content-Type\": \"text/event-stream\",\n\t\t\t\t\"Cache-Control\": \"no-cache\",\n\t\t\t},\n\t\t},\n\t);\n};\n\n/** The deployments API the dashboard and `tsplc deploy` use: `/api/deployments` and below. */\nexport const createDeploymentRoutes = (context: {\n\trunner: DeploymentRunner;\n\treleases: ReleaseStore;\n}): ApiRoute[] => {\n\tconst { runner } = context;\n\tconst created = (request: Request, record: DeploymentRecord) =>\n\t\tResponse.json(\n\t\t\t{\n\t\t\t\tid: record.id,\n\t\t\t\turl: `${new URL(request.url).origin}${deploymentPagePath(record.id)}`,\n\t\t\t} satisfies z.infer<typeof deploymentCreatedSchema>,\n\t\t\t{ status: 202 },\n\t\t);\n\tconst id = (params: Readonly<Record<string, string>>) => param(params, \"id\");\n\treturn [\n\t\t{\n\t\t\tmethod: \"POST\",\n\t\t\tpattern: deploymentsApiPath,\n\t\t\trole: \"deployer\",\n\t\t\thandle: async (request, { identity }) => {\n\t\t\t\tconst warnings = await clientWarnings(clientRelease(request));\n\t\t\t\tconst { settings, upload } = await readDeployRequest(\n\t\t\t\t\tcontext.releases,\n\t\t\t\t\trequest,\n\t\t\t\t);\n\t\t\t\tconst record = await runner.submit(\n\t\t\t\t\tupload,\n\t\t\t\t\tsubmissionFrom(settings, identity, clientIdentity(request), warnings),\n\t\t\t\t);\n\t\t\t\treturn created(request, record);\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tmethod: \"GET\",\n\t\t\tpattern: deploymentsApiPath,\n\t\t\trole: \"viewer\",\n\t\t\thandle: async () =>\n\t\t\t\tResponse.json(\n\t\t\t\t\trunner.list() satisfies z.infer<typeof deploymentListSchema>,\n\t\t\t\t),\n\t\t},\n\t\t{\n\t\t\tmethod: \"GET\",\n\t\t\tpattern: `${deploymentsApiPath}/:id`,\n\t\t\trole: \"viewer\",\n\t\t\thandle: async (_request, { params }) =>\n\t\t\t\tResponse.json(runner.get(id(params))),\n\t\t},\n\t\t{\n\t\t\tmethod: \"GET\",\n\t\t\tpattern: `${deploymentsApiPath}/:id/logs`,\n\t\t\trole: \"viewer\",\n\t\t\thandle: async (request, { params }) =>\n\t\t\t\tResponse.json({\n\t\t\t\t\tlines: await runner.lines(id(params), after(request)),\n\t\t\t\t}),\n\t\t},\n\t\t{\n\t\t\tmethod: \"GET\",\n\t\t\tpattern: `${deploymentsApiPath}/:id/events`,\n\t\t\trole: \"viewer\",\n\t\t\thandle: async (request, { params }) =>\n\t\t\t\teventStream(runner, id(params), after(request)),\n\t\t},\n\t\t{\n\t\t\tmethod: \"POST\",\n\t\t\tpattern: `${deploymentsApiPath}/:id/approve`,\n\t\t\trole: \"deployer\",\n\t\t\thandle: async (request, { identity, params }) => {\n\t\t\t\tconst { download } = approveSchema.parse(await request.json());\n\t\t\t\treturn Response.json(\n\t\t\t\t\tawait runner.approve(id(params), { download }, identity.name),\n\t\t\t\t);\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tmethod: \"POST\",\n\t\t\tpattern: `${deploymentsApiPath}/:id/cancel`,\n\t\t\trole: \"deployer\",\n\t\t\thandle: async (_request, { identity, params }) =>\n\t\t\t\tResponse.json(await runner.cancel(id(params), identity.name)),\n\t\t},\n\t\t{\n\t\t\tmethod: \"POST\",\n\t\t\tpattern: `${deploymentsApiPath}/:id/redeploy`,\n\t\t\trole: \"deployer\",\n\t\t\thandle: async (request, { identity, params }) => {\n\t\t\t\tconst { mode } = redeploySchema.parse(await request.json());\n\t\t\t\treturn created(\n\t\t\t\t\trequest,\n\t\t\t\t\tawait runner.redeploy(\n\t\t\t\t\t\tid(params),\n\t\t\t\t\t\tmode,\n\t\t\t\t\t\trequester(identity, clientIdentity(request)),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tmethod: \"POST\",\n\t\t\tpattern: `${deploymentsApiPath}/:id/rollback`,\n\t\t\trole: \"deployer\",\n\t\t\thandle: async (request, { identity, params }) =>\n\t\t\t\tcreated(\n\t\t\t\t\trequest,\n\t\t\t\t\tawait runner.rollback(\n\t\t\t\t\t\tid(params),\n\t\t\t\t\t\trequester(identity, clientIdentity(request)),\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t},\n\t\t{\n\t\t\tmethod: \"GET\",\n\t\t\tpattern: `${deploymentsApiPath}/:id/source`,\n\t\t\trole: \"viewer\",\n\t\t\thandle: async (_request, { params }) =>\n\t\t\t\tResponse.json({\n\t\t\t\t\tfiles: await runner.source(id(params)),\n\t\t\t\t} satisfies z.infer<typeof deploymentSourceSchema>),\n\t\t},\n\t\t{\n\t\t\tmethod: \"GET\",\n\t\t\tpattern: `${deploymentsApiPath}/:id/source/*`,\n\t\t\trole: \"viewer\",\n\t\t\thandle: async (_request, { params }) =>\n\t\t\t\tnew Response(await runner.sourceFile(id(params), param(params, \"*\")), {\n\t\t\t\t\theaders: { \"Content-Type\": \"text/plain; charset=utf-8\" },\n\t\t\t\t}),\n\t\t},\n\t];\n};\n",
30
+ "import { Resolver } from \"node:dns/promises\";\nimport { createConnection } from \"node:net\";\nimport { networkInterfaces as osInterfaces } from \"node:os\";\nimport type { DiscoveredController, NetworkInterface } from \"./protocol\";\n\n/** A /22 is 1022 hosts: a sweep at 128 probes a time takes a few seconds. */\nconst largestPrefix = 22;\nconst probeTimeoutMs = 500;\nconst probesAtOnce = 128;\n\n/** The machine's IPv4 networks, which `discoverControllers` scans one at a time. */\nexport const networkInterfaces = (): NetworkInterface[] =>\n\tObject.entries(osInterfaces()).flatMap(([name, addresses]) =>\n\t\t(addresses ?? [])\n\t\t\t.filter((address) => address.family === \"IPv4\" && !address.internal)\n\t\t\t.map((address) => ({\n\t\t\t\tname,\n\t\t\t\taddress: address.address,\n\t\t\t\tprefixLength: address.netmask\n\t\t\t\t\t.split(\".\")\n\t\t\t\t\t.reduce(\n\t\t\t\t\t\t(bits, octet) =>\n\t\t\t\t\t\t\tbits + Number(octet).toString(2).replaceAll(\"0\", \"\").length,\n\t\t\t\t\t\t0,\n\t\t\t\t\t),\n\t\t\t})),\n\t);\n\nconst toNumber = (address: string) =>\n\taddress.split(\".\").reduce((value, octet) => value * 256 + Number(octet), 0);\nconst toAddress = (value: number) =>\n\t[24, 16, 8, 0].map((shift) => Math.floor(value / 2 ** shift) % 256).join(\".\");\n\n/** Every host address on the interface's subnet, except the interface's own. */\nexport const subnetHosts = ({ address, prefixLength }: NetworkInterface) => {\n\tif (prefixLength < largestPrefix) {\n\t\tthrow new Error(\n\t\t\t`The /${prefixLength} network is too large to scan; the limit is /${largestPrefix}.`,\n\t\t);\n\t}\n\tconst size = 2 ** (32 - prefixLength);\n\tconst network = toNumber(address) - (toNumber(address) % size);\n\t// /31 and /32 networks have no network or broadcast address to skip.\n\tconst hosts =\n\t\tsize <= 2\n\t\t\t? Array.from({ length: size }, (_, index) => network + index)\n\t\t\t: Array.from({ length: size - 2 }, (_, index) => network + index + 1);\n\treturn hosts.map(toAddress).filter((host) => host !== address);\n};\n\nconst accepts = (host: string, port: number) =>\n\tnew Promise<boolean>((resolve) => {\n\t\tconst socket = createConnection({ host, port });\n\t\t// A silent host leaves the connection pending for the OS's own timeout, which is minutes.\n\t\tconst timer = setTimeout(() => finish(false), probeTimeoutMs);\n\t\tconst finish = (open: boolean) => {\n\t\t\tclearTimeout(timer);\n\t\t\tsocket.destroy();\n\t\t\tresolve(open);\n\t\t};\n\t\tsocket.once(\"connect\", () => finish(true));\n\t\tsocket.once(\"error\", () => finish(false));\n\t});\n\nconst resolver = new Resolver({ timeout: 1000, tries: 1 });\nconst hostname = (address: string) =>\n\tresolver.reverse(address).then(\n\t\t(names) => names[0] ?? null,\n\t\t// Plant networks rarely have reverse DNS; the address alone identifies the controller.\n\t\t() => null,\n\t);\n\n/** Finds the hosts on `network` that accept connections on `port`, such as CODESYS runtimes'. */\nexport const discoverControllers = async (\n\tnetwork: NetworkInterface,\n\tport: number,\n): Promise<DiscoveredController[]> => {\n\tconst hosts = subnetHosts(network);\n\tconst found: DiscoveredController[] = [];\n\tfor (let start = 0; start < hosts.length; start += probesAtOnce) {\n\t\tconst batch = hosts.slice(start, start + probesAtOnce);\n\t\tconst open = await Promise.all(batch.map((host) => accepts(host, port)));\n\t\tfor (const [index, host] of batch.entries()) {\n\t\t\tif (open[index]) {\n\t\t\t\tfound.push({ address: host, port, hostname: await hostname(host) });\n\t\t\t}\n\t\t}\n\t}\n\treturn found;\n};\n",
31
+ "import type { PlantVariables } from \"@tsplc/config\";\nimport { envName } from \"@tsplc/config/build\";\nimport { z } from \"zod\";\nimport { type AuditLog, authorOf } from \"./audit\";\nimport { AgentError } from \"./errors\";\nimport {\n\ttype EnvironmentEntry,\n\ttype EnvironmentListing,\n\tenvironmentValueSchema,\n\ttype Identity,\n} from \"./protocol\";\nimport { loadRelease } from \"./releases\";\nimport type { ApiRoute } from \"./routes\";\nimport { environmentService } from \"./secrets\";\nimport { type AgentState, readJsonFile, writeJsonFile } from \"./state\";\n\nconst storedNamesSchema = z.record(z.string(), z.array(envName));\n\nconst storedVariablesSchema = z.record(envName, z.string());\n\n/**\n * The plant PC's variables: plain ones, shown and edited here, and secrets, set and replaced but\n * never read back; and what the running release was built with. `tsplc deploy` builds the PLC's\n * program with the plain values and carries them to the server, and the agent fills the secrets\n * in from the Bun.secrets service the release names, so a change reaches both with the next\n * deployment.\n */\nexport const createEnvironment = (context: {\n\tstate: AgentState;\n\taudit: AuditLog;\n}) => {\n\tconst { state, audit } = context;\n\tconst { paths } = state;\n\n\tconst storedNames = async () =>\n\t\t(await readJsonFile(paths.environment, storedNamesSchema)) ?? {};\n\tconst writeStoredNames = async (\n\t\tservice: string,\n\t\tupdate: (names: string[]) => string[],\n\t) => {\n\t\tconst stored = await storedNames();\n\t\twriteJsonFile(paths.environment, {\n\t\t\t...stored,\n\t\t\t[service]: update(stored[service] ?? []),\n\t\t});\n\t};\n\tconst storedVariables = async () =>\n\t\t(await readJsonFile(paths.variables, storedVariablesSchema)) ?? {};\n\n\tconst deployedManifest = async () => {\n\t\tconst release = await state.release();\n\t\treturn release\n\t\t\t? (await loadRelease(state.paths.releases, release.id)).manifest\n\t\t\t: undefined;\n\t};\n\n\t/** The service the deployed release keeps its secrets in, and the names it reads. */\n\tconst declared = async () =>\n\t\t(await deployedManifest())?.secrets ?? {\n\t\t\tservice: environmentService,\n\t\t\tnames: [],\n\t\t};\n\n\tconst isSet = async (service: string, name: string) =>\n\t\t(await Bun.secrets.get({ service, name })) !== null;\n\n\tconst entries = async (): Promise<EnvironmentEntry[]> => {\n\t\tconst { service, names } = await declared();\n\t\tconst stored = ((await storedNames())[service] ?? []).filter(\n\t\t\t(name) => !names.includes(name),\n\t\t);\n\t\tconst undeclared = await Promise.all(\n\t\t\tstored.map(async (name) => ({\n\t\t\t\tname,\n\t\t\t\tdeclared: false,\n\t\t\t\tset: await isSet(service, name),\n\t\t\t})),\n\t\t);\n\t\treturn [\n\t\t\t...(await Promise.all(\n\t\t\t\tnames.map(async (name) => ({\n\t\t\t\t\tname,\n\t\t\t\t\tdeclared: true,\n\t\t\t\t\tset: await isSet(service, name),\n\t\t\t\t})),\n\t\t\t)),\n\t\t\t// A name deleted outside the dashboard is gone.\n\t\t\t...undeclared.filter(({ set }) => set),\n\t\t];\n\t};\n\n\tconst listing = async (): Promise<EnvironmentListing> => ({\n\t\tvalues: (await deployedManifest())?.values ?? {},\n\t\tvariables: await storedVariables(),\n\t\tsecrets: await entries(),\n\t});\n\n\t/** What `tsplc deploy` builds with: the plain values, and the secrets set in `service`. */\n\tconst forRelease = async (service: string): Promise<PlantVariables> => {\n\t\tconst held = (await storedNames())[service] ?? [];\n\t\tconst set = await Promise.all(\n\t\t\theld.map(async (name) => ((await isSet(service, name)) ? [name] : [])),\n\t\t);\n\t\treturn { service, values: await storedVariables(), secrets: set.flat() };\n\t};\n\n\t/** Records a change by the variable's name, with a plain one's value; never a secret's. */\n\tconst record = (\n\t\tidentity: Identity,\n\t\tcommand: string,\n\t\tchange: {\n\t\t\tvalues: Record<string, string>;\n\t\t\tprevious: Record<string, string> | null;\n\t\t},\n\t) =>\n\t\taudit.record({\n\t\t\tby: authorOf(identity),\n\t\t\tcommand,\n\t\t\tvalues: change.values,\n\t\t\tprevious: change.previous,\n\t\t\terror: null,\n\t\t});\n\t/** A secret's change: its name alone. */\n\tconst nameOnly = { values: {}, previous: null };\n\n\tconst withoutVariable = async (name: string) => {\n\t\tconst { [name]: removed, ...rest } = await storedVariables();\n\t\tif (removed !== undefined) {\n\t\t\twriteJsonFile(paths.variables, rest);\n\t\t}\n\t\treturn removed;\n\t};\n\n\tconst routes: ApiRoute[] = [\n\t\t{\n\t\t\tmethod: \"GET\",\n\t\t\tpattern: \"/api/environment\",\n\t\t\trole: \"viewer\",\n\t\t\thandle: async () => Response.json(await listing()),\n\t\t},\n\t\t{\n\t\t\tmethod: \"GET\",\n\t\t\tpattern: \"/api/environment/release\",\n\t\t\trole: \"deployer\",\n\t\t\thandle: async (request) =>\n\t\t\t\tResponse.json(\n\t\t\t\t\tawait forRelease(\n\t\t\t\t\t\tnew URL(request.url).searchParams.get(\"service\") ||\n\t\t\t\t\t\t\tenvironmentService,\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t},\n\t\t{\n\t\t\tmethod: \"PUT\",\n\t\t\tpattern: \"/api/environment/:name\",\n\t\t\trole: \"admin\",\n\t\t\thandle: async (request, { identity, params }) => {\n\t\t\t\tconst name = envName.parse(params.name);\n\t\t\t\tconst change = environmentValueSchema.parse(await request.json());\n\t\t\t\tconst { service } = await declared();\n\t\t\t\tif (change.secret) {\n\t\t\t\t\tawait Bun.secrets.set({ service, name, value: change.value });\n\t\t\t\t\tawait writeStoredNames(service, (stored) => [\n\t\t\t\t\t\t...stored.filter((other) => other !== name),\n\t\t\t\t\t\tname,\n\t\t\t\t\t]);\n\t\t\t\t\tawait withoutVariable(name);\n\t\t\t\t\tawait record(identity, `environment set ${name}`, nameOnly);\n\t\t\t\t\treturn Response.json(await listing());\n\t\t\t\t}\n\t\t\t\tconst variables = await storedVariables();\n\t\t\t\tconst previous = variables[name];\n\t\t\t\twriteJsonFile(paths.variables, { ...variables, [name]: change.value });\n\t\t\t\t// A name is a plain variable or a secret, never both.\n\t\t\t\tif (await Bun.secrets.delete({ service, name })) {\n\t\t\t\t\tawait writeStoredNames(service, (stored) =>\n\t\t\t\t\t\tstored.filter((other) => other !== name),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tawait record(identity, `environment set ${name}`, {\n\t\t\t\t\tvalues: { [name]: change.value },\n\t\t\t\t\tprevious: previous === undefined ? null : { [name]: previous },\n\t\t\t\t});\n\t\t\t\treturn Response.json(await listing());\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tmethod: \"DELETE\",\n\t\t\tpattern: \"/api/environment/:name\",\n\t\t\trole: \"admin\",\n\t\t\thandle: async (_request, { identity, params }) => {\n\t\t\t\tconst name = envName.parse(params.name);\n\t\t\t\tconst removed = await withoutVariable(name);\n\t\t\t\tif (removed !== undefined) {\n\t\t\t\t\tawait record(identity, `environment delete ${name}`, {\n\t\t\t\t\t\tvalues: {},\n\t\t\t\t\t\tprevious: { [name]: removed },\n\t\t\t\t\t});\n\t\t\t\t\treturn Response.json(await listing());\n\t\t\t\t}\n\t\t\t\tconst { service } = await declared();\n\t\t\t\tif (!(await Bun.secrets.delete({ service, name }))) {\n\t\t\t\t\tthrow new AgentError(`${name} isn't set`, 404);\n\t\t\t\t}\n\t\t\t\tawait writeStoredNames(service, (stored) =>\n\t\t\t\t\tstored.filter((other) => other !== name),\n\t\t\t\t);\n\t\t\t\tawait record(identity, `environment delete ${name}`, nameOnly);\n\t\t\t\treturn Response.json(await listing());\n\t\t\t},\n\t\t},\n\t];\n\treturn { routes };\n};\n",
32
+ "import { setTimeout as delay } from \"node:timers/promises\";\nimport {\n\ttype ControllerLogin,\n\tfailureReason,\n\tfindControllerLogin,\n\ttype LoginCommand,\n\topenControllerLogin,\n\ttype ResetKind,\n\tsettleWarmController,\n} from \"@tsplc/build\";\nimport { LoginUnavailable, noLogin } from \"@tsplc/debug\";\nimport type { AuditLog } from \"./audit\";\nimport {\n\ttype CodesysSettings,\n\tcontrollerConfig,\n\tcredentialEnvironment,\n\tdeployContainer,\n\tensureGateway,\n\tloginContainer,\n\trequireBuilder,\n} from \"./codesys\";\nimport { AgentError, errorMessage } from \"./errors\";\nimport type { Operations } from \"./operations\";\nimport type { AgentStatus, ClientIdentity, Credentials } from \"./protocol\";\nimport { controllerCredentials } from \"./secrets\";\nimport type { AgentState } from \"./state\";\n\n/** A login's state comes back within a second; one that takes this long waits on a hung worker. */\nconst loginStateTimeout = 30_000;\nconst stoppedAnswering = { error: \"The login stopped answering\" };\n\n/** How an audited login command reads in the log, or nothing for commands that only read. */\nconst auditOf = (command: LoginCommand) => {\n\tswitch (command.command) {\n\t\tcase \"write\":\n\t\tcase \"force\":\n\t\t\treturn { command: command.command, values: command.values };\n\t\tcase \"unforce\":\n\t\t\treturn {\n\t\t\t\tcommand: command.restore ? \"unforce --restore\" : \"unforce\",\n\t\t\t\tvalues: Object.fromEntries(\n\t\t\t\t\tcommand.expressions.map((expression) => [expression, \"\"]),\n\t\t\t\t),\n\t\t\t};\n\t\tcase \"start\":\n\t\tcase \"stop\":\n\t\t\treturn { command: command.command, values: {} };\n\t\tcase \"reset\":\n\t\t\treturn { command: `reset ${command.kind.toLowerCase()}`, values: {} };\n\t\tcase \"state\":\n\t\tcase \"read\":\n\t\t\treturn undefined;\n\t}\n};\n\n/**\n * The agent's engineering login to the controller, which outlives the agent in its own\n * container. Its commands, the debugger's reads among them, run one at a time.\n */\nexport const createLogin = (context: {\n\tstate: AgentState;\n\toperations: Operations;\n\tcodesys: CodesysSettings;\n\taudit: AuditLog;\n\tlog: (message: string) => void;\n}) => {\n\tconst { state, operations } = context;\n\tlet generation = 0;\n\tlet commands: Promise<unknown> = Promise.resolve();\n\n\tconst enqueue = <Result>(run: () => Promise<Result>) => {\n\t\tconst queuedIn = generation;\n\t\tconst sent = commands.then(() => {\n\t\t\tif (queuedIn !== generation) {\n\t\t\t\tthrow new AgentError(\"The login was closed\", 409);\n\t\t\t}\n\t\t\treturn run();\n\t\t});\n\t\tcommands = sent.catch(() => undefined);\n\t\treturn sent;\n\t};\n\tconst send = (login: ControllerLogin, command: LoginCommand) =>\n\t\tenqueue(() => login.send(command));\n\n\tconst openLogin = async () => {\n\t\tconst lookedUpIn = generation;\n\t\tconst login = await findControllerLogin(loginContainer);\n\t\tif (lookedUpIn !== generation) {\n\t\t\tthrow new AgentError(\"The login was closed\", 409);\n\t\t}\n\t\tif (!login) {\n\t\t\tthrow new AgentError(\"No login is open: tsplc login\", 409);\n\t\t}\n\t\treturn login;\n\t};\n\t/** The open login, for a command that runs while no operation does. */\n\tconst requireLogin = async () => {\n\t\toperations.requireIdle();\n\t\tconst login = await openLogin();\n\t\toperations.requireIdle();\n\t\treturn login;\n\t};\n\n\t/** Whether a login's container runs, open or opening. */\n\tconst isOpen = async () =>\n\t\t(await findControllerLogin(loginContainer)) !== undefined;\n\n\treturn {\n\t\t/** What the debugger reads through: the open login, which it never opens itself. */\n\t\tread: async ([first, ...rest]: string[]) => {\n\t\t\tconst busy = operations.busy();\n\t\t\tif (busy === \"a login\") {\n\t\t\t\tthrow new LoginUnavailable(\"The engineering login is opening\", {\n\t\t\t\t\tstate: \"connecting\",\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (busy) {\n\t\t\t\tthrow new LoginUnavailable(`Live values pause during ${busy}`);\n\t\t\t}\n\t\t\tconst login = await findControllerLogin(loginContainer);\n\t\t\tif (!login) {\n\t\t\t\tthrow new LoginUnavailable(noLogin);\n\t\t\t}\n\t\t\tif (!first) {\n\t\t\t\treturn {};\n\t\t\t}\n\t\t\tconst result = await send(login, {\n\t\t\t\tcommand: \"read\",\n\t\t\t\texpressions: [first, ...rest],\n\t\t\t});\n\t\t\tif (!(\"values\" in result)) {\n\t\t\t\tthrow new Error(\"The login answered a read without values\");\n\t\t\t}\n\t\t\treturn result.values;\n\t\t},\n\n\t\topen: async (sent: Credentials | null) => {\n\t\t\toperations.requireIdle();\n\t\t\tawait requireBuilder();\n\t\t\tconst credentials = await controllerCredentials(sent);\n\t\t\tcontext.log(\n\t\t\t\t`Opening a login with the ${sent ? \"provided\" : \"stored\"} controller user`,\n\t\t\t);\n\t\t\tconst config = controllerConfig(\n\t\t\t\tawait state.requireRelease(),\n\t\t\t\tawait state.requireTarget(),\n\t\t\t\tstate.paths.controller,\n\t\t\t\tcontext.codesys,\n\t\t\t);\n\t\t\treturn operations.stream(\"a login\", async (emit) => {\n\t\t\t\tif (await isOpen()) {\n\t\t\t\t\tthrow new AgentError(\"A login is already open\", 409);\n\t\t\t\t}\n\t\t\t\t// The login opens the committed download, which the last deployment may still be saving.\n\t\t\t\tawait settleWarmController(config, deployContainer);\n\t\t\t\temit({\n\t\t\t\t\tkind: \"progress\",\n\t\t\t\t\tmessage: \"Logging in; CODESYS takes minutes to start\",\n\t\t\t\t});\n\t\t\t\tawait ensureGateway();\n\t\t\t\tconst login = await openControllerLogin(config, loginContainer, {\n\t\t\t\t\tenvironment: credentialEnvironment(credentials),\n\t\t\t\t});\n\t\t\t\treturn send(login, { command: \"state\" });\n\t\t\t});\n\t\t},\n\n\t\t/** Runs a login command; one that changes the controller goes to the audit log, with the values it replaces. */\n\t\tcommand: async (command: LoginCommand, client: ClientIdentity) => {\n\t\t\tconst login = await requireLogin();\n\t\t\tconst change = auditOf(command);\n\t\t\tif (!change) {\n\t\t\t\treturn send(login, command);\n\t\t\t}\n\t\t\treturn enqueue(async () => {\n\t\t\t\tconst [first, ...rest] = Object.keys(change.values);\n\t\t\t\t// Without the old values the command is still worth running and recording.\n\t\t\t\tconst previous = first\n\t\t\t\t\t? await login\n\t\t\t\t\t\t\t.send({ command: \"read\", expressions: [first, ...rest] })\n\t\t\t\t\t\t\t.then((result) =>\n\t\t\t\t\t\t\t\t\"values\" in result ? result.values : undefined,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.catch(() => undefined)\n\t\t\t\t\t: undefined;\n\t\t\t\tconst audit = async (error: string | null) =>\n\t\t\t\t\tcontext.audit.record({\n\t\t\t\t\t\tby: { ...client, release: (await state.release())?.id },\n\t\t\t\t\t\t...change,\n\t\t\t\t\t\tprevious: previous ?? null,\n\t\t\t\t\t\terror,\n\t\t\t\t\t});\n\t\t\t\ttry {\n\t\t\t\t\tconst result = await login.send(command);\n\t\t\t\t\tawait audit(null);\n\t\t\t\t\treturn result;\n\t\t\t\t} catch (error) {\n\t\t\t\t\tawait audit(errorMessage(error));\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\n\t\t/**\n\t\t * Resets the application through the open login and starts it again, as `tsplc reset` then\n\t\t * `tsplc start` do, for a caller that holds the agent's one operation. Returns the state it\n\t\t * runs in.\n\t\t */\n\t\trestart: async (reset: ResetKind) => {\n\t\t\tconst login = await openLogin();\n\t\t\treturn enqueue(async () => {\n\t\t\t\tawait login.send({ command: \"reset\", kind: reset });\n\t\t\t\tconst started = await login.send({ command: \"start\" });\n\t\t\t\tif (!(\"state\" in started)) {\n\t\t\t\t\tthrow new Error(\"The login answered a start without the state\");\n\t\t\t\t}\n\t\t\t\treturn { state: started.state };\n\t\t\t});\n\t\t},\n\n\t\tisOpen,\n\n\t\t/**\n\t\t * The open login's state. A login that lost the controller, or whose worker died or hangs, is\n\t\t * reported as failed, so the CLI can log it out and open a new one.\n\t\t */\n\t\tstatus: async (): Promise<AgentStatus[\"login\"]> => {\n\t\t\tconst login = await findControllerLogin(loginContainer);\n\t\t\tif (!login) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\t// A login still opening has its container but doesn't answer yet.\n\t\t\tif (!(await login.ready())) {\n\t\t\t\treturn operations.busy() === \"a login\" ? null : stoppedAnswering;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst loginState = await Promise.race([\n\t\t\t\t\tsend(login, { command: \"state\" }),\n\t\t\t\t\tdelay(loginStateTimeout, null),\n\t\t\t\t]);\n\t\t\t\tif (!loginState) {\n\t\t\t\t\treturn stoppedAnswering;\n\t\t\t\t}\n\t\t\t\treturn \"state\" in loginState ? loginState : null;\n\t\t\t} catch (error) {\n\t\t\t\treturn { error: failureReason(error) };\n\t\t\t}\n\t\t},\n\n\t\t/** Logs out, cancelling queued commands; a replacement login starts with an empty queue. */\n\t\tlogout: async () => {\n\t\t\tconst login = await requireLogin();\n\t\t\treturn operations.exclusive(\"a logout\", async () => {\n\t\t\t\tgeneration++;\n\t\t\t\tconst failure = await login.close();\n\t\t\t\tcommands = Promise.resolve();\n\t\t\t\tif (failure) {\n\t\t\t\t\tcontext.log(\n\t\t\t\t\t\t`The login couldn't log out (${failure}); its container was removed`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\treturn failure ? { failure } : {};\n\t\t\t});\n\t\t},\n\t};\n};\nexport type Login = ReturnType<typeof createLogin>;\n",
33
+ "import { type ResetKind, resetLabel } from \"@tsplc/build\";\nimport {\n\tcontrollerRestartPath,\n\ttype controllerRestartReplySchema,\n\tcontrollerRestartSchema,\n} from \"@tsplc/server/plant-agent\";\nimport type { z } from \"zod\";\nimport { type AuditLog, authorOf } from \"./audit\";\nimport { AgentError, errorMessage } from \"./errors\";\nimport type { Operations } from \"./operations\";\nimport type { Identity } from \"./protocol\";\nimport type { ApiRoute } from \"./routes\";\nimport type { ServerSupervisor } from \"./server-process\";\n\n/**\n * Restarting the controller's application, for the dashboard, `tsplc restart` and the deployed\n * server, and restarting the line's server, for the dashboard. Each restart is audited.\n */\nexport const createRestartRoutes = (context: {\n\t/** Resets the controller's application and starts it again, as the agent's one operation. */\n\trestartController: (\n\t\treset: ResetKind,\n\t) => Promise<z.infer<typeof controllerRestartReplySchema>>;\n\tserver: ServerSupervisor;\n\toperations: Operations;\n\taudit: AuditLog;\n\tlog: (message: string) => void;\n}): ApiRoute[] => {\n\tconst audited = async <Result>(\n\t\tidentity: Identity,\n\t\trestart: { command: string; action: string },\n\t\trun: () => Promise<Result>,\n\t) => {\n\t\tconst outcome = await run().then(\n\t\t\t(result): { result: Result } | { failure: unknown } => ({ result }),\n\t\t\t(failure: unknown) => ({ failure }),\n\t\t);\n\t\t// Refused before it began, such as while another operation runs: nothing happened to record.\n\t\tif (\"failure\" in outcome && outcome.failure instanceof AgentError) {\n\t\t\tthrow outcome.failure;\n\t\t}\n\t\tawait context.audit.record({\n\t\t\tby: authorOf(identity),\n\t\t\tcommand: restart.command,\n\t\t\tvalues: {},\n\t\t\tprevious: null,\n\t\t\terror: \"failure\" in outcome ? errorMessage(outcome.failure) : null,\n\t\t});\n\t\tif (\"result\" in outcome) {\n\t\t\treturn outcome.result;\n\t\t}\n\t\tcontext.log(`${restart.action} failed: ${errorMessage(outcome.failure)}`);\n\t\tthrow new AgentError(errorMessage(outcome.failure), 500);\n\t};\n\n\treturn [\n\t\t{\n\t\t\tmethod: \"POST\",\n\t\t\tpattern: controllerRestartPath,\n\t\t\trole: \"deployer\",\n\t\t\thandle: async (request, { identity }) => {\n\t\t\t\tconst { reset } = controllerRestartSchema.parse(await request.json());\n\t\t\t\treturn Response.json(\n\t\t\t\t\tawait audited(\n\t\t\t\t\t\tidentity,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcommand: reset === \"warm\" ? \"restart\" : \"restart --cold\",\n\t\t\t\t\t\t\taction: \"Restarting the controller\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\t() => context.restartController(resetLabel(reset)),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tmethod: \"POST\",\n\t\t\tpattern: \"/api/server/restart\",\n\t\t\trole: \"deployer\",\n\t\t\thandle: async (_request, { identity }) => {\n\t\t\t\tconst running = context.server.status();\n\t\t\t\tif (!running) {\n\t\t\t\t\tthrow new AgentError(\"The deployed release runs no server\", 409);\n\t\t\t\t}\n\t\t\t\tawait audited(\n\t\t\t\t\tidentity,\n\t\t\t\t\t{ command: \"server restart\", action: \"Restarting the server\" },\n\t\t\t\t\t() =>\n\t\t\t\t\t\tcontext.operations.exclusive(\"a server restart\", () =>\n\t\t\t\t\t\t\tcontext.server.replace(running.executable),\n\t\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\treturn Response.json(context.server.status());\n\t\t\t},\n\t\t},\n\t];\n};\n",
34
+ "import { z } from \"zod\";\nimport { AgentError, errorMessage } from \"./errors\";\nimport { allows, type Identity, type Role } from \"./protocol\";\n\n/** One `/api` route: who may call it, and what answers it. */\nexport interface ApiRoute {\n\tmethod: \"GET\" | \"POST\" | \"PUT\" | \"DELETE\";\n\t/**\n\t * A path with `:name` segments, such as `/api/deployments/:id`. A last segment `*` matches the\n\t * rest of the path, one segment or more, as param `*`.\n\t */\n\tpattern: string;\n\trole: Role;\n\thandle: (\n\t\trequest: Request,\n\t\tcontext: { identity: Identity; params: Readonly<Record<string, string>> },\n\t) => Promise<Response>;\n}\n\n/** The route `method` and `pathname` name, with the values of its `:name` segments. */\nconst matchRoute = (\n\troutes: readonly ApiRoute[],\n\tmethod: string,\n\tpathname: string,\n) => {\n\tconst parts = pathname.split(\"/\");\n\tfor (const route of routes) {\n\t\tconst pattern = route.pattern.split(\"/\");\n\t\tconst rest = pattern.at(-1) === \"*\";\n\t\tif (\n\t\t\troute.method !== method ||\n\t\t\t(rest ? parts.length < pattern.length : pattern.length !== parts.length)\n\t\t) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst params: Record<string, string> = {};\n\t\tconst matched = pattern.every((segment, index) => {\n\t\t\tconst part = parts[index] ?? \"\";\n\t\t\tif (rest && index === pattern.length - 1) {\n\t\t\t\tparams[\"*\"] = parts.slice(index).map(decodeURIComponent).join(\"/\");\n\t\t\t\treturn part !== \"\";\n\t\t\t}\n\t\t\tif (segment.startsWith(\":\")) {\n\t\t\t\tparams[segment.slice(1)] = decodeURIComponent(part);\n\t\t\t\treturn part !== \"\";\n\t\t\t}\n\t\t\treturn segment === part;\n\t\t});\n\t\tif (matched) {\n\t\t\treturn { route, params };\n\t\t}\n\t}\n\treturn undefined;\n};\n\n/** What a request reaches past signing in: who may send it, the role it needs and what answers it. */\nexport interface Destination {\n\t/** A browser's session, this PC or a tailnet member may send it; otherwise only a token. */\n\tbrowser: boolean;\n\trole: Role;\n\thandle: (identity: Identity) => Promise<Response>;\n}\n\n/** The route of `routes` that `request` names, as a destination a browser may send it to or not. */\nexport const routeDestination = (\n\trequest: Request,\n\ttable: { routes: readonly ApiRoute[]; browser: boolean },\n): Destination | undefined => {\n\tconst matched = matchRoute(\n\t\ttable.routes,\n\t\trequest.method,\n\t\tnew URL(request.url).pathname,\n\t);\n\treturn (\n\t\tmatched && {\n\t\t\tbrowser: table.browser,\n\t\t\trole: matched.route.role,\n\t\t\thandle: (identity) =>\n\t\t\t\tmatched.route.handle(request, { identity, params: matched.params }),\n\t\t}\n\t);\n};\n\n/**\n * Answers `request` as `identity` at `destination`, if it has one: a refused or invalid request with\n * its status and the agent's message, and anything else that fails, logged, with 500.\n */\nexport const answer = async (\n\trequest: Request,\n\tdestination: Destination | undefined,\n\tidentity: Identity,\n\tlog: (message: string) => void,\n): Promise<Response> => {\n\tif (!destination) {\n\t\t// Only an admin learns that a route doesn't exist.\n\t\treturn allows(identity.role, \"admin\")\n\t\t\t? Response.json(\n\t\t\t\t\t{\n\t\t\t\t\t\terror: `No route ${request.method} ${new URL(request.url).pathname}`,\n\t\t\t\t\t},\n\t\t\t\t\t{ status: 404 },\n\t\t\t\t)\n\t\t\t: Response.json({ error: \"Unauthorized\" }, { status: 401 });\n\t}\n\tif (!allows(identity.role, destination.role)) {\n\t\t// The CLI's routes answer a token without the role as if it were none, which its client relies on.\n\t\treturn destination.browser\n\t\t\t? Response.json(\n\t\t\t\t\t{ error: `This needs the ${destination.role} role` },\n\t\t\t\t\t{ status: 403 },\n\t\t\t\t)\n\t\t\t: Response.json({ error: \"Unauthorized\" }, { status: 401 });\n\t}\n\ttry {\n\t\treturn await destination.handle(identity);\n\t} catch (error) {\n\t\tif (error instanceof AgentError) {\n\t\t\treturn Response.json({ error: error.message }, { status: error.status });\n\t\t}\n\t\tif (error instanceof z.ZodError) {\n\t\t\treturn Response.json({ error: z.prettifyError(error) }, { status: 400 });\n\t\t}\n\t\tlog(\n\t\t\t`${request.method} ${request.url} failed: ${error instanceof Error ? error.stack : String(error)}`,\n\t\t);\n\t\treturn Response.json({ error: errorMessage(error) }, { status: 500 });\n\t}\n};\n",
35
+ "import { rm } from \"node:fs/promises\";\nimport { uptime } from \"node:os\";\nimport { dirname } from \"node:path\";\nimport { setTimeout as delay } from \"node:timers/promises\";\nimport type { Environment } from \"@tsplc/config\";\nimport { z } from \"zod\";\nimport { errorMessage } from \"./errors\";\nimport { spawnWithLog } from \"./logs\";\nimport { processAlive, signalProcess, waitUntil } from \"./processes\";\nimport { readJsonFileIfValid, writeJsonFile } from \"./state\";\n\nconst healthyWithinMs = 60_000;\n/** Without a health URL, a server that stays up this long counts as started. */\nconst settleMs = 5000;\nconst restartDelayMs = 2000;\n/** How often a server this agent didn't start is checked for having exited. */\nconst watchMs = 2000;\n/** How long a server this agent didn't start may take to answer before another is started. */\nconst adoptWithinMs = 10_000;\n/** How long a stopped server may take to exit. */\nconst stopWithinMs = 10_000;\n\n/** The running server's process, which a restarted agent takes over instead of starting another. */\nconst recordSchema = z.strictObject({\n\tpid: z.int().positive(),\n\texecutable: z.string(),\n\t/** When it started, in milliseconds since the epoch. */\n\tstartedAt: z.number(),\n});\ntype ServerRecord = z.infer<typeof recordSchema>;\n\n/**\n * Whether a recorded server may still be running as the agent left it: its process exists and it\n * started since the machine booted, so its PID can't belong to a process from before a restart.\n */\nexport const mayStillRun = (\n\trecord: ServerRecord,\n\tmachine: {\n\t\tnow: number;\n\t\tuptimeSeconds: number;\n\t\talive: (pid: number) => boolean;\n\t},\n) =>\n\trecord.startedAt > machine.now - machine.uptimeSeconds * 1000 &&\n\tmachine.alive(record.pid);\n\n/** One running server: one this agent started, or one an earlier agent left running. */\ninterface Running {\n\texecutable: string;\n\tpid: number;\n\talive: () => boolean;\n\texited: Promise<unknown>;\n}\n\n/**\n * Runs the deployed server executable, restarting it whenever it exits, and swaps it for\n * another release's. Each start reads the environment afresh, so a restart applies changed secrets.\n * It runs detached from the agent with its output appended to `output`, so an agent that\n * restarts, to upgrade or after a crash, leaves the line's server running and takes it over.\n */\nexport const createServerSupervisor = (options: {\n\t/** The server's `/health` route, which answers once it is listening, or null for none. */\n\thealthUrl: string | null;\n\t/** Where the running server's process is recorded for the next agent. */\n\trecord: string;\n\t/** The file the server's output is appended to. */\n\toutput: string;\n\t/** The environment `executable` starts in. */\n\tenvironment: (executable: string) => Promise<Environment>;\n\tlog: (message: string) => void;\n}) => {\n\tlet current: Running | undefined;\n\n\t/** The environment `executable` starts in now, or null after logging why it can't be read. */\n\tconst readEnvironment = (executable: string) =>\n\t\toptions.environment(executable).catch((error: unknown) => {\n\t\t\toptions.log(\n\t\t\t\t`Starting the deployed server failed: ${errorMessage(error)}`,\n\t\t\t);\n\t\t\treturn null;\n\t\t});\n\n\t/** Restarts `running` once it exits, unless it was stopped or replaced first. */\n\tconst restartWhenExited = (running: Running, code: () => unknown) => {\n\t\tvoid running.exited.then(() => {\n\t\t\tif (current !== running) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\toptions.log(\n\t\t\t\t`Server exited (${code()}); restarting it in ${restartDelayMs / 1000} s`,\n\t\t\t);\n\t\t\tvoid delay(restartDelayMs).then(async () => {\n\t\t\t\tif (current !== running) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst environment = await readEnvironment(running.executable);\n\t\t\t\tif (current === running) {\n\t\t\t\t\tcurrent = environment\n\t\t\t\t\t\t? spawn(running.executable, environment)\n\t\t\t\t\t\t: undefined;\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t};\n\n\tconst spawn = (executable: string, environment: Environment): Running => {\n\t\t// A bundled server runs on the agent's own Bun; releases before bundles shipped an executable.\n\t\tconst command = executable.endsWith(\".js\")\n\t\t\t? [process.execPath, executable]\n\t\t\t: [executable];\n\t\tconst child = spawnWithLog(command, options.output, {\n\t\t\tcwd: dirname(executable),\n\t\t\tenv: environment,\n\t\t\tdetached: true,\n\t\t});\n\t\tconst running: Running = {\n\t\t\texecutable,\n\t\t\tpid: child.pid,\n\t\t\talive: () => child.exitCode === null && child.signalCode === null,\n\t\t\texited: child.exited,\n\t\t};\n\t\t// Written before anything else can happen, so an agent exiting next leaves it for the one after.\n\t\twriteJsonFile(options.record, {\n\t\t\tpid: child.pid,\n\t\t\texecutable,\n\t\t\tstartedAt: Date.now(),\n\t\t} satisfies ServerRecord);\n\t\trestartWhenExited(running, () => child.exitCode ?? child.signalCode);\n\t\treturn running;\n\t};\n\n\t/** Watches a server an earlier agent started, which this one can't wait on. */\n\tconst adopt = (record: ServerRecord): Running => {\n\t\tconst exited = Promise.withResolvers<void>();\n\t\tconst watch = setInterval(() => {\n\t\t\tif (!processAlive(record.pid)) {\n\t\t\t\tclearInterval(watch);\n\t\t\t\texited.resolve();\n\t\t\t}\n\t\t}, watchMs);\n\t\twatch.unref();\n\t\tconst running: Running = {\n\t\t\texecutable: record.executable,\n\t\t\tpid: record.pid,\n\t\t\talive: () => processAlive(record.pid),\n\t\t\texited: exited.promise,\n\t\t};\n\t\trestartWhenExited(running, () => \"unknown status\");\n\t\treturn running;\n\t};\n\n\t/** Whether the server answers its health route within `within`, giving up once it has exited. */\n\tconst answers = async (alive: () => boolean, within: number) => {\n\t\tconst { healthUrl } = options;\n\t\tif (healthUrl === null) {\n\t\t\treturn alive();\n\t\t}\n\t\tconst settled = await waitUntil(\n\t\t\tasync () =>\n\t\t\t\t!alive() ||\n\t\t\t\t(await fetch(healthUrl).then(\n\t\t\t\t\t(response) => response.ok,\n\t\t\t\t\t() => false,\n\t\t\t\t)),\n\t\t\twithin,\n\t\t);\n\t\treturn settled && alive();\n\t};\n\n\tconst start = (executable: string, environment: Environment) => {\n\t\tcurrent = spawn(executable, environment);\n\t\treturn current;\n\t};\n\n\tconst stop = async () => {\n\t\tconst running = current;\n\t\tcurrent = undefined;\n\t\tif (!running) {\n\t\t\treturn;\n\t\t}\n\t\tsignalProcess(running.pid, \"SIGTERM\");\n\t\tawait Promise.race([running.exited, delay(stopWithinMs)]);\n\t\tif (running.alive()) {\n\t\t\tsignalProcess(running.pid, \"SIGKILL\");\n\t\t\tawait running.exited;\n\t\t}\n\t\tawait rm(options.record, { force: true });\n\t};\n\n\tconst healthy = async (running: Running) => {\n\t\tif (options.healthUrl === null) {\n\t\t\tawait delay(settleMs);\n\t\t\treturn running.alive();\n\t\t}\n\t\treturn answers(running.alive, healthyWithinMs);\n\t};\n\n\treturn {\n\t\thealthUrl: options.healthUrl,\n\t\t/**\n\t\t * Runs `executable`, taking over the server an earlier agent left running when that is the one\n\t\t * still running and, with a health route, answering it. One whose environment can't be read is\n\t\t * logged and left stopped rather than failing the agent, which can still deploy another release.\n\t\t */\n\t\tresume: async (executable: string) => {\n\t\t\tconst record = await readJsonFileIfValid(options.record, recordSchema);\n\t\t\tif (\n\t\t\t\trecord?.executable === executable &&\n\t\t\t\tmayStillRun(record, {\n\t\t\t\t\tnow: Date.now(),\n\t\t\t\t\tuptimeSeconds: uptime(),\n\t\t\t\t\talive: processAlive,\n\t\t\t\t}) &&\n\t\t\t\t(await answers(() => processAlive(record.pid), adoptWithinMs))\n\t\t\t) {\n\t\t\t\toptions.log(`Took over the running server (process ${record.pid})`);\n\t\t\t\tcurrent = adopt(record);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst environment = await readEnvironment(executable);\n\t\t\tif (environment) {\n\t\t\t\tstart(executable, environment);\n\t\t\t}\n\t\t},\n\t\tstop,\n\t\t/** Stops supervising the server and leaves it running, for the agent that replaces this one. */\n\t\tleave: () => {\n\t\t\tcurrent = undefined;\n\t\t},\n\t\t/** Replaces the running server; if the new one doesn't come up, the previous one runs again. */\n\t\treplace: async (executable: string) => {\n\t\t\tconst previous = current;\n\t\t\tconst environment = await options.environment(executable);\n\t\t\tawait stop();\n\t\t\tconst { started, failure } = await (async () =>\n\t\t\t\thealthy(start(executable, environment)))().then(\n\t\t\t\t(answered) => ({ started: answered, failure: undefined }),\n\t\t\t\t(error: unknown) => ({ started: false, failure: error }),\n\t\t\t);\n\t\t\tif (started) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait stop();\n\t\t\tconst previousEnvironment =\n\t\t\t\tprevious && (await readEnvironment(previous.executable));\n\t\t\tif (previous && previousEnvironment) {\n\t\t\t\tstart(previous.executable, previousEnvironment);\n\t\t\t}\n\t\t\tconst reason =\n\t\t\t\tfailure instanceof Error\n\t\t\t\t\t? failure.message\n\t\t\t\t\t: `it did not start${options.healthUrl ? ` answering ${options.healthUrl}` : \"\"}`;\n\t\t\tthrow new Error(\n\t\t\t\t`The new server failed: ${reason}. ${previousEnvironment ? \"The previous one is running again.\" : \"\"}`.trim(),\n\t\t\t\t{ cause: failure },\n\t\t\t);\n\t\t},\n\t\tstatus: () =>\n\t\t\tcurrent\n\t\t\t\t? { executable: current.executable, running: current.alive() }\n\t\t\t\t: null,\n\t};\n};\nexport type ServerSupervisor = ReturnType<typeof createServerSupervisor>;\n",
36
+ "import { setTimeout as delay } from \"node:timers/promises\";\n\nconst isGone = (error: unknown) =>\n\terror instanceof Error && \"code\" in error && error.code === \"ESRCH\";\n\n/** Whether process `pid` exists; the agent can't wait on one an earlier agent started. */\nexport const processAlive = (pid: number) => {\n\ttry {\n\t\t// Signal 0 checks that the process exists without signalling it.\n\t\tprocess.kill(pid, 0);\n\t\treturn true;\n\t} catch (error) {\n\t\treturn !isGone(error);\n\t}\n};\n\n/** Signals process `pid`, which may have exited since it was last seen. */\nexport const signalProcess = (pid: number, name: NodeJS.Signals) => {\n\ttry {\n\t\tprocess.kill(pid, name);\n\t} catch (error) {\n\t\tif (!isGone(error)) {\n\t\t\tthrow error;\n\t\t}\n\t}\n};\n\n/** Whether `condition` holds within `within` milliseconds, checking it each second. */\nexport const waitUntil = async (\n\tcondition: () => Promise<boolean>,\n\twithin: number,\n) => {\n\tconst deadline = Date.now() + within;\n\twhile (Date.now() < deadline) {\n\t\tif (await condition()) {\n\t\t\treturn true;\n\t\t}\n\t\tawait delay(1000);\n\t}\n\treturn false;\n};\n",
37
+ "import { rm } from \"node:fs/promises\";\nimport { z } from \"zod\";\nimport type { AgentClient } from \"./client\";\nimport { processAlive } from \"./processes\";\nimport { agentVersionHeader, statusPath } from \"./protocol\";\nimport { readJsonFileIfValid } from \"./state\";\n\n/**\n * The running agent, as `serve` records it in its state directory, so that `upgrade` and\n * `service` on the same PC can reach it and start it again the same way.\n */\nexport const instanceSchema = z.strictObject({\n\tpid: z.int().positive(),\n\tversion: z.string(),\n\turl: z.url(),\n\t/** The arguments after `serve` it was started with. */\n\tserve: z.array(z.string()),\n\t/** Started by `tsplc-agent service run`, which starts it again when it exits. */\n\tsupervised: z.boolean(),\n\tstartedAt: z.iso.datetime(),\n});\nexport type Instance = z.infer<typeof instanceSchema>;\n\n/** The exit status of an agent that exits to be started again, such as after an upgrade. */\nexport const restartStatus = 75;\n\n/** Removes the record, unless another agent has replaced it since. */\nexport const removeInstance = async (file: string, pid: number) => {\n\tif ((await readInstance(file))?.pid === pid) {\n\t\tawait rm(file, { force: true });\n\t}\n};\n\nconst readInstance = (file: string) =>\n\treadJsonFileIfValid(file, instanceSchema);\n\n/** The agent recorded in `file`, when its process still runs, or null. */\nexport const runningAgent = async (file: string) => {\n\tconst instance = await readInstance(file);\n\treturn instance && processAlive(instance.pid) ? instance : null;\n};\n\n/** The tsPLC version the agent at `url` answers with, which it names even to a request without its token, or null. */\nexport const answeringVersion = (url: string) =>\n\tfetch(new URL(statusPath, url), { signal: AbortSignal.timeout(5000) }).then(\n\t\t(response) => response.headers.get(agentVersionHeader),\n\t\t() => null,\n\t);\n\n/** The routes that hold a running agent for an upgrade and make it exit. */\nexport type AgentControl = Pick<AgentClient, \"hold\" | \"releaseHold\" | \"exit\">;\n",
38
+ "import { mkdtemp, readFile, rm, writeFile } from \"node:fs/promises\";\nimport { homedir, tmpdir } from \"node:os\";\nimport { join, resolve } from \"node:path\";\nimport { agentTokenEnv, type Environment } from \"@tsplc/config\";\nimport { z } from \"zod\";\nimport { createAgentClient } from \"./client\";\nimport {\n\ttype AgentControl,\n\tansweringVersion,\n\ttype Instance,\n\trunningAgent,\n} from \"./instance\";\nimport { spawnWithLog } from \"./logs\";\nimport { processAlive, waitUntil } from \"./processes\";\nimport { agentSetting } from \"./secrets\";\nimport { schtasks, superviseAgent, taskDefinition, taskFile } from \"./service\";\nimport { openState } from \"./state\";\nimport {\n\tinstallCommand,\n\tnpmCommand,\n\tpackageManagerFor,\n\tupgradeAgent,\n} from \"./upgrade\";\n\n/** The installed agent package, one directory above its source modules and its bundle alike. */\nconst agentPackage = resolve(import.meta.dir, \"..\");\n\n/** The version of the agent package installed now, which an upgrade may have changed under this process. */\nconst installedVersion = async () =>\n\tz\n\t\t.object({ version: z.string() })\n\t\t.parse(\n\t\t\tJSON.parse(await readFile(join(agentPackage, \"package.json\"), \"utf8\")),\n\t\t).version;\n\n/** How long a new agent may take to answer, and an old one to exit. */\nconst answerWithinMs = 180_000;\nconst exitWithinMs = 60_000;\n\nconst run = (command: string[]) =>\n\tBun.spawn(command, { stdio: [\"inherit\", \"inherit\", \"inherit\"] }).exited;\n\nconst quietly = (command: string[]) =>\n\tBun.spawn(command, { stdio: [\"ignore\", \"ignore\", \"ignore\"] }).exited;\n\n/** What `command` prints, or null when it fails or isn't installed. */\nconst capture = async (command: string[]) => {\n\ttry {\n\t\tconst child = Bun.spawn(command, { stdio: [\"ignore\", \"pipe\", \"ignore\"] });\n\t\tconst [output, status] = await Promise.all([\n\t\t\tnew Response(child.stdout).text(),\n\t\t\tchild.exited,\n\t\t]);\n\t\treturn status === 0 ? output.trim() : null;\n\t} catch {\n\t\treturn null;\n\t}\n};\n\n/** The command that runs this agent's CLI with `args`, on the Bun running it now. */\nconst agentCommand = (...args: string[]) => [\n\tprocess.execPath,\n\tBun.main,\n\t...args,\n];\n\n/** The control routes of `instance`, which need its full token. */\nconst controlOf = async (\n\tinstance: Instance,\n\tenvironment: Environment,\n): Promise<AgentControl> => {\n\tconst token = await agentSetting(agentTokenEnv, environment);\n\tif (!token) {\n\t\tthrow new Error(\n\t\t\t`tsplc-agent ${instance.version} is running, and holding it needs its token: set ${agentTokenEnv}, or store it with tsplc-agent secrets set ${agentTokenEnv} as the user the agent runs as`,\n\t\t);\n\t}\n\treturn createAgentClient({ url: instance.url, token });\n};\n\n/** The running agent and its control routes. */\nconst controlRunning = async (agentFile: string, environment: Environment) => {\n\tconst instance = await runningAgent(agentFile);\n\treturn (\n\t\tinstance && { instance, control: await controlOf(instance, environment) }\n\t);\n};\n\nconst waitForExit = async (instance: Instance) => {\n\tif (\n\t\t!(await waitUntil(async () => !processAlive(instance.pid), exitWithinMs))\n\t) {\n\t\tthrow new Error(\n\t\t\t`tsplc-agent (process ${instance.pid}) didn't exit within ${exitWithinMs / 1000} s`,\n\t\t);\n\t}\n};\n\n/** Whether the agent recorded in `agentFile` runs `version` and answers. */\nconst answers = (agentFile: string, version: string) =>\n\twaitUntil(async () => {\n\t\tconst instance = await runningAgent(agentFile);\n\t\treturn (\n\t\t\tinstance?.version === version &&\n\t\t\t(await answeringVersion(instance.url)) === version\n\t\t);\n\t}, answerWithinMs);\n\n/** `tsplc-agent upgrade [version]`. */\nexport const upgradeCommand = async (options: {\n\tversion: string;\n\tstate: string;\n\tenvironment: Environment;\n}) => {\n\tconst state = await openState(options.state);\n\tconst manager =\n\t\tpackageManagerFor(agentPackage, null) ??\n\t\tpackageManagerFor(\n\t\t\tagentPackage,\n\t\t\tawait capture(npmCommand(process.platform, \"root\", \"--global\")),\n\t\t);\n\tif (!manager) {\n\t\tthrow new Error(\n\t\t\t`This agent runs from ${agentPackage}, which isn't a global bun or npm install; upgrade it the way it was installed`,\n\t\t);\n\t}\n\tawait upgradeAgent(\n\t\t{\n\t\t\tversion: options.version,\n\t\t\tinstall: installCommand(manager, options.version, {\n\t\t\t\tbun: process.execPath,\n\t\t\t\tplatform: process.platform,\n\t\t\t}),\n\t\t\tsetup: agentCommand(\"setup\", \"--if-needed\"),\n\t\t\trunning: await controlRunning(state.paths.agent, options.environment),\n\t\t\tagentLog: state.paths.agentLog,\n\t\t},\n\t\t{\n\t\t\trun,\n\t\t\tinstalledVersion,\n\t\t\tstartAgent: async (instance) => {\n\t\t\t\tawait waitForExit(instance);\n\t\t\t\tspawnWithLog(\n\t\t\t\t\tagentCommand(\"serve\", ...instance.serve),\n\t\t\t\t\tstate.paths.agentLog,\n\t\t\t\t\t{ detached: true, windowsHide: true },\n\t\t\t\t).unref();\n\t\t\t},\n\t\t\tstartService: async () =>\n\t\t\t\tprocess.platform === \"win32\" &&\n\t\t\t\t(await quietly(schtasks.query())) === 0 &&\n\t\t\t\t(await run(schtasks.run())) === 0,\n\t\t\tanswers: (version) => answers(state.paths.agent, version),\n\t\t\tprint: (line) => console.log(line),\n\t\t},\n\t);\n};\n\nconst requireWindows = () => {\n\tif (process.platform !== \"win32\") {\n\t\tthrow new Error(\n\t\t\t\"tsplc-agent service registers a Windows Task Scheduler task. Elsewhere, have your init system run tsplc-agent service run with the serve options, such as a systemd unit\",\n\t\t);\n\t}\n};\n\nconst releasing = async <T>(\n\trunning: { control: AgentControl } | null,\n\tstep: () => Promise<T>,\n) =>\n\tstep().catch(async (error: unknown) => {\n\t\tawait running?.control.releaseHold();\n\t\tthrow error;\n\t});\n\n/** `tsplc-agent service install|uninstall|status|run`. */\nexport const serviceCommand = async (options: {\n\taction: string | undefined;\n\tstate: string;\n\t/** The serve options the service runs the agent with. */\n\tserve: string[];\n\tstopServer: boolean;\n\tenvironment: Environment;\n}) => {\n\tconst state = await openState(options.state);\n\tconst logs = `The agent's log is ${state.paths.agentLog}; the line's server's is ${state.paths.serverLog}`;\n\tswitch (options.action) {\n\t\tcase \"run\":\n\t\t\tawait superviseAgent({\n\t\t\t\tcommand: agentCommand(\"serve\", ...options.serve),\n\t\t\t\tlog: state.paths.agentLog,\n\t\t\t\tenvironment: options.environment,\n\t\t\t});\n\t\t\treturn;\n\t\tcase \"install\": {\n\t\t\trequireWindows();\n\t\t\tconst { USERDOMAIN, USERNAME } = options.environment;\n\t\t\tif (!USERNAME) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"USERNAME isn't set, so the service has no user to run as\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst user = [USERDOMAIN, USERNAME].filter(Boolean).join(\"\\\\\");\n\t\t\tconst running = await controlRunning(\n\t\t\t\tstate.paths.agent,\n\t\t\t\toptions.environment,\n\t\t\t);\n\t\t\tawait running?.control.hold();\n\t\t\tawait releasing(running, async () => {\n\t\t\t\tconst directory = await mkdtemp(join(tmpdir(), \"tsplc-agent-service-\"));\n\t\t\t\ttry {\n\t\t\t\t\tconst file = join(directory, \"task.xml\");\n\t\t\t\t\tawait writeFile(\n\t\t\t\t\t\tfile,\n\t\t\t\t\t\ttaskFile(\n\t\t\t\t\t\t\ttaskDefinition({\n\t\t\t\t\t\t\t\tbun: process.execPath,\n\t\t\t\t\t\t\t\tscript: Bun.main,\n\t\t\t\t\t\t\t\tserve: options.serve,\n\t\t\t\t\t\t\t\tuser,\n\t\t\t\t\t\t\t\tworkingDirectory: homedir(),\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t`Registering the ${user} service; schtasks asks for ${user}'s Windows password, which Task Scheduler keeps to start the agent at boot`,\n\t\t\t\t\t);\n\t\t\t\t\tif ((await run(schtasks.create(file, user))) !== 0) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\"Registering the service failed. Run tsplc-agent service install in a PowerShell opened with Run as administrator, signed in as the user the agent runs as\",\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t} finally {\n\t\t\t\t\tawait rm(directory, { recursive: true, force: true });\n\t\t\t\t}\n\t\t\t});\n\t\t\tif (running) {\n\t\t\t\tconsole.log(\n\t\t\t\t\t`Handing over from tsplc-agent ${running.instance.version} (process ${running.instance.pid}); the line's server keeps running`,\n\t\t\t\t);\n\t\t\t\tawait running.control.exit({ server: \"leave\", restart: false });\n\t\t\t\tawait waitForExit(running.instance);\n\t\t\t}\n\t\t\tif ((await run(schtasks.run())) !== 0) {\n\t\t\t\tthrow new Error(\"The service is registered but didn't start\");\n\t\t\t}\n\t\t\tconst version = await installedVersion();\n\t\t\tif (!(await answers(state.paths.agent, version))) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`The service started but tsplc-agent ${version} doesn't answer. ${logs}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconsole.log(\n\t\t\t\t`The tsplc-agent service runs tsplc-agent ${version} at boot as ${user}, and starts it again if it exits. ${logs}`,\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tcase \"uninstall\": {\n\t\t\trequireWindows();\n\t\t\tconst running = await runningAgent(state.paths.agent);\n\t\t\tif (running?.supervised) {\n\t\t\t\tconst control = await controlOf(running, options.environment);\n\t\t\t\tawait control.hold();\n\t\t\t\tawait control.exit({\n\t\t\t\t\tserver: options.stopServer ? \"stop\" : \"leave\",\n\t\t\t\t\trestart: false,\n\t\t\t\t});\n\t\t\t\tawait waitForExit(running);\n\t\t\t} else {\n\t\t\t\t// A service waiting to start the agent again is stopped instead.\n\t\t\t\tawait quietly(schtasks.end());\n\t\t\t}\n\t\t\tif ((await run(schtasks.remove())) !== 0) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"Removing the service failed. Run it in a PowerShell opened with Run as administrator\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tconsole.log(\n\t\t\t\toptions.stopServer || !running?.supervised\n\t\t\t\t\t? \"Removed the tsplc-agent service\"\n\t\t\t\t\t: \"Removed the tsplc-agent service. The line's server keeps running; the next tsplc-agent serve takes it over\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tcase \"status\": {\n\t\t\tif (process.platform === \"win32\" && (await run(schtasks.query())) !== 0) {\n\t\t\t\tconsole.log(\"The tsplc-agent service isn't installed\");\n\t\t\t}\n\t\t\tconst running = await runningAgent(state.paths.agent);\n\t\t\tconsole.log(\n\t\t\t\trunning\n\t\t\t\t\t? `tsplc-agent ${running.version} runs as process ${running.pid} at ${running.url}${running.supervised ? \", under the service\" : \"\"}, since ${running.startedAt}`\n\t\t\t\t\t: \"No tsplc-agent is running\",\n\t\t\t);\n\t\t\tconsole.log(logs);\n\t\t\treturn;\n\t\t}\n\t\tdefault:\n\t\t\tthrow new Error(\n\t\t\t\t\"Usage: tsplc-agent service install|uninstall|status|run [serve options]\",\n\t\t\t);\n\t}\n};\n",
39
+ "import { hostname, userInfo } from \"node:os\";\nimport {\n\ttype LoginCommand,\n\tloginResultSchema,\n\ttype Rollback,\n\tworkerScriptsDigest,\n} from \"@tsplc/build\";\nimport { plantVariablesSchema } from \"@tsplc/config\";\nimport { parseEventStream } from \"@tsplc/debug/api\";\nimport {\n\ttype ControllerRestart,\n\tcontrollerRestartPath,\n\tcontrollerRestartReplySchema,\n\trefusalMessage,\n} from \"@tsplc/server/plant-agent\";\nimport { z } from \"zod\";\nimport {\n\ttype AgentExit,\n\tagentExitPath,\n\tagentHoldPath,\n\tagentVersionHeader,\n\ttype Comparison,\n\ttype Credentials,\n\tclientHeaders,\n\tcomparisonSchema,\n\ttype DeploymentEvent,\n\ttype DeploymentMode,\n\ttype DeployOptions,\n\tdeploymentApiPath,\n\tdeploymentCreatedSchema,\n\tdeploymentListSchema,\n\tdeploymentLogLineSchema,\n\tdeploymentRecordSchema,\n\tdeploymentsApiPath,\n\tdiscoveredControllerSchema,\n\teventSchema,\n\tlogoutSchema,\n\tnetworkInterfaceSchema,\n\ttype ReleaseManifest,\n\ttype ReleaseUpload,\n\treleaseSchema,\n\treleaseUploadType,\n\tstatusPath,\n\tstatusSchema,\n\ttype Target,\n\ttargetSchema,\n\ttsplcVersion,\n\tupgradesItself,\n\tvariableSchema,\n\tversionMismatch,\n} from \"./protocol\";\nimport {\n\tbucketDigests,\n\tencodeUpload,\n\tfileBucket,\n\ttype ReleaseContent,\n\tshortDigest,\n} from \"./transfer\";\n\n/**\n * A failed agent operation; `downloadRequired` means only a full download can deploy, and\n * `rollback` what became of the controller after a download failed mid-transfer.\n */\nexport class AgentOperationError extends Error {\n\treadonly downloadRequired: boolean;\n\treadonly rollback: Rollback | undefined;\n\n\tconstructor(\n\t\tmessage: string,\n\t\t{\n\t\t\tdownloadRequired = false,\n\t\t\trollback,\n\t\t}: { downloadRequired?: boolean; rollback?: Rollback } = {},\n\t) {\n\t\tsuper(message);\n\t\tthis.downloadRequired = downloadRequired;\n\t\tthis.rollback = rollback;\n\t}\n}\n\n/** The agent can't be reached, or the connection to it broke; trying again may succeed. */\nexport class AgentUnreachable extends Error {}\n\nexport type { DeploymentEvent };\n\n/** A response body's text as it arrives; a broken connection throws `AgentUnreachable`. */\nasync function* bodyText(body: NonNullable<Response[\"body\"]>) {\n\ttry {\n\t\tyield* body.pipeThrough(new TextDecoderStream());\n\t} catch (cause) {\n\t\tthrow new AgentUnreachable(\"The connection to the agent broke\", { cause });\n\t}\n}\n\n/** A file to upload, at its path in the release. */\nexport interface ReleaseFile {\n\tpath: string;\n\tcontent: Blob;\n}\n\n/** Talks to a plant agent at `url`, such as its Tailscale name and port. */\nexport const createAgentClient = (options: { url: string; token: string }) => {\n\t// The agent records who deployed and who changed the controller, and refuses another tsPLC version.\n\tconst identity = workerScriptsDigest()\n\t\t.then(\n\t\t\t(scripts) => ({ [clientHeaders.scripts]: scripts }),\n\t\t\t// The digest only tells local builds apart; an installation that can't read its scripts still deploys.\n\t\t\t() => ({}),\n\t\t)\n\t\t.then((scripts) => ({\n\t\t\t[clientHeaders.user]: userInfo().username,\n\t\t\t[clientHeaders.host]: hostname(),\n\t\t\t[clientHeaders.version]: tsplcVersion,\n\t\t\t...scripts,\n\t\t}));\n\tconst call = async (path: string, init: RequestInit = {}) => {\n\t\tconst response = await fetch(new URL(path, options.url), {\n\t\t\t...init,\n\t\t\theaders: {\n\t\t\t\t...init.headers,\n\t\t\t\t...(await identity),\n\t\t\t\tAuthorization: `Bearer ${options.token}`,\n\t\t\t},\n\t\t}).catch((cause: unknown) => {\n\t\t\tthrow new AgentUnreachable(\n\t\t\t\t`Cannot reach the plant agent at ${options.url}`,\n\t\t\t\t{ cause },\n\t\t\t);\n\t\t});\n\t\tif (!response.ok) {\n\t\t\tthrow new AgentOperationError(await refusalMessage(response));\n\t\t}\n\t\treturn response;\n\t};\n\tconst get = async <T>(path: string, schema: z.ZodType<T>) =>\n\t\tschema.parse(await (await call(path)).json());\n\tconst send = async <T>(\n\t\tmethod: string,\n\t\tpath: string,\n\t\tbody: unknown,\n\t\tschema: z.ZodType<T>,\n\t) =>\n\t\tschema.parse(\n\t\t\tawait (\n\t\t\t\tawait call(path, {\n\t\t\t\t\tmethod,\n\t\t\t\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\t\t\t\tbody: JSON.stringify(body),\n\t\t\t\t})\n\t\t\t).json(),\n\t\t);\n\n\t/** Reads a streamed operation, reporting progress, until its result or failure. */\n\tconst operation = async (\n\t\tresponse: Response,\n\t\tonProgress: (message: string) => void,\n\t) => {\n\t\tconst reader = response.body\n\t\t\t?.pipeThrough(new TextDecoderStream())\n\t\t\t.getReader();\n\t\tif (!reader) {\n\t\t\tthrow new Error(\"The agent returned no operation stream\");\n\t\t}\n\t\tlet buffered = \"\";\n\t\twhile (true) {\n\t\t\tconst { done, value } = await reader.read();\n\t\t\tif (done) {\n\t\t\t\tthrow new Error(\"The agent closed the operation without a result\");\n\t\t\t}\n\t\t\tbuffered += value;\n\t\t\tconst lines = buffered.split(\"\\n\");\n\t\t\tbuffered = lines.pop() ?? \"\";\n\t\t\tfor (const line of lines.filter(Boolean)) {\n\t\t\t\tconst event = eventSchema.parse(JSON.parse(line));\n\t\t\t\tif (event.kind === \"progress\") {\n\t\t\t\t\tonProgress(event.message);\n\t\t\t\t} else if (event.kind === \"done\") {\n\t\t\t\t\treturn event.result;\n\t\t\t\t} else {\n\t\t\t\t\tthrow new AgentOperationError(event.message, {\n\t\t\t\t\t\tdownloadRequired: event.downloadRequired,\n\t\t\t\t\t\trollback: event.rollback,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t};\n\n\t/** What the agent holds of a release with these bucket digests. */\n\tconst compare = (buckets: string[]) =>\n\t\tsend(\"POST\", \"/releases/compare\", { buckets }, comparisonSchema);\n\n\t/**\n\t * The upload body of `release`, built on what the agent already holds. Refuses an agent of\n\t * another version first.\n\t */\n\tconst upload = async (\n\t\trelease: { manifest: ReleaseManifest; files: ReleaseFile[] },\n\t\tsettings: DeployOptions,\n\t\tonProgress: (message: string) => void,\n\t) => {\n\t\t// Before uploading: an agent of another version, including one from before version checks,\n\t\t// would compile the release with scripts this client doesn't expect.\n\t\tconst agentVersion = (await call(statusPath)).headers.get(\n\t\t\tagentVersionHeader,\n\t\t);\n\t\tif (agentVersion !== tsplcVersion) {\n\t\t\tthrow new AgentOperationError(\n\t\t\t\tversionMismatch({\n\t\t\t\t\tagent: agentVersion,\n\t\t\t\t\tclient: tsplcVersion,\n\t\t\t\t\tagentUpgrades: upgradesItself(agentVersion),\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\t\tconst files = await Promise.all(\n\t\t\trelease.files.map(async ({ path, content }) => ({\n\t\t\t\tpath,\n\t\t\t\tcontent: await content.bytes(),\n\t\t\t})),\n\t\t);\n\t\tconst digests = files.map(({ path, content }) => ({\n\t\t\tpath,\n\t\t\tdigest: shortDigest(content),\n\t\t}));\n\t\tconst buckets = bucketDigests(digests);\n\t\treturn releaseUpload(\n\t\t\t{ manifest: release.manifest, options: settings, buckets },\n\t\t\tfiles,\n\t\t\tawait compare(buckets),\n\t\t\tonProgress,\n\t\t);\n\t};\n\n\treturn {\n\t\t/** The agent's address, where its dashboard is. */\n\t\turl: options.url,\n\t\tstatus: () => get(statusPath, statusSchema),\n\t\tinterfaces: () => get(\"/interfaces\", z.array(networkInterfaceSchema)),\n\t\tdiscover: (name: string) =>\n\t\t\tsend(\"POST\", \"/discover\", { name }, z.array(discoveredControllerSchema)),\n\t\tsetTarget: (target: Target) => send(\"PUT\", \"/target\", target, targetSchema),\n\t\tvariables: () => get(\"/variables\", z.array(variableSchema)),\n\t\t/** Deploys `release` at once, streaming its progress: `POST /deploy`. */\n\t\tdeploy: async (\n\t\t\trelease: { manifest: ReleaseManifest; files: ReleaseFile[] },\n\t\t\tsettings: DeployOptions,\n\t\t\tonProgress: (message: string) => void,\n\t\t) => {\n\t\t\tconst body = await upload(release, settings, onProgress);\n\t\t\treturn releaseSchema.parse(\n\t\t\t\tawait operation(\n\t\t\t\t\tawait call(\"/deploy\", { method: \"POST\", ...body }),\n\t\t\t\t\tonProgress,\n\t\t\t\t),\n\t\t\t);\n\t\t},\n\t\t/** Queues `release` as a deployment the agent runs on its own: `POST /api/deployments`. */\n\t\tqueueDeployment: async (\n\t\t\trelease: { manifest: ReleaseManifest; files: ReleaseFile[] },\n\t\t\tsettings: DeployOptions,\n\t\t\tonProgress: (message: string) => void,\n\t\t) => {\n\t\t\tconst body = await upload(release, settings, onProgress);\n\t\t\treturn deploymentCreatedSchema.parse(\n\t\t\t\tawait (\n\t\t\t\t\tawait call(deploymentsApiPath, { method: \"POST\", ...body })\n\t\t\t\t).json(),\n\t\t\t);\n\t\t},\n\t\tdeployments: () => get(deploymentsApiPath, deploymentListSchema),\n\t\t/**\n\t\t * A deployment's events from after log line `after`, until the agent ends the stream once\n\t\t * the deployment finishes. A broken connection throws `AgentUnreachable`.\n\t\t */\n\t\tdeploymentEvents: async function* (\n\t\t\tid: string,\n\t\t\tafter: number,\n\t\t): AsyncGenerator<DeploymentEvent> {\n\t\t\tconst response = await call(\n\t\t\t\t`${deploymentApiPath(id)}/events?after=${after}`,\n\t\t\t\t{ headers: { Accept: \"text/event-stream\" } },\n\t\t\t);\n\t\t\tif (!response.body) {\n\t\t\t\tthrow new AgentUnreachable(\"The agent returned no event stream\");\n\t\t\t}\n\t\t\tfor await (const event of parseEventStream(bodyText(response.body))) {\n\t\t\t\tif (event.event === \"record\") {\n\t\t\t\t\tyield {\n\t\t\t\t\t\tkind: \"record\",\n\t\t\t\t\t\trecord: deploymentRecordSchema.parse(JSON.parse(event.data)),\n\t\t\t\t\t};\n\t\t\t\t} else if (event.event === \"log\") {\n\t\t\t\t\tyield {\n\t\t\t\t\t\tkind: \"log\",\n\t\t\t\t\t\tline: deploymentLogLineSchema.parse(JSON.parse(event.data)),\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t/** Approves a deployment that waits on a person, as a full download when `download`. */\n\t\tapprove: async (id: string, approval: { download: boolean }) => {\n\t\t\tawait call(`${deploymentApiPath(id)}/approve`, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\t\t\tbody: JSON.stringify(approval),\n\t\t\t});\n\t\t},\n\t\tredeploy: (id: string, mode: DeploymentMode) =>\n\t\t\tsend(\n\t\t\t\t\"POST\",\n\t\t\t\t`${deploymentApiPath(id)}/redeploy`,\n\t\t\t\t{ mode },\n\t\t\t\tdeploymentCreatedSchema,\n\t\t\t),\n\t\trollback: (id: string) =>\n\t\t\tsend(\n\t\t\t\t\"POST\",\n\t\t\t\t`${deploymentApiPath(id)}/rollback`,\n\t\t\t\t{},\n\t\t\t\tdeploymentCreatedSchema,\n\t\t\t),\n\t\t/**\n\t\t * The plant PC's plain variables, and the secrets it holds in `service`, or in the agent's\n\t\t * own service when null: what a release is built with.\n\t\t */\n\t\treleaseVariables: (service: string | null) =>\n\t\t\tget(\n\t\t\t\t`/api/environment/release${service === null ? \"\" : `?${new URLSearchParams({ service })}`}`,\n\t\t\t\tplantVariablesSchema,\n\t\t\t),\n\t\t/** Resets the controller's application and starts it again; answers once it runs. */\n\t\trestartController: (restart: ControllerRestart) =>\n\t\t\tsend(\n\t\t\t\t\"POST\",\n\t\t\t\tcontrollerRestartPath,\n\t\t\t\trestart,\n\t\t\t\tcontrollerRestartReplySchema,\n\t\t\t),\n\t\tlogin: async (\n\t\t\tcredentials: Credentials | null,\n\t\t\tonProgress: (message: string) => void,\n\t\t) =>\n\t\t\tloginResultSchema.parse(\n\t\t\t\tawait operation(\n\t\t\t\t\tawait call(\"/login\", {\n\t\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\t\t\t\t\tbody: JSON.stringify(credentials),\n\t\t\t\t\t}),\n\t\t\t\t\tonProgress,\n\t\t\t\t),\n\t\t\t),\n\t\tcommand: (command: LoginCommand) =>\n\t\t\tsend(\"POST\", \"/login/command\", command, loginResultSchema),\n\t\tlogout: () => send(\"DELETE\", \"/login\", undefined, logoutSchema),\n\t\t/** Holds the agent for an upgrade, so it takes no operations; fails while one runs or a login is open. */\n\t\thold: async () => {\n\t\t\tawait call(agentHoldPath, { method: \"POST\" });\n\t\t},\n\t\t/** Lets a held agent take operations again. */\n\t\treleaseHold: async () => {\n\t\t\tawait call(agentHoldPath, { method: \"DELETE\" });\n\t\t},\n\t\t/** Makes the held agent exit. */\n\t\texit: async (exit: AgentExit) => {\n\t\t\tawait call(agentExitPath, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\t\t\tbody: JSON.stringify(exit),\n\t\t\t});\n\t\t},\n\t};\n};\nexport type AgentClient = ReturnType<typeof createAgentClient>;\n\n/**\n * A release upload built on the release the agent compared it with: in each bucket that differs,\n * the files the agent lacks and the paths to drop. Without a base, every file.\n */\nconst releaseUpload = async (\n\theader: Pick<ReleaseUpload, \"manifest\" | \"options\" | \"buckets\">,\n\tfiles: readonly ReleaseContent[],\n\t{ base, changed }: Comparison,\n\tonProgress: (message: string) => void,\n) => {\n\tconst stored = new Map(changed.map(({ bucket, files }) => [bucket, files]));\n\tconst uploaded =\n\t\tbase === null\n\t\t\t? files\n\t\t\t: files.filter(({ path, content }) => {\n\t\t\t\t\tconst held = stored.get(fileBucket(path));\n\t\t\t\t\treturn held !== undefined && held[path] !== shortDigest(content);\n\t\t\t\t});\n\tconst paths = new Set(files.map(({ path }) => path));\n\tconst remove = [...stored.values()].flatMap((held) =>\n\t\tObject.keys(held).filter((path) => !paths.has(path)),\n\t);\n\tconst body = await encodeUpload(\n\t\t{ ...header, base, remove } satisfies ReleaseUpload,\n\t\tuploaded,\n\t);\n\tonProgress(\n\t\t`Uploading ${uploaded.length} of ${files.length} files (${Math.ceil(body.length / 1024)} KB)`,\n\t);\n\treturn { headers: { \"Content-Type\": releaseUploadType }, body };\n};\n",
40
+ "import { rm } from \"node:fs/promises\";\nimport { z } from \"zod\";\nimport type { AgentClient } from \"./client\";\nimport { processAlive } from \"./processes\";\nimport { agentVersionHeader, statusPath } from \"./protocol\";\nimport { readJsonFileIfValid } from \"./state\";\n\n/**\n * The running agent, as `serve` records it in its state directory, so that `upgrade` and\n * `service` on the same PC can reach it and start it again the same way.\n */\nexport const instanceSchema = z.strictObject({\n\tpid: z.int().positive(),\n\tversion: z.string(),\n\turl: z.url(),\n\t/** The arguments after `serve` it was started with. */\n\tserve: z.array(z.string()),\n\t/** Started by `tsplc-agent service run`, which starts it again when it exits. */\n\tsupervised: z.boolean(),\n\tstartedAt: z.iso.datetime(),\n});\nexport type Instance = z.infer<typeof instanceSchema>;\n\n/** The exit status of an agent that exits to be started again, such as after an upgrade. */\nexport const restartStatus = 75;\n\n/** Removes the record, unless another agent has replaced it since. */\nexport const removeInstance = async (file: string, pid: number) => {\n\tif ((await readInstance(file))?.pid === pid) {\n\t\tawait rm(file, { force: true });\n\t}\n};\n\nconst readInstance = (file: string) =>\n\treadJsonFileIfValid(file, instanceSchema);\n\n/** The agent recorded in `file`, when its process still runs, or null. */\nexport const runningAgent = async (file: string) => {\n\tconst instance = await readInstance(file);\n\treturn instance && processAlive(instance.pid) ? instance : null;\n};\n\n/** The tsPLC version the agent at `url` answers with, which it names even to a request without its token, or null. */\nexport const answeringVersion = (url: string) =>\n\tfetch(new URL(statusPath, url), { signal: AbortSignal.timeout(5000) }).then(\n\t\t(response) => response.headers.get(agentVersionHeader),\n\t\t() => null,\n\t);\n\n/** The routes that hold a running agent for an upgrade and make it exit. */\nexport type AgentControl = Pick<AgentClient, \"hold\" | \"releaseHold\" | \"exit\">;\n",
41
+ "import { appendFile } from \"node:fs/promises\";\nimport { setTimeout as delay } from \"node:timers/promises\";\nimport type { Environment } from \"@tsplc/config\";\nimport { restartStatus } from \"./instance\";\nimport { spawnWithLog } from \"./logs\";\n\n/** The Task Scheduler task that runs the agent as a service. */\nexport const serviceName = \"tsplc-agent\";\n\n/** Set in the environment of a `serve` that `service run` started, which says so in its record. */\nexport const supervisedEnv = \"TSPLC_AGENT_SUPERVISED\";\n\n/**\n * One argument of a Windows command line, quoted so that a program's C runtime\n * (CommandLineToArgvW) reads it back unchanged: backslashes double only before a quote.\n */\nexport const quoteWindowsArgument = (argument: string) => {\n\tif (argument !== \"\" && !/[\\s\"]/.test(argument)) {\n\t\treturn argument;\n\t}\n\tconst escaped = argument\n\t\t.replace(/(\\\\*)\"/g, '$1$1\\\\\"')\n\t\t.replace(/(\\\\+)$/, \"$1$1\");\n\treturn `\"${escaped}\"`;\n};\n\nconst escapeXml = (text: string) =>\n\ttext\n\t\t.replaceAll(\"&\", \"&amp;\")\n\t\t.replaceAll(\"<\", \"&lt;\")\n\t\t.replaceAll(\">\", \"&gt;\")\n\t\t.replaceAll('\"', \"&quot;\");\n\n/**\n * The Task Scheduler definition of the agent's service: `bun script service run <serve…>` as\n * `user`, at boot whether or not anyone logs on, so the line's server runs after a power cut.\n * The password logon keeps the user's Credential Manager, where Bun.secrets keeps the agent's\n * token, readable. `service run` restarts the agent itself; Task Scheduler restarts `service run`\n * if it fails to start. It runs without a time limit, and only one at a time.\n */\nexport const taskDefinition = (task: {\n\tbun: string;\n\tscript: string;\n\tserve: string[];\n\tuser: string;\n\tworkingDirectory: string;\n}) => {\n\tconst argumentsText = [task.script, \"service\", \"run\", ...task.serve]\n\t\t.map(quoteWindowsArgument)\n\t\t.join(\" \");\n\treturn `<?xml version=\"1.0\" encoding=\"UTF-16\"?>\n<Task version=\"1.4\" xmlns=\"http://schemas.microsoft.com/windows/2004/02/mit/task\">\n <RegistrationInfo>\n <Description>tsPLC plant agent: deploys to the controller and runs the line's server</Description>\n </RegistrationInfo>\n <Triggers>\n <BootTrigger>\n <Enabled>true</Enabled>\n </BootTrigger>\n </Triggers>\n <Principals>\n <Principal id=\"Author\">\n <UserId>${escapeXml(task.user)}</UserId>\n <LogonType>Password</LogonType>\n <RunLevel>LeastPrivilege</RunLevel>\n </Principal>\n </Principals>\n <Settings>\n <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>\n <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>\n <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>\n <AllowHardTerminate>true</AllowHardTerminate>\n <StartWhenAvailable>true</StartWhenAvailable>\n <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>\n <IdleSettings>\n <StopOnIdleEnd>false</StopOnIdleEnd>\n <RestartOnIdle>false</RestartOnIdle>\n </IdleSettings>\n <AllowStartOnDemand>true</AllowStartOnDemand>\n <Enabled>true</Enabled>\n <Hidden>false</Hidden>\n <RunOnlyIfIdle>false</RunOnlyIfIdle>\n <WakeToRun>false</WakeToRun>\n <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>\n <Priority>7</Priority>\n <RestartOnFailure>\n <Interval>PT1M</Interval>\n <Count>999</Count>\n </RestartOnFailure>\n </Settings>\n <Actions Context=\"Author\">\n <Exec>\n <Command>${escapeXml(task.bun)}</Command>\n <Arguments>${escapeXml(argumentsText)}</Arguments>\n <WorkingDirectory>${escapeXml(task.workingDirectory)}</WorkingDirectory>\n </Exec>\n </Actions>\n</Task>\n`;\n};\n\n/** A task definition as `schtasks /XML` reads it: UTF-16 with a byte order mark. */\nexport const taskFile = (definition: string) =>\n\tBuffer.concat([\n\t\tBuffer.from([0xff, 0xfe]),\n\t\tBuffer.from(definition, \"utf16le\"),\n\t]);\n\n/** The schtasks commands the service's lifecycle runs, as Task Scheduler names them. */\nexport const schtasks = {\n\t/** Registers `file` as `user`; schtasks asks for the password, which it keeps for boot. */\n\tcreate: (file: string, user: string) => [\n\t\t\"schtasks\",\n\t\t\"/Create\",\n\t\t\"/TN\",\n\t\tserviceName,\n\t\t\"/XML\",\n\t\tfile,\n\t\t\"/RU\",\n\t\tuser,\n\t\t\"/RP\",\n\t\t\"*\",\n\t\t\"/F\",\n\t],\n\trun: () => [\"schtasks\", \"/Run\", \"/TN\", serviceName],\n\tend: () => [\"schtasks\", \"/End\", \"/TN\", serviceName],\n\tremove: () => [\"schtasks\", \"/Delete\", \"/TN\", serviceName, \"/F\"],\n\tquery: () => [\"schtasks\", \"/Query\", \"/TN\", serviceName, \"/FO\", \"LIST\", \"/V\"],\n};\n\n/** An agent that ran this long before it failed is started again at once. */\nconst steadyMs = 60_000;\n\n/** How long `service run` waits before starting an agent that failed again. */\nexport const restartDelay = (exits: {\n\t/** How long the agent that failed ran. */\n\tranMs: number;\n\t/** How many agents in a row, this one included, failed within `steadyMs` of starting. */\n\tquickExits: number;\n}) => {\n\tif (exits.ranMs >= steadyMs) {\n\t\treturn 1000;\n\t}\n\treturn Math.min(5000 * 2 ** (exits.quickExits - 1), 60_000);\n};\n\nconst stampedLine = (message: string) =>\n\t`${new Date().toISOString()} ${message}\\n`;\n\n/** Appends a timestamped line to the agent log. */\nconst logLine = (file: string, message: string) =>\n\tappendFile(file, stampedLine(message));\n\n/**\n * Runs `serve` with `arguments`, writing its output to `log`, and starts it again whenever it\n * exits: at once when it exits to be restarted, as after an upgrade, which re-reads the installed\n * agent; after a growing delay when it fails; never when it exits as asked to stop.\n */\nexport const superviseAgent = async (options: {\n\tcommand: string[];\n\tlog: string;\n\t/** The environment the agent runs in, which also says it is supervised. */\n\tenvironment: Environment;\n\t/** Waits between restarts; real time by default. */\n\twait?: (milliseconds: number) => Promise<unknown>;\n}) => {\n\tconst wait = options.wait ?? delay;\n\tlet quickExits = 0;\n\twhile (true) {\n\t\tconst started = Date.now();\n\t\tconst child = spawnWithLog(options.command, options.log, {\n\t\t\tenv: { ...options.environment, [supervisedEnv]: \"1\" },\n\t\t\theading: stampedLine(`Starting ${options.command.join(\" \")}`),\n\t\t});\n\t\tconst status = await child.exited;\n\t\tconst ranMs = Date.now() - started;\n\t\tif (status === 0) {\n\t\t\tawait logLine(options.log, \"The agent stopped as asked\");\n\t\t\treturn;\n\t\t}\n\t\tif (status === restartStatus) {\n\t\t\tquickExits = 0;\n\t\t\tawait logLine(options.log, \"The agent exited to restart\");\n\t\t\tcontinue;\n\t\t}\n\t\tquickExits = ranMs < steadyMs ? quickExits + 1 : 0;\n\t\tconst pause = restartDelay({ ranMs, quickExits });\n\t\tawait logLine(\n\t\t\toptions.log,\n\t\t\t`The agent exited (${status}); starting it again in ${pause / 1000} s`,\n\t\t);\n\t\tawait wait(pause);\n\t}\n};\n",
42
+ "import { z } from \"zod\";\nimport type { AgentControl, Instance } from \"./instance\";\n\n/** A version or dist-tag of @tsplc/agent, which goes into an install command. */\nexport const versionSchema = z\n\t.string()\n\t.regex(\n\t\t/^[0-9A-Za-z][0-9A-Za-z.+-]*$/,\n\t\t\"Name a version, such as 0.5.0, or a dist-tag, such as latest\",\n\t);\n\n/** The package manager whose global install holds the running agent. */\nexport type PackageManager = \"bun\" | \"npm\";\n\nconst normalize = (path: string) =>\n\tpath.replaceAll(\"\\\\\", \"/\").replace(/\\/+$/, \"\").toLowerCase();\n\n/**\n * The package manager whose global install holds the agent package at `packagePath`, such as\n * `C:\\Users\\plant\\.bun\\install\\global\\node_modules\\@tsplc\\agent`, or null for a project or\n * source checkout, which `upgrade` leaves to whoever installed it. `npmGlobalRoot` is\n * `npm root --global`, or null without npm.\n */\nexport const packageManagerFor = (\n\tpackagePath: string,\n\tnpmGlobalRoot: string | null,\n): PackageManager | null => {\n\tconst path = normalize(packagePath);\n\tif (path.endsWith(\"/install/global/node_modules/@tsplc/agent\")) {\n\t\treturn \"bun\";\n\t}\n\tif (\n\t\tnpmGlobalRoot !== null &&\n\t\tpath === `${normalize(npmGlobalRoot)}/@tsplc/agent`\n\t) {\n\t\treturn \"npm\";\n\t}\n\treturn null;\n};\n\n/** npm with `args` on `platform`, where npm is a batch file on Windows that only cmd runs. */\nexport const npmCommand = (platform: NodeJS.Platform, ...args: string[]) =>\n\tplatform === \"win32\"\n\t\t? [\"cmd.exe\", \"/d\", \"/s\", \"/c\", \"npm\", ...args]\n\t\t: [\"npm\", ...args];\n\n/** The command that installs @tsplc/agent at `version` globally with `manager`. */\nexport const installCommand = (\n\tmanager: PackageManager,\n\tversion: string,\n\thost: { bun: string; platform: NodeJS.Platform },\n) => {\n\t// The spec reaches cmd on Windows, so it is only ever a version or tag.\n\tconst spec = `@tsplc/agent@${versionSchema.parse(version)}`;\n\tif (manager === \"bun\") {\n\t\treturn [host.bun, \"add\", \"--global\", spec];\n\t}\n\treturn npmCommand(host.platform, \"install\", \"--global\", spec);\n};\n\n/** What `upgrade` does to the system, so its sequence can be followed without one. */\nexport interface UpgradeEffects {\n\t/** Runs a command on this terminal and returns its exit status. */\n\trun: (command: string[]) => Promise<number>;\n\t/** The version of the agent package now installed. */\n\tinstalledVersion: () => Promise<string>;\n\t/** Starts an agent that no service starts again, once `instance` has exited. */\n\tstartAgent: (instance: Instance) => Promise<void>;\n\t/** Starts the installed service; false when none is installed. */\n\tstartService: () => Promise<boolean>;\n\t/** Whether an agent of `version` answers within a few minutes. */\n\tanswers: (version: string) => Promise<boolean>;\n\tprint: (line: string) => void;\n}\n\n/**\n * Installs another version of the agent and runs it, without interrupting a deployment, touching\n * the controller or stopping the line's server. A running agent is held first, which fails while\n * an operation runs or a login is open, then installs, runs the new version's setup (nothing,\n * unless its image recipe changed), and is replaced by the new version, which takes over the\n * line's server and starts CODESYS again with its own code.\n */\nexport const upgradeAgent = async (\n\trequest: {\n\t\tversion: string;\n\t\tinstall: string[];\n\t\t/** The installed version's setup, which builds only images that need it. */\n\t\tsetup: string[];\n\t\trunning: { instance: Instance; control: AgentControl } | null;\n\t\t/** Where an agent `upgrade` starts writes its output. */\n\t\tagentLog: string;\n\t},\n\teffects: UpgradeEffects,\n) => {\n\tconst { running } = request;\n\tif (running) {\n\t\teffects.print(\n\t\t\t`Holding tsplc-agent ${running.instance.version} (process ${running.instance.pid}): it takes no deployments or logins until the new version runs`,\n\t\t);\n\t\tawait running.control.hold();\n\t}\n\tconst installed = await (async () => {\n\t\tif ((await effects.run(request.install)) !== 0) {\n\t\t\tthrow new Error(\n\t\t\t\t`Installing @tsplc/agent@${request.version} failed; see the output above`,\n\t\t\t);\n\t\t}\n\t\tconst version = await effects.installedVersion();\n\t\tif (running?.instance.version === version) {\n\t\t\treturn null;\n\t\t}\n\t\teffects.print(`Installed tsplc-agent ${version}; checking its images`);\n\t\tif ((await effects.run(request.setup)) !== 0) {\n\t\t\tthrow new Error(\n\t\t\t\t`tsplc-agent ${version} is installed, but its setup failed; see the output above. Run tsplc-agent upgrade ${version} again once it can`,\n\t\t\t);\n\t\t}\n\t\treturn version;\n\t})().catch(async (error: unknown) => {\n\t\tawait running?.control.releaseHold();\n\t\tthrow error;\n\t});\n\tif (installed === null) {\n\t\tawait running?.control.releaseHold();\n\t\teffects.print(\n\t\t\t`tsplc-agent ${running?.instance.version} is installed and running already`,\n\t\t);\n\t\treturn;\n\t}\n\tif (!running) {\n\t\tif (!(await effects.startService())) {\n\t\t\teffects.print(\n\t\t\t\t`tsplc-agent ${installed} is installed. No agent was running: start it with tsplc-agent serve, or install the service with tsplc-agent service install`,\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\teffects.print(\"Started the tsplc-agent service\");\n\t} else {\n\t\teffects.print(\n\t\t\t`Restarting the agent; the line's server keeps running and CODESYS starts again in the background`,\n\t\t);\n\t\tawait running.control.exit({ server: \"leave\", restart: true });\n\t\tif (!running.instance.supervised) {\n\t\t\tawait effects.startAgent(running.instance);\n\t\t}\n\t}\n\tif (!(await effects.answers(installed))) {\n\t\tthrow new Error(\n\t\t\t`tsplc-agent ${installed} is installed but doesn't answer; see ${request.agentLog}`,\n\t\t);\n\t}\n\teffects.print(`tsplc-agent ${installed} is running`);\n};\n",
43
+ "import {\n\tcontrollerCredentialsSchema,\n\tcontrollerIdsSchema,\n\tloginStateSchema,\n\tonlineChangeFindingSchema,\n\trollbackSchema,\n} from \"@tsplc/build\";\nimport { plainValue, secretValue, tsplcConfigSchema } from \"@tsplc/config\";\nimport { envName, releaseConfigSchema, tcpPort } from \"@tsplc/config/build\";\nimport { z } from \"zod\";\nimport { version } from \"../package.json\";\n\n/** The tsPLC version a client and the agent it deploys through must share. */\nexport const tsplcVersion = version;\n\n/** The controller the agent deploys to, as its runtime's TCP block driver address. */\nexport const targetSchema = z.strictObject({\n\thost: z.string().nonempty(),\n\tport: tcpPort,\n});\nexport type Target = z.infer<typeof targetSchema>;\n\nexport const networkInterfaceSchema = z.strictObject({\n\tname: z.string(),\n\taddress: z.ipv4(),\n\tprefixLength: z.number().int().min(0).max(32),\n});\nexport type NetworkInterface = z.infer<typeof networkInterfaceSchema>;\n\n/** A host on the scanned subnet that accepts connections on the CODESYS runtime port. */\nexport const discoveredControllerSchema = z.strictObject({\n\taddress: z.ipv4(),\n\tport: z.number().int(),\n\thostname: z.string().nullable(),\n});\nexport type DiscoveredController = z.infer<typeof discoveredControllerSchema>;\n\n/** `POST /discover`: the network interface to scan for controllers. */\nexport const discoverSchema = z.strictObject({ name: z.string() });\n\n/**\n * The controller's user, which the agent passes to CODESYS for one operation. A request sends\n * null instead to use the one stored on the agent's PC.\n */\nexport type Credentials = z.infer<typeof controllerCredentialsSchema>;\n\n/** A published leaf of the deployed program, as CODESYS expressions name it. */\nexport const variableSchema = z.strictObject({\n\tpath: z.string(),\n\ttype: z.string(),\n});\nexport type Variable = z.infer<typeof variableSchema>;\n\n/** A target's plain values, by variable name. */\nconst targetValuesSchema = z.record(envName, z.string());\n\n/**\n * What `tsplc deploy` uploads beside its files. `config` is the build config with paths\n * relative to the release: `st/`, `template.project` and `libraries/`.\n */\nexport const releaseManifestSchema = z.strictObject({\n\t// Checked against the owner's schema but kept as uploaded: the release id hashes the manifest.\n\tconfig: z.record(z.string(), z.unknown()).superRefine((config, context) => {\n\t\tconst release = releaseConfigSchema.safeParse(config);\n\t\tif (!release.success) {\n\t\t\tcontext.addIssue({\n\t\t\t\tcode: \"custom\",\n\t\t\t\tmessage: `Invalid release config: ${z.prettifyError(release.error)}`,\n\t\t\t});\n\t\t}\n\t}),\n\tvariables: z.array(variableSchema),\n\t/** The server executable's path in the release, when the project builds one. */\n\tserver: z.string().nonempty().optional(),\n\t/** The project's `debug` section; the program's debug manifest is the release's `debug.json`. */\n\tdebug: tsplcConfigSchema.shape.debug,\n\t/** The variable in the agent's environment holding the server's bearer token, for its telemetry and request trace. */\n\tserverTokenEnv: z.string().nonempty().optional(),\n\t/** The project's `secrets`, whose placeholders in the ST the agent fills in from Bun.secrets. */\n\tsecrets: tsplcConfigSchema.shape.secrets,\n\t/** The values of the target it was built for, which its server starts with; none in a release from before 0.5.12. */\n\tvalues: targetValuesSchema.default({}),\n});\nexport type ReleaseManifest = z.infer<typeof releaseManifestSchema>;\n\n/** How `tsplc deploy` compresses each file of a multipart upload, the only form agents without `POST /releases/compare` accept. */\nexport const uploadEncoding = \"gzip\";\n\n/** The commit a deployment was built from, when `tsplc deploy` ran in a git checkout. */\nexport const gitSourceSchema = z.strictObject({\n\tcommit: z.string().nonempty(),\n\tbranch: z.string().nullable(),\n\t/** Uncommitted changes went into the build. */\n\tdirty: z.boolean(),\n\t/** The commit's subject line. */\n\tmessage: z.string().nullable(),\n});\nexport type GitSource = z.infer<typeof gitSourceSchema>;\n\n/**\n * How a deployment applies: `apply` runs it as soon as it is its turn; `review` builds it and\n * checks what an online change would do, then waits for someone to approve it.\n */\nexport const deploymentModeSchema = z.enum([\"apply\", \"review\"]);\nexport type DeploymentMode = z.infer<typeof deploymentModeSchema>;\n\n/**\n * What `tsplc deploy` sends with a release to `POST /api/deployments`, in the upload's `options`\n * beside the existing deploy options.\n */\nexport const deploymentRequestSchema = z.strictObject({\n\tmode: deploymentModeSchema,\n\tgit: gitSourceSchema.nullable(),\n});\n\nexport const deployOptionsSchema = z\n\t.strictObject({\n\t\tcredentials: controllerCredentialsSchema.nullable(),\n\t\t/** A full download stops the application; without it only an online change is applied. */\n\t\tdownload: z.boolean(),\n\t\tinitializeUser: z.boolean(),\n\t\t/** How `POST /api/deployments` queues it; `POST /deploy` runs it at once and ignores this. */\n\t\tdeployment: deploymentRequestSchema.optional(),\n\t})\n\t.refine(\n\t\t(options) => options.credentials || !options.initializeUser,\n\t\t\"Initializing the controller's user needs the user's credentials.\",\n\t);\nexport type DeployOptions = z.infer<typeof deployOptionsSchema>;\n\n/** How many buckets a release's files fall into for `POST /releases/compare`. */\nexport const releaseBuckets = 256;\n\n/** A release id, or the start of a SHA-256 of content: 16 lowercase hex digits. */\nconst shortHex = z.string().regex(/^[a-f0-9]{16}$/);\n\n/** `POST /releases/compare`: the digest of each bucket of the release about to be deployed. */\nexport const compareRequestSchema = z.strictObject({\n\tbuckets: z.array(shortHex).length(releaseBuckets),\n});\n\n/**\n * Its answer: the stored release the upload can build on, and that release's files, by path and\n * digest, in each bucket that differs. Without a base the whole release is uploaded.\n */\nexport const comparisonSchema = z.strictObject({\n\tbase: shortHex.nullable(),\n\tchanged: z.array(\n\t\tz.strictObject({\n\t\t\tbucket: z\n\t\t\t\t.number()\n\t\t\t\t.int()\n\t\t\t\t.min(0)\n\t\t\t\t.max(releaseBuckets - 1),\n\t\t\tfiles: z.record(z.string(), shortHex),\n\t\t}),\n\t),\n});\nexport type Comparison = z.infer<typeof comparisonSchema>;\n\n/** A `POST /deploy` body in this form is one release upload rather than a multipart form. */\nexport const releaseUploadType = \"application/vnd.tsplc.release+zstd\";\n\n/**\n * A release upload's header. The release is `base`'s files without the `remove` paths, with the\n * uploaded files added or replacing theirs; `buckets` are the digests it must then have.\n */\nexport const releaseUploadSchema = z.strictObject({\n\tmanifest: releaseManifestSchema,\n\toptions: deployOptionsSchema,\n\tbase: shortHex.nullable(),\n\tbuckets: compareRequestSchema.shape.buckets,\n\tremove: z.array(z.string()),\n});\nexport type ReleaseUpload = z.infer<typeof releaseUploadSchema>;\n\n/** Long operations stream one of these per line. */\nexport const eventSchema = z.discriminatedUnion(\"kind\", [\n\tz.strictObject({ kind: z.literal(\"progress\"), message: z.string() }),\n\tz.strictObject({ kind: z.literal(\"done\"), result: z.unknown() }),\n\tz.strictObject({\n\t\tkind: z.literal(\"error\"),\n\t\tmessage: z.string(),\n\t\t/** The controller has no application from this agent yet, so only a full download can deploy. */\n\t\tdownloadRequired: z.boolean(),\n\t\t/**\n\t\t * What became of the controller after a download failed mid-transfer. Sent only to clients that\n\t\t * send their version, since earlier clients reject an event with fields they don't know.\n\t\t */\n\t\trollback: rollbackSchema.optional(),\n\t}),\n]);\nexport type AgentEvent = z.infer<typeof eventSchema>;\n\nconst deployOperationSchema = z.enum([\"download\", \"online-change\"]);\n\nexport const releaseSchema = z.strictObject({\n\tid: z.string(),\n\tdeployedAt: z.iso.datetime(),\n\toperation: deployOperationSchema,\n\tcontrollerIds: controllerIdsSchema,\n\t/** The running server executable, relative to the releases directory. */\n\tserver: z.string().optional(),\n});\nexport type Release = z.infer<typeof releaseSchema>;\n\nexport const statusSchema = z.strictObject({\n\ttarget: targetSchema.nullable(),\n\trelease: releaseSchema.nullable(),\n\tserver: z\n\t\t.strictObject({ executable: z.string(), running: z.boolean() })\n\t\t.nullable(),\n\t/** The open login's application state and forced expressions, or why it can't report them. */\n\tlogin: z\n\t\t.union([loginStateSchema, z.strictObject({ error: z.string() })])\n\t\t.nullable(),\n\t/** A controller user is stored on the agent's PC, so requests may leave theirs out. */\n\tcredentialsStored: z.boolean(),\n});\nexport type AgentStatus = z.infer<typeof statusSchema>;\n\n/** The agent's status, which names the agent's version even to a request it refuses. */\nexport const statusPath = \"/status\";\n\n/** `POST` holds the agent for an upgrade, so it takes no operations; `DELETE` lets it take them again. */\nexport const agentHoldPath = \"/agent/hold\";\n\n/** `POST`: a held agent exits, as `exitSchema` asks. */\nexport const agentExitPath = \"/agent/exit\";\n\n/**\n * How a held agent exits: leaving the line's server running for the next agent or stopping it,\n * and whether whatever started it should start it again.\n */\nexport const exitSchema = z.strictObject({\n\tserver: z.enum([\"leave\", \"stop\"]),\n\trestart: z.boolean(),\n});\nexport type AgentExit = z.infer<typeof exitSchema>;\n\n/** A logout's result: why the login couldn't log out, when its container had to be removed instead. */\nexport const logoutSchema = z.strictObject({ failure: z.string().optional() });\n\n/** Who ran a command, and with which tsPLC, as the client reports it in these headers. */\nexport const clientHeaders = {\n\tuser: \"x-tsplc-user\",\n\thost: \"x-tsplc-host\",\n\tversion: \"x-tsplc-version\",\n\t/** The client's `workerScriptsDigest`, which tells a local build from a release of its version. */\n\tscripts: \"x-tsplc-scripts\",\n} as const;\n\n/** The header each agent response names the agent's tsPLC version in; agents before 0.3.0 send none. */\nexport const agentVersionHeader = \"x-tsplc-agent-version\";\n\n/** Whether `version` is at least `minimum`, comparing major, minor and patch. */\nconst atLeast = (version: string, minimum: [number, number, number]) => {\n\tconst parts = version.split(/[.+-]/).slice(0, 3).map(Number);\n\tfor (const [index, wanted] of minimum.entries()) {\n\t\tconst part = parts[index] ?? 0;\n\t\tif (part !== wanted) {\n\t\t\treturn part > wanted;\n\t\t}\n\t}\n\treturn true;\n};\n\n/** Whether an agent of `version` has `tsplc-agent upgrade`, which arrived in 0.5.0. */\nexport const upgradesItself = (version: string | null) =>\n\tversion !== null && atLeast(version, [0, 5, 0]);\n\n/** Why a client and an agent of different tsPLC versions don't deploy, and what to do about it. */\nexport const versionMismatch = (versions: {\n\tagent: string | null;\n\tclient: string;\n\t/** The agent has `tsplc-agent upgrade`. */\n\tagentUpgrades: boolean;\n}) =>\n\t`The plant agent runs ${versions.agent ? `tsPLC ${versions.agent}` : \"a tsPLC older than 0.3.0\"}, but this deployment comes from tsPLC ${versions.client}. A release is compiled by the agent's own CODESYS scripts, so the two must match: on the plant PC, run ${versions.agentUpgrades ? `tsplc-agent upgrade ${versions.client}` : `bun add --global @tsplc/agent@${versions.client}, then restart tsplc-agent serve`}${versions.agent ? `, or deploy with tsPLC ${versions.agent}` : \"\"}`;\n\n/** Who sent a request, as the client reports it. */\nexport const clientIdentity = (request: Request) => {\n\tconst header = (name: string) =>\n\t\trequest.headers.get(name)?.slice(0, 200) || undefined;\n\treturn { user: header(clientHeaders.user), host: header(clientHeaders.host) };\n};\nexport type ClientIdentity = ReturnType<typeof clientIdentity>;\n\n/** The tsPLC a request's client runs, as it reports it; clients before 0.3.0 report none. */\nexport const clientRelease = (request: Request) => ({\n\tversion:\n\t\trequest.headers.get(clientHeaders.version)?.slice(0, 50) || undefined,\n\tscripts:\n\t\trequest.headers.get(clientHeaders.scripts)?.slice(0, 100) || undefined,\n});\nexport type ClientRelease = ReturnType<typeof clientRelease>;\n\n/** A line of the agent's `deployments.jsonl`. */\nexport const deploymentSchema = z.strictObject({\n\tat: z.iso.datetime(),\n\trelease: z.string(),\n\t/** The debug manifest's build id, when the release has one. */\n\tbuild: z.string().optional(),\n\toperation: deployOperationSchema,\n\t/** Whether the request sent the controller user or the agent used its stored one; lines from before 0.2.18 lack it. */\n\tcredentials: z.enum([\"provided\", \"stored\"]).optional(),\n\tuser: z.string().optional(),\n\thost: z.string().optional(),\n});\nexport type Deployment = z.infer<typeof deploymentSchema>;\n\n/** A line of the agent's `audit.jsonl`: a login command that changed the controller. */\nexport const auditSchema = z.strictObject({\n\tat: z.iso.datetime(),\n\t/** As typed after `tsplc`, such as `force` or `reset cold`. */\n\tcommand: z.string(),\n\t/** Expressions written or forced, with their values; unforced expressions map to \"\". */\n\tvalues: z.record(z.string(), z.string()),\n\t/** The values read just before the command, when the read succeeded. */\n\tprevious: z.record(z.string(), z.string()).optional(),\n\tuser: z.string().optional(),\n\thost: z.string().optional(),\n\trelease: z.string().optional(),\n\terror: z.string().optional(),\n});\nexport type Audit = z.infer<typeof auditSchema>;\n\n/**\n * Who may do what on the agent's dashboard and API, each role including the ones before it: a\n * viewer reads deployments, logs, the debugger and the audit log; a deployer also deploys,\n * approves, cancels, redeploys, rolls back and restarts the server; an admin also manages the\n * environment's secrets and who has which role.\n */\nexport const roles = [\"viewer\", \"deployer\", \"admin\"] as const;\nexport const roleSchema = z.enum(roles);\nexport type Role = z.infer<typeof roleSchema>;\n\nexport const allows = (role: Role, required: Role) =>\n\troles.indexOf(role) >= roles.indexOf(required);\n\n/** Who made a request, and how the agent knows. */\nexport const identitySchema = z.strictObject({\n\t/** The Tailscale login, or null for a token or a request from the agent's own PC. */\n\tlogin: z.string().nullable(),\n\t/** A name to show: the Tailscale display name, or how the token or PC is known. */\n\tname: z.string(),\n\trole: roleSchema,\n\t/** `server`: the deployed server, with the token the agent started it with. */\n\tvia: z.enum([\"tailscale\", \"token\", \"local\", \"server\"]),\n});\nexport type Identity = z.infer<typeof identitySchema>;\n\n/**\n * Where a deployment is. `awaitingApproval` waits on a person: a review to apply, or a full\n * download that would stop the line. A finished deployment is `ready`, `error` or `canceled`.\n */\nexport const deploymentStateSchema = z.enum([\n\t\"queued\",\n\t\"building\",\n\t\"awaitingApproval\",\n\t\"applying\",\n\t\"starting\",\n\t\"verifying\",\n\t\"ready\",\n\t\"error\",\n\t\"canceled\",\n]);\nexport type DeploymentState = z.infer<typeof deploymentStateSchema>;\n\n/** States a deployment never leaves. */\nexport const finalStates: readonly DeploymentState[] = [\n\t\"ready\",\n\t\"error\",\n\t\"canceled\",\n];\n\n/** States a deployment may still be canceled in: anything before it applies. */\nexport const cancelableStates: readonly DeploymentState[] = [\n\t\"queued\",\n\t\"building\",\n\t\"awaitingApproval\",\n];\n\n/** The steps a deployment goes through, in order; a deployment skips the ones it doesn't need. */\nexport const deploymentPhaseNameSchema = z.enum([\n\t\"queue\",\n\t\"build\",\n\t\"review\",\n\t\"apply\",\n\t\"server\",\n\t\"health\",\n]);\n\nconst deploymentIdSchema = z.string().regex(/^dpl_[a-z0-9]{16,32}$/);\n\n/**\n * A deployment as the agent keeps it, in `deployments/<id>/record.json` of its state directory.\n * Every record of the last 14 days is kept, and always the running one and the last that was\n * healthy, with their releases.\n */\nexport const deploymentRecordSchema = z.strictObject({\n\tid: deploymentIdSchema,\n\trelease: z.string(),\n\t/** The debug manifest's build id, when the release has one. */\n\tbuild: z.string().nullable(),\n\tcreatedAt: z.iso.datetime(),\n\tupdatedAt: z.iso.datetime(),\n\t/** An upload from `tsplc deploy`, or a release the agent already had, deployed again. */\n\torigin: z.discriminatedUnion(\"kind\", [\n\t\tz.strictObject({ kind: z.literal(\"upload\") }),\n\t\tz.strictObject({ kind: z.literal(\"redeploy\"), from: deploymentIdSchema }),\n\t\tz.strictObject({ kind: z.literal(\"rollback\"), from: deploymentIdSchema }),\n\t]),\n\tgit: gitSourceSchema.nullable(),\n\t/** Who asked for it: the identity behind the request, with the deploying machine's user and host. */\n\trequestedBy: z.strictObject({\n\t\tidentity: identitySchema.omit({ role: true }),\n\t\tuser: z.string().nullable(),\n\t\thost: z.string().nullable(),\n\t}),\n\tmode: deploymentModeSchema,\n\t/** What it applies or applied: an online change unless a full download was asked for or approved. */\n\toperation: deployOperationSchema,\n\tstate: deploymentStateSchema,\n\tphases: z.array(\n\t\tz.strictObject({\n\t\t\tname: deploymentPhaseNameSchema,\n\t\t\tstartedAt: z.iso.datetime(),\n\t\t\tfinishedAt: z.iso.datetime().nullable(),\n\t\t\toutcome: z.enum([\"running\", \"ok\", \"failed\", \"skipped\"]),\n\t\t}),\n\t),\n\t/** What the online-change check found: refusals, and what the change restarts. */\n\tfindings: z.array(onlineChangeFindingSchema),\n\t/** What it waits on while `awaitingApproval`. */\n\tapproval: z\n\t\t.strictObject({\n\t\t\treason: z.enum([\"review\", \"downloadRequired\"]),\n\t\t\tmessage: z.string(),\n\t\t})\n\t\t.nullable(),\n\terror: z\n\t\t.strictObject({\n\t\t\tmessage: z.string(),\n\t\t\tdownloadRequired: z.boolean(),\n\t\t\trollback: rollbackSchema.optional(),\n\t\t})\n\t\t.nullable(),\n\tcontrollerIds: controllerIdsSchema.nullable(),\n\t/** What the check after applying found; null until it ran. */\n\thealth: z\n\t\t.strictObject({\n\t\t\tcontroller: z.enum([\"ok\", \"failed\"]),\n\t\t\tserver: z.enum([\"ok\", \"failed\", \"none\"]),\n\t\t\tplc: z.enum([\"ok\", \"failed\", \"unknown\"]),\n\t\t\tdetail: z.string().nullable(),\n\t\t})\n\t\t.nullable(),\n\t/** When it became the running deployment, and when another replaced it; null until and while. */\n\tactiveFrom: z.iso.datetime().nullable(),\n\tactiveUntil: z.iso.datetime().nullable(),\n});\nexport type DeploymentRecord = z.infer<typeof deploymentRecordSchema>;\n\n/** One line of a deployment's log, `deployments/<id>/log.jsonl`. */\nexport const deploymentLogLineSchema = z.strictObject({\n\t/** Counts from 1 within the deployment; `?after=` resumes from it. */\n\tseq: z.number().int().positive(),\n\tat: z.iso.datetime(),\n\tlevel: z.enum([\"info\", \"warning\", \"error\"]),\n\tphase: deploymentPhaseNameSchema.nullable(),\n\tmessage: z.string(),\n});\nexport type DeploymentLogLine = z.infer<typeof deploymentLogLineSchema>;\n\n/** A change to a deployment, as its subscribers and its server-sent events carry it. */\nexport type DeploymentEvent =\n\t| { kind: \"record\"; record: DeploymentRecord }\n\t| { kind: \"log\"; line: DeploymentLogLine };\n\n/** The deployments API: `POST` queues a release, `GET` lists the deployments. */\nexport const deploymentsApiPath = \"/api/deployments\";\n\n/** Deployment `id` in the deployments API; its actions and views are below it. */\nexport const deploymentApiPath = (id: string) =>\n\t`${deploymentsApiPath}/${encodeURIComponent(id)}`;\n\n/** Deployment `id`'s page on the dashboard. */\nexport const deploymentPagePath = (id: string) =>\n\t`/deployments/${encodeURIComponent(id)}`;\n\n/** Where the agent serves the debugger. */\nexport const debuggerMount = \"/debug/\";\n\n/** `POST /api/deployments`'s answer: the queued deployment and the dashboard page that shows it. */\nexport const deploymentCreatedSchema = z.strictObject({\n\tid: deploymentIdSchema,\n\turl: z.string(),\n});\n\n/** `GET /api/deployments`: newest first, with the running and last healthy ones named. */\nexport const deploymentListSchema = z.strictObject({\n\tdeployments: z.array(deploymentRecordSchema),\n\tcurrent: deploymentIdSchema.nullable(),\n\tlastGood: deploymentIdSchema.nullable(),\n});\n\n/** `POST /api/deployments/:id/approve`: apply it, as a full download when one is required. */\nexport const approveSchema = z.strictObject({ download: z.boolean() });\n\n/** `POST /api/deployments/:id/redeploy`: deploy its release again. */\nexport const redeploySchema = z.strictObject({ mode: deploymentModeSchema });\n\n/** `GET /api/deployments/:id/source`: the release's files, by path, with their sizes in bytes. */\nexport const deploymentSourceSchema = z.strictObject({\n\tfiles: z.array(\n\t\tz.strictObject({ path: z.string(), size: z.number().int().nonnegative() }),\n\t),\n});\n\n/** A secret the deployed release's config declares, or one stored without a declaration: never its value. */\nconst environmentEntrySchema = z.strictObject({\n\tname: z.string(),\n\tdeclared: z.boolean(),\n\tset: z.boolean(),\n});\nexport type EnvironmentEntry = z.infer<typeof environmentEntrySchema>;\n\n/** `GET /api/environment`: the plant PC's variables, and what the running release was built with. */\nexport const environmentSchema = z.strictObject({\n\t/** The plain values the running release was built with, from the config's target and this PC. */\n\tvalues: targetValuesSchema,\n\t/** The plain variables stored on this PC, which the next deployment is built with. */\n\tvariables: z.record(envName, z.string()),\n\tsecrets: z.array(environmentEntrySchema),\n});\nexport type EnvironmentListing = z.infer<typeof environmentSchema>;\n\n/**\n * `access.json` in the agent's state directory, and the body of `GET` and `PUT /api/access`: the\n * role of each Tailscale login, and the role a tailnet member without one gets, none by default.\n */\nexport const accessConfigSchema = z.strictObject({\n\troles: z.record(z.string().nonempty(), roleSchema),\n\ttailnetDefault: roleSchema.nullable(),\n});\nexport type AccessConfig = z.infer<typeof accessConfigSchema>;\n\n/** `POST /api/session`: the agent's full or read token, which signs a browser in. */\nexport const sessionRequestSchema = z.strictObject({ token: z.string() });\n\n/** `PUT /api/environment/:name`: a plain variable's new value, shown and built with, or a secret's. */\nexport const environmentValueSchema = z.discriminatedUnion(\"secret\", [\n\tz.strictObject({ secret: z.literal(false), value: plainValue }),\n\tz.strictObject({ secret: z.literal(true), value: secretValue }),\n]);\nexport type EnvironmentValue = z.infer<typeof environmentValueSchema>;\n",
44
+ "import { randomBytes } from \"node:crypto\";\nimport { mkdir, readFile, rm, writeFile } from \"node:fs/promises\";\nimport { dirname, join, relative } from \"node:path\";\nimport {\n\ttype agentTokenEnv,\n\ttype Environment,\n\tsecretPlaceholder,\n\tsecretValue,\n} from \"@tsplc/config\";\nimport type { ResolvedConfig } from \"@tsplc/config/build\";\nimport { escapeString } from \"@tsplc/iec/st\";\nimport { AgentError } from \"./errors\";\nimport type { Credentials, ReleaseManifest } from \"./protocol\";\nimport type { StoredRelease } from \"./releases\";\n\n/** The agent's own Bun.secrets service, which holds the controller user and the agent's tokens. */\nexport const agentService = \"tsplc-agent\";\n/** Where the dashboard stores the environment's secrets while the deployed release declares none. */\nexport const environmentService = \"tsplc-agent-env\";\n/** The token that only reads from the agent. */\nexport const agentReadTokenEnv = \"TSPLC_AGENT_READ_TOKEN\";\nexport const controllerSecretNames = {\n\tusername: \"controller-username\",\n\tpassword: \"controller-password\",\n};\n\n/** Agent setting `name`: its variable in `environment` when set, otherwise the value stored under the agent's service, or null. */\nexport const agentSetting = async (\n\tname: typeof agentTokenEnv | typeof agentReadTokenEnv,\n\tenvironment: Environment,\n) =>\n\tenvironment[name] ?? (await Bun.secrets.get({ service: agentService, name }));\n\n/**\n * The token the deployed server is started with, made once and kept under the agent's service, so\n * a server an earlier agent started still has a valid one.\n */\nexport const serverToken = async () => {\n\tconst name = \"server-token\";\n\tconst stored = await Bun.secrets.get({ service: agentService, name });\n\tif (stored) {\n\t\treturn stored;\n\t}\n\tconst token = randomBytes(32).toString(\"hex\");\n\tawait Bun.secrets.set({ service: agentService, name, value: token });\n\treturn token;\n};\n\n/** The controller user stored with `tsplc-agent secrets set-controller`, or null. */\nexport const storedCredentials = async (): Promise<Credentials | null> => {\n\tconst [username, password] = await Promise.all([\n\t\tBun.secrets.get({\n\t\t\tservice: agentService,\n\t\t\tname: controllerSecretNames.username,\n\t\t}),\n\t\tBun.secrets.get({\n\t\t\tservice: agentService,\n\t\t\tname: controllerSecretNames.password,\n\t\t}),\n\t]);\n\treturn username && password ? { username, password } : null;\n};\n\n/** The controller user a request sent, or the stored one when it sent null. */\nexport const controllerCredentials = async (sent: Credentials | null) => {\n\tconst credentials = sent ?? (await storedCredentials());\n\tif (!credentials) {\n\t\tthrow new AgentError(\n\t\t\t\"No controller user is stored on the plant PC: run tsplc-agent secrets set-controller there\",\n\t\t\t409,\n\t\t);\n\t}\n\treturn credentials;\n};\n\n/** The release's secrets from Bun.secrets, by name. Fails naming every one that is missing. */\nexport const readSecrets = async (secrets: ReleaseManifest[\"secrets\"]) => {\n\tconst values = new Map<string, string>();\n\tif (!secrets) {\n\t\treturn values;\n\t}\n\tconst { service } = secrets;\n\tconst missing: string[] = [];\n\tfor (const name of secrets.names) {\n\t\tconst value = await Bun.secrets.get({ service, name });\n\t\tconst valid = secretValue.safeParse(value);\n\t\tif (!value) {\n\t\t\tmissing.push(name);\n\t\t} else if (!valid.success) {\n\t\t\tthrow new AgentError(\n\t\t\t\t`Secret ${name} in Bun.secrets service ${service} ${valid.error.issues.map((issue) => issue.message).join(\" and \")}`,\n\t\t\t\t409,\n\t\t\t);\n\t\t} else {\n\t\t\tvalues.set(name, value);\n\t\t}\n\t}\n\tif (missing.length) {\n\t\tthrow new AgentError(\n\t\t\t`The plant PC has no ${missing.join(\", \")} in Bun.secrets service ${service}: run tsplc-agent secrets set <name> --service ${service} there`,\n\t\t\t409,\n\t\t);\n\t}\n\treturn values;\n};\n\n/** The release's secrets that Bun.secrets holds, by name. */\nconst storedSecrets = async (secrets: ReleaseManifest[\"secrets\"]) => {\n\tif (!secrets) {\n\t\treturn {};\n\t}\n\tconst stored = await Promise.all(\n\t\tsecrets.names.map(async (name) => ({\n\t\t\tname,\n\t\t\tvalue: await Bun.secrets.get({ service: secrets.service, name }),\n\t\t})),\n\t);\n\treturn Object.fromEntries(\n\t\tstored.flatMap(({ name, value }): [string, string][] =>\n\t\t\tvalue === null ? [] : [[name, value]],\n\t\t),\n\t);\n};\n\n/**\n * The environment the server of `release` runs in, and so what the agent reads a variable of the\n * release's as: `environment`, then the values of the target the release was built for, as the\n * PLC's program got them, then the release's secrets that Bun.secrets holds.\n */\nexport const serverEnvironment = async (\n\t{ manifest }: StoredRelease,\n\tenvironment: Environment,\n): Promise<Environment> => ({\n\t...environment,\n\t...manifest.values,\n\t...(await storedSecrets(manifest.secrets)),\n});\n\n/** Structured Text with each secret's placeholder replaced by its value, inside the STRING literal that holds it. */\nconst fillSecrets = (st: string, secrets: ReadonlyMap<string, string>) =>\n\t[...secrets].reduce(\n\t\t// A replacer function, since a replacement string would read `$'` and `$$` as patterns.\n\t\t(text, [name, value]) =>\n\t\t\ttext.replaceAll(secretPlaceholder(name), () => escapeString(value, \"'\")),\n\t\tst,\n\t);\n\n/** The config with its ST copied to `directory`, the secrets filled in. */\nexport const withSecrets = async (\n\tconfig: ResolvedConfig,\n\tsecrets: ReadonlyMap<string, string>,\n\tdirectory: string,\n): Promise<ResolvedConfig> => {\n\tawait rm(directory, { recursive: true, force: true });\n\tfor await (const path of new Bun.Glob(\"**/*\").scan({\n\t\tcwd: config.sourceDir,\n\t\tdot: true,\n\t})) {\n\t\tconst file = join(directory, path);\n\t\tawait mkdir(dirname(file), { recursive: true });\n\t\tawait writeFile(\n\t\t\tfile,\n\t\t\tfillSecrets(\n\t\t\t\tawait readFile(join(config.sourceDir, path), \"utf8\"),\n\t\t\t\tsecrets,\n\t\t\t),\n\t\t);\n\t}\n\treturn {\n\t\t...config,\n\t\tsourceDir: directory,\n\t\tentry: join(directory, relative(config.sourceDir, config.entry)),\n\t};\n};\n",
45
+ "import { appendFile } from \"node:fs/promises\";\nimport { setTimeout as delay } from \"node:timers/promises\";\nimport type { Environment } from \"@tsplc/config\";\nimport { restartStatus } from \"./instance\";\nimport { spawnWithLog } from \"./logs\";\n\n/** The Task Scheduler task that runs the agent as a service. */\nexport const serviceName = \"tsplc-agent\";\n\n/** Set in the environment of a `serve` that `service run` started, which says so in its record. */\nexport const supervisedEnv = \"TSPLC_AGENT_SUPERVISED\";\n\n/**\n * One argument of a Windows command line, quoted so that a program's C runtime\n * (CommandLineToArgvW) reads it back unchanged: backslashes double only before a quote.\n */\nexport const quoteWindowsArgument = (argument: string) => {\n\tif (argument !== \"\" && !/[\\s\"]/.test(argument)) {\n\t\treturn argument;\n\t}\n\tconst escaped = argument\n\t\t.replace(/(\\\\*)\"/g, '$1$1\\\\\"')\n\t\t.replace(/(\\\\+)$/, \"$1$1\");\n\treturn `\"${escaped}\"`;\n};\n\nconst escapeXml = (text: string) =>\n\ttext\n\t\t.replaceAll(\"&\", \"&amp;\")\n\t\t.replaceAll(\"<\", \"&lt;\")\n\t\t.replaceAll(\">\", \"&gt;\")\n\t\t.replaceAll('\"', \"&quot;\");\n\n/**\n * The Task Scheduler definition of the agent's service: `bun script service run <serve…>` as\n * `user`, at boot whether or not anyone logs on, so the line's server runs after a power cut.\n * The password logon keeps the user's Credential Manager, where Bun.secrets keeps the agent's\n * token, readable. `service run` restarts the agent itself; Task Scheduler restarts `service run`\n * if it fails to start. It runs without a time limit, and only one at a time.\n */\nexport const taskDefinition = (task: {\n\tbun: string;\n\tscript: string;\n\tserve: string[];\n\tuser: string;\n\tworkingDirectory: string;\n}) => {\n\tconst argumentsText = [task.script, \"service\", \"run\", ...task.serve]\n\t\t.map(quoteWindowsArgument)\n\t\t.join(\" \");\n\treturn `<?xml version=\"1.0\" encoding=\"UTF-16\"?>\n<Task version=\"1.4\" xmlns=\"http://schemas.microsoft.com/windows/2004/02/mit/task\">\n <RegistrationInfo>\n <Description>tsPLC plant agent: deploys to the controller and runs the line's server</Description>\n </RegistrationInfo>\n <Triggers>\n <BootTrigger>\n <Enabled>true</Enabled>\n </BootTrigger>\n </Triggers>\n <Principals>\n <Principal id=\"Author\">\n <UserId>${escapeXml(task.user)}</UserId>\n <LogonType>Password</LogonType>\n <RunLevel>LeastPrivilege</RunLevel>\n </Principal>\n </Principals>\n <Settings>\n <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>\n <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>\n <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>\n <AllowHardTerminate>true</AllowHardTerminate>\n <StartWhenAvailable>true</StartWhenAvailable>\n <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>\n <IdleSettings>\n <StopOnIdleEnd>false</StopOnIdleEnd>\n <RestartOnIdle>false</RestartOnIdle>\n </IdleSettings>\n <AllowStartOnDemand>true</AllowStartOnDemand>\n <Enabled>true</Enabled>\n <Hidden>false</Hidden>\n <RunOnlyIfIdle>false</RunOnlyIfIdle>\n <WakeToRun>false</WakeToRun>\n <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>\n <Priority>7</Priority>\n <RestartOnFailure>\n <Interval>PT1M</Interval>\n <Count>999</Count>\n </RestartOnFailure>\n </Settings>\n <Actions Context=\"Author\">\n <Exec>\n <Command>${escapeXml(task.bun)}</Command>\n <Arguments>${escapeXml(argumentsText)}</Arguments>\n <WorkingDirectory>${escapeXml(task.workingDirectory)}</WorkingDirectory>\n </Exec>\n </Actions>\n</Task>\n`;\n};\n\n/** A task definition as `schtasks /XML` reads it: UTF-16 with a byte order mark. */\nexport const taskFile = (definition: string) =>\n\tBuffer.concat([\n\t\tBuffer.from([0xff, 0xfe]),\n\t\tBuffer.from(definition, \"utf16le\"),\n\t]);\n\n/** The schtasks commands the service's lifecycle runs, as Task Scheduler names them. */\nexport const schtasks = {\n\t/** Registers `file` as `user`; schtasks asks for the password, which it keeps for boot. */\n\tcreate: (file: string, user: string) => [\n\t\t\"schtasks\",\n\t\t\"/Create\",\n\t\t\"/TN\",\n\t\tserviceName,\n\t\t\"/XML\",\n\t\tfile,\n\t\t\"/RU\",\n\t\tuser,\n\t\t\"/RP\",\n\t\t\"*\",\n\t\t\"/F\",\n\t],\n\trun: () => [\"schtasks\", \"/Run\", \"/TN\", serviceName],\n\tend: () => [\"schtasks\", \"/End\", \"/TN\", serviceName],\n\tremove: () => [\"schtasks\", \"/Delete\", \"/TN\", serviceName, \"/F\"],\n\tquery: () => [\"schtasks\", \"/Query\", \"/TN\", serviceName, \"/FO\", \"LIST\", \"/V\"],\n};\n\n/** An agent that ran this long before it failed is started again at once. */\nconst steadyMs = 60_000;\n\n/** How long `service run` waits before starting an agent that failed again. */\nexport const restartDelay = (exits: {\n\t/** How long the agent that failed ran. */\n\tranMs: number;\n\t/** How many agents in a row, this one included, failed within `steadyMs` of starting. */\n\tquickExits: number;\n}) => {\n\tif (exits.ranMs >= steadyMs) {\n\t\treturn 1000;\n\t}\n\treturn Math.min(5000 * 2 ** (exits.quickExits - 1), 60_000);\n};\n\nconst stampedLine = (message: string) =>\n\t`${new Date().toISOString()} ${message}\\n`;\n\n/** Appends a timestamped line to the agent log. */\nconst logLine = (file: string, message: string) =>\n\tappendFile(file, stampedLine(message));\n\n/**\n * Runs `serve` with `arguments`, writing its output to `log`, and starts it again whenever it\n * exits: at once when it exits to be restarted, as after an upgrade, which re-reads the installed\n * agent; after a growing delay when it fails; never when it exits as asked to stop.\n */\nexport const superviseAgent = async (options: {\n\tcommand: string[];\n\tlog: string;\n\t/** The environment the agent runs in, which also says it is supervised. */\n\tenvironment: Environment;\n\t/** Waits between restarts; real time by default. */\n\twait?: (milliseconds: number) => Promise<unknown>;\n}) => {\n\tconst wait = options.wait ?? delay;\n\tlet quickExits = 0;\n\twhile (true) {\n\t\tconst started = Date.now();\n\t\tconst child = spawnWithLog(options.command, options.log, {\n\t\t\tenv: { ...options.environment, [supervisedEnv]: \"1\" },\n\t\t\theading: stampedLine(`Starting ${options.command.join(\" \")}`),\n\t\t});\n\t\tconst status = await child.exited;\n\t\tconst ranMs = Date.now() - started;\n\t\tif (status === 0) {\n\t\t\tawait logLine(options.log, \"The agent stopped as asked\");\n\t\t\treturn;\n\t\t}\n\t\tif (status === restartStatus) {\n\t\t\tquickExits = 0;\n\t\t\tawait logLine(options.log, \"The agent exited to restart\");\n\t\t\tcontinue;\n\t\t}\n\t\tquickExits = ranMs < steadyMs ? quickExits + 1 : 0;\n\t\tconst pause = restartDelay({ ranMs, quickExits });\n\t\tawait logLine(\n\t\t\toptions.log,\n\t\t\t`The agent exited (${status}); starting it again in ${pause / 1000} s`,\n\t\t);\n\t\tawait wait(pause);\n\t}\n};\n",
46
+ "import { randomUUID } from \"node:crypto\";\nimport { renameSync, writeFileSync } from \"node:fs\";\nimport { mkdir, readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { z } from \"zod\";\nimport { AgentError } from \"./errors\";\nimport {\n\ttype Release,\n\treleaseSchema,\n\ttype Target,\n\ttargetSchema,\n} from \"./protocol\";\nimport { loadRelease } from \"./releases\";\n\n/** The text of the file at `path`, or null when there is none. Failing to read it is an error. */\nexport const readTextIfPresent = (path: string) =>\n\treadFile(path, \"utf8\").catch((error: unknown) => {\n\t\tif (error instanceof Error && \"code\" in error && error.code === \"ENOENT\") {\n\t\t\treturn null;\n\t\t}\n\t\tthrow error;\n\t});\n\n/** The JSON file at `path`, checked against `schema`, or null when there is none. */\nexport const readJsonFile = async <T>(path: string, schema: z.ZodType<T>) => {\n\tconst text = await readTextIfPresent(path);\n\treturn text === null ? null : schema.parse(JSON.parse(text));\n};\n\n/**\n * The JSON file at `path`, or null when there is none or its content isn't `schema`'s, such as a\n * record an agent of another version wrote. Failing to read it is an error.\n */\nexport const readJsonFileIfValid = <T>(path: string, schema: z.ZodType<T>) =>\n\treadJsonFile(path, schema).catch((error: unknown) => {\n\t\tif (error instanceof SyntaxError || error instanceof z.ZodError) {\n\t\t\treturn null;\n\t\t}\n\t\tthrow error;\n\t});\n\n/**\n * Replaces the JSON file at `path` whole, before anything else runs: a reader never sees half of\n * it, and each write has a temporary file of its own, so writers in other processes don't collide.\n */\nexport const writeJsonFile = (path: string, value: unknown) => {\n\tconst temporary = `${path}.${randomUUID()}.tmp`;\n\twriteFileSync(temporary, JSON.stringify(value, null, 2));\n\trenameSync(temporary, path);\n};\n\n/** Each file and directory of the agent's state directory `directory`. */\nexport const statePaths = (directory: string) => ({\n\treleases: join(directory, \"releases\"),\n\tcontroller: join(directory, \"controller\"),\n\t/** The deploying release's ST with its secrets filled in. */\n\tsources: join(directory, \"sources\"),\n\trelease: join(directory, \"release.json\"),\n\ttarget: join(directory, \"target.json\"),\n\tdeployments: join(directory, \"deployments.jsonl\"),\n\t/** Each deployment's record and log, under its id. */\n\tdeploymentRecords: join(directory, \"deployments\"),\n\taudit: join(directory, \"audit.jsonl\"),\n\t/** Who on the tailnet has which role. */\n\taccess: join(directory, \"access.json\"),\n\t/**\n\t * The names the dashboard stored by Bun.secrets service, since Bun.secrets can't list a\n\t * service's names. Never a value.\n\t */\n\tenvironment: join(directory, \"environment.json\"),\n\t/** The plain variables set on this PC, by name. */\n\tvariables: join(directory, \"variables.json\"),\n\tdebug: join(directory, \"debug\"),\n\t/** The running server's process, for the agent that takes it over. */\n\tserver: join(directory, \"server.json\"),\n\t/** The running agent: its process, address and serve arguments. */\n\tagent: join(directory, \"agent.json\"),\n\tlogs: join(directory, \"logs\"),\n\t/** The server's output. */\n\tserverLog: join(directory, \"logs\", \"server.log\"),\n\t/** The agent's output when `tsplc-agent service run` or `upgrade` starts it. */\n\tagentLog: join(directory, \"logs\", \"agent.log\"),\n});\n\n/**\n * The agent's state directory: releases, the controller's download baseline, the selected\n * target, the deployed release and the logs.\n */\nexport const openState = async (directory: string) => {\n\tconst paths = statePaths(directory);\n\tawait mkdir(paths.logs, { recursive: true });\n\n\tconst target = () => readJsonFile(paths.target, targetSchema);\n\tconst release = () => readJsonFile(paths.release, releaseSchema);\n\n\treturn {\n\t\tpaths,\n\t\t/** The selected controller, or null before `tsplc target`. */\n\t\ttarget,\n\t\tsetTarget: async (selected: Target) =>\n\t\t\twriteJsonFile(paths.target, selected),\n\t\trequireTarget: async () => {\n\t\t\tconst selected = await target();\n\t\t\tif (!selected) {\n\t\t\t\tthrow new AgentError(\"Select the controller first: tsplc target\", 409);\n\t\t\t}\n\t\t\treturn selected;\n\t\t},\n\t\t/** The deployed release, or null before the first deployment. */\n\t\trelease,\n\t\tsetRelease: async (deployed: Release) =>\n\t\t\twriteJsonFile(paths.release, deployed),\n\t\t/** The deployed release's files and manifest. */\n\t\trequireRelease: async () => {\n\t\t\tconst deployed = await release();\n\t\t\tif (!deployed) {\n\t\t\t\tthrow new AgentError(\n\t\t\t\t\t\"Nothing has been deployed yet: tsplc deploy\",\n\t\t\t\t\t409,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn loadRelease(paths.releases, deployed.id);\n\t\t},\n\t};\n};\nexport type AgentState = Awaited<ReturnType<typeof openState>>;\n",
47
+ "import { createInterface } from \"node:readline/promises\";\nimport type { Credentials } from \"./protocol\";\n\nexport const ask = async (question: string) => {\n\tconst lines = createInterface({\n\t\tinput: process.stdin,\n\t\toutput: process.stdout,\n\t});\n\ttry {\n\t\treturn (await lines.question(question)).trim();\n\t} finally {\n\t\tlines.close();\n\t}\n};\n\n/** Reads a line without echoing it. */\nexport const askSecret = (question: string) =>\n\tnew Promise<string>((accept, reject) => {\n\t\tif (!process.stdin.isTTY) {\n\t\t\treject(new Error(\"Typing a secret needs an interactive terminal.\"));\n\t\t\treturn;\n\t\t}\n\t\t// Echo goes off before the prompt appears, so nothing typed at it can show.\n\t\tprocess.stdin.setRawMode(true);\n\t\tprocess.stdin.setEncoding(\"utf8\");\n\t\tprocess.stdin.resume();\n\t\tprocess.stdout.write(question);\n\t\tlet secret = \"\";\n\t\tconst finish = () => {\n\t\t\tprocess.stdin.off(\"data\", read);\n\t\t\tprocess.stdin.setRawMode(false);\n\t\t\tprocess.stdin.pause();\n\t\t\tprocess.stdout.write(\"\\n\");\n\t\t};\n\t\tconst read = (text: string) => {\n\t\t\tfor (const character of text) {\n\t\t\t\tif (character === \"\\r\" || character === \"\\n\") {\n\t\t\t\t\tfinish();\n\t\t\t\t\taccept(secret);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (character === \"\\u0003\") {\n\t\t\t\t\tfinish();\n\t\t\t\t\treject(new Error(\"Cancelled.\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tsecret =\n\t\t\t\t\tcharacter === \"\\u007f\" ? secret.slice(0, -1) : secret + character;\n\t\t\t}\n\t\t};\n\t\tprocess.stdin.on(\"data\", read);\n\t});\n\nexport const askCredentials = async (): Promise<Credentials> => ({\n\tusername: await ask(\"Controller username: \"),\n\tpassword: await askSecret(\"Controller password: \"),\n});\n",
48
+ "import { z } from \"zod\";\nimport type { AgentControl, Instance } from \"./instance\";\n\n/** A version or dist-tag of @tsplc/agent, which goes into an install command. */\nexport const versionSchema = z\n\t.string()\n\t.regex(\n\t\t/^[0-9A-Za-z][0-9A-Za-z.+-]*$/,\n\t\t\"Name a version, such as 0.5.0, or a dist-tag, such as latest\",\n\t);\n\n/** The package manager whose global install holds the running agent. */\nexport type PackageManager = \"bun\" | \"npm\";\n\nconst normalize = (path: string) =>\n\tpath.replaceAll(\"\\\\\", \"/\").replace(/\\/+$/, \"\").toLowerCase();\n\n/**\n * The package manager whose global install holds the agent package at `packagePath`, such as\n * `C:\\Users\\plant\\.bun\\install\\global\\node_modules\\@tsplc\\agent`, or null for a project or\n * source checkout, which `upgrade` leaves to whoever installed it. `npmGlobalRoot` is\n * `npm root --global`, or null without npm.\n */\nexport const packageManagerFor = (\n\tpackagePath: string,\n\tnpmGlobalRoot: string | null,\n): PackageManager | null => {\n\tconst path = normalize(packagePath);\n\tif (path.endsWith(\"/install/global/node_modules/@tsplc/agent\")) {\n\t\treturn \"bun\";\n\t}\n\tif (\n\t\tnpmGlobalRoot !== null &&\n\t\tpath === `${normalize(npmGlobalRoot)}/@tsplc/agent`\n\t) {\n\t\treturn \"npm\";\n\t}\n\treturn null;\n};\n\n/** npm with `args` on `platform`, where npm is a batch file on Windows that only cmd runs. */\nexport const npmCommand = (platform: NodeJS.Platform, ...args: string[]) =>\n\tplatform === \"win32\"\n\t\t? [\"cmd.exe\", \"/d\", \"/s\", \"/c\", \"npm\", ...args]\n\t\t: [\"npm\", ...args];\n\n/** The command that installs @tsplc/agent at `version` globally with `manager`. */\nexport const installCommand = (\n\tmanager: PackageManager,\n\tversion: string,\n\thost: { bun: string; platform: NodeJS.Platform },\n) => {\n\t// The spec reaches cmd on Windows, so it is only ever a version or tag.\n\tconst spec = `@tsplc/agent@${versionSchema.parse(version)}`;\n\tif (manager === \"bun\") {\n\t\treturn [host.bun, \"add\", \"--global\", spec];\n\t}\n\treturn npmCommand(host.platform, \"install\", \"--global\", spec);\n};\n\n/** What `upgrade` does to the system, so its sequence can be followed without one. */\nexport interface UpgradeEffects {\n\t/** Runs a command on this terminal and returns its exit status. */\n\trun: (command: string[]) => Promise<number>;\n\t/** The version of the agent package now installed. */\n\tinstalledVersion: () => Promise<string>;\n\t/** Starts an agent that no service starts again, once `instance` has exited. */\n\tstartAgent: (instance: Instance) => Promise<void>;\n\t/** Starts the installed service; false when none is installed. */\n\tstartService: () => Promise<boolean>;\n\t/** Whether an agent of `version` answers within a few minutes. */\n\tanswers: (version: string) => Promise<boolean>;\n\tprint: (line: string) => void;\n}\n\n/**\n * Installs another version of the agent and runs it, without interrupting a deployment, touching\n * the controller or stopping the line's server. A running agent is held first, which fails while\n * an operation runs or a login is open, then installs, runs the new version's setup (nothing,\n * unless its image recipe changed), and is replaced by the new version, which takes over the\n * line's server and starts CODESYS again with its own code.\n */\nexport const upgradeAgent = async (\n\trequest: {\n\t\tversion: string;\n\t\tinstall: string[];\n\t\t/** The installed version's setup, which builds only images that need it. */\n\t\tsetup: string[];\n\t\trunning: { instance: Instance; control: AgentControl } | null;\n\t\t/** Where an agent `upgrade` starts writes its output. */\n\t\tagentLog: string;\n\t},\n\teffects: UpgradeEffects,\n) => {\n\tconst { running } = request;\n\tif (running) {\n\t\teffects.print(\n\t\t\t`Holding tsplc-agent ${running.instance.version} (process ${running.instance.pid}): it takes no deployments or logins until the new version runs`,\n\t\t);\n\t\tawait running.control.hold();\n\t}\n\tconst installed = await (async () => {\n\t\tif ((await effects.run(request.install)) !== 0) {\n\t\t\tthrow new Error(\n\t\t\t\t`Installing @tsplc/agent@${request.version} failed; see the output above`,\n\t\t\t);\n\t\t}\n\t\tconst version = await effects.installedVersion();\n\t\tif (running?.instance.version === version) {\n\t\t\treturn null;\n\t\t}\n\t\teffects.print(`Installed tsplc-agent ${version}; checking its images`);\n\t\tif ((await effects.run(request.setup)) !== 0) {\n\t\t\tthrow new Error(\n\t\t\t\t`tsplc-agent ${version} is installed, but its setup failed; see the output above. Run tsplc-agent upgrade ${version} again once it can`,\n\t\t\t);\n\t\t}\n\t\treturn version;\n\t})().catch(async (error: unknown) => {\n\t\tawait running?.control.releaseHold();\n\t\tthrow error;\n\t});\n\tif (installed === null) {\n\t\tawait running?.control.releaseHold();\n\t\teffects.print(\n\t\t\t`tsplc-agent ${running?.instance.version} is installed and running already`,\n\t\t);\n\t\treturn;\n\t}\n\tif (!running) {\n\t\tif (!(await effects.startService())) {\n\t\t\teffects.print(\n\t\t\t\t`tsplc-agent ${installed} is installed. No agent was running: start it with tsplc-agent serve, or install the service with tsplc-agent service install`,\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\teffects.print(\"Started the tsplc-agent service\");\n\t} else {\n\t\teffects.print(\n\t\t\t`Restarting the agent; the line's server keeps running and CODESYS starts again in the background`,\n\t\t);\n\t\tawait running.control.exit({ server: \"leave\", restart: true });\n\t\tif (!running.instance.supervised) {\n\t\t\tawait effects.startAgent(running.instance);\n\t\t}\n\t}\n\tif (!(await effects.answers(installed))) {\n\t\tthrow new Error(\n\t\t\t`tsplc-agent ${installed} is installed but doesn't answer; see ${request.agentLog}`,\n\t\t);\n\t}\n\teffects.print(`tsplc-agent ${installed} is running`);\n};\n"
49
+ ],
50
+ "mappings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