@verbodhpteltd/devops-agent 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE.md ADDED
@@ -0,0 +1,28 @@
1
+ # AgenticDevOps DevOps agent licence
2
+
3
+ Copyright © VerBodh Pte. Ltd., Singapore. All rights reserved.
4
+
5
+ The `@verbodhpteltd/devops-agent` package, and the DevOps agent program it downloads, are
6
+ proprietary software. They are not open source.
7
+
8
+ Parts of the agent are derived from third-party open-source software. Those licences still apply to
9
+ those parts; the agent prints them with `devops-agent help`.
10
+
11
+ ## What you may do
12
+ - Install and run the agent to read and work on your own cloud accounts.
13
+ - Run it on your own machines and in your own CI.
14
+ - Use it with your own AgenticDevOps account and your own model key.
15
+
16
+ ## What you may not do
17
+ - Copy, change, or share the package, the program, or their source, except as needed to run them.
18
+ - Sell, rent, sublicense, or offer either as part of another product or service.
19
+ - Use either to build a product that competes with AgenticDevOps.
20
+ - Remove this notice.
21
+
22
+ ## No warranty
23
+ The package and the program are provided "as is", without warranty of any kind. VerBodh Pte. Ltd. is
24
+ not liable for any claim or damage that comes from using them. A check can miss a problem, and a
25
+ clean report is not proof that an account is safe or compliant.
26
+
27
+ ## Questions
28
+ support@verbodh.com · https://www.devsecops-agent.com
package/README.md CHANGED
@@ -1,3 +1,84 @@
1
- # Temporary Holding Version
1
+ # @verbodhpteltd/devops-agent
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The AgenticDevOps DevOps agent, in your terminal. Ask your AWS estate a question, run the checks,
4
+ read the findings, and make a change behind an approval you give.
5
+
6
+ ```bash
7
+ npm i -g @verbodhpteltd/devops-agent
8
+ devops-agent login # your AgenticDevOps sign-in
9
+ devops-agent # the chat
10
+ ```
11
+
12
+ One run, nothing installed globally:
13
+
14
+ ```bash
15
+ npx @verbodhpteltd/devops-agent ask "which S3 buckets are public?"
16
+ ```
17
+
18
+ ## What installing does
19
+
20
+ This package holds no program. The **first time you run `devops-agent`**, it reads the release
21
+ pointer on https://www.devsecops-agent.com, downloads the build for your system, checks it against
22
+ the sha256 published beside it, and places it in your own app folder:
23
+
24
+ ```
25
+ ~/.local/share/devops-agent/versions/<version>/DevSecOpsAgent
26
+ ~/.local/share/devops-agent/database/ your local results
27
+ ~/.local/share/devops-agent/env your model key, written only by `devops-agent key set`
28
+ ```
29
+
30
+ It is the same folder the website installer uses, so your key, your sign-in and your local results
31
+ are the same whichever way you installed. It adds no second copy of the command, no login item, and
32
+ starts nothing when you log in.
33
+
34
+ The download waits for your first run rather than happening during `npm install`, because npm 12
35
+ blocks a dependency's install scripts unless your project allowlists the package. A package that
36
+ downloaded itself in a `postinstall` would install nothing for most people today. To fetch it ahead
37
+ of time, run `devops-agent version` once.
38
+
39
+ Nothing is installed at all, and you are told why in one line, when the pointer is not a version,
40
+ the checksum does not match, the download leaves our host, your system has no published build, or
41
+ your Linux uses musl instead of glibc (Alpine).
42
+
43
+ ## Two version numbers
44
+
45
+ | Number | What it is |
46
+ |---|---|
47
+ | This package's version | the installer's own version, which is what `npm i` pins |
48
+ | The agent's version, from `devops-agent version` | the build the website's release pointer names on the day you install |
49
+
50
+ So pinning a version of this package does not pin a version of the agent. To move the agent to the
51
+ newest build, run `/update` inside the chat, or install again. `npx` keeps the copy it already
52
+ downloaded; `npx --prefer-online` and `/update` are the two ways to move it.
53
+
54
+ ## What this package cannot do
55
+
56
+ - **Autostart and the hosted chat.** `devops-agent autostart on` needs the command the website
57
+ installer puts in `~/.local/bin`, so an npm-only install cannot turn it on. Install from
58
+ https://www.devsecops-agent.com/install.html as well if you want the chat at
59
+ https://www.devsecops-agent.com/app.html to work with no terminal open.
60
+ - **Run with no network, the first time.** The program is about 55 MB and comes from our site, not
61
+ from npm. A machine behind a proxy that blocks it, or an offline cache, gets nothing on that first
62
+ run: use the website installer, or keep the file yourself. Later runs need no network of their own.
63
+ - **Appear in your SBOM.** `npm audit` and `npm sbom` see this package and no dependencies. The
64
+ program it downloads is not an npm package and will not be listed, and each container whose agent
65
+ runs for the first time downloads it again.
66
+ - **Run without Docker, for shell commands.** The agent runs a command only inside a Docker sandbox.
67
+ Everything else works with Docker absent.
68
+
69
+ On Windows the command works from PowerShell and from Git Bash. Your terminal names the tab `node`,
70
+ because npm's command is a Node program; the website installer's command names it after the agent.
71
+
72
+ ## Your data
73
+
74
+ Your cloud credentials, your model key and your local results stay on your machine. The sign-in says
75
+ who you are and whether you may use the agent. What the agent sends to the server, and what never
76
+ leaves the laptop, is printed by `devops-agent login`.
77
+
78
+ ## Links
79
+
80
+ - The app: https://www.devsecops-agent.com
81
+ - Install page, with the one-liners: https://www.devsecops-agent.com/install.html
82
+ - Questions: support@verbodh.com
83
+
84
+ Licence: see LICENSE.md. Proprietary, not open source.
@@ -0,0 +1,66 @@
1
+ #!/usr/bin/env node
2
+ // The `devops-agent` command npm installs. It runs the agent and gets out of the way: same
3
+ // arguments, same terminal, same exit code.
4
+ //
5
+ // On the first run it downloads the agent itself. That is not done at npm install time because npm
6
+ // 12 blocks a dependency's install scripts unless the installing project allowlists the package
7
+ // ("Dependency install scripts are blocked by default",
8
+ // docs.npmjs.com/cli/v12/commands/npm-approve-scripts), so a `postinstall` would be skipped for
9
+ // most people and leave this command with no program behind it.
10
+ //
11
+ // Three details earn their lines:
12
+ // * the terminal is inherited, both ways, because the full-screen chat starts only when stdin and
13
+ // stdout are both terminals (backend/src/chat.rs:1815);
14
+ // * a child killed by a signal exits with 128 + the signal, not 0, so a run stopped by Ctrl-C or
15
+ // by a CI timeout is not read as a clean pass;
16
+ // * the download prints to stderr, so `devops-agent ask ... > answer.txt` holds the answer only.
17
+ 'use strict';
18
+
19
+ const { spawn } = require('node:child_process');
20
+ const P = require('../lib/platform.js');
21
+ const { ensure, Refused } = require('../scripts/install.js');
22
+
23
+ // The shell's own convention, so a caller can tell a kill from an exit code.
24
+ const NUMBERS = { SIGHUP: 1, SIGINT: 2, SIGQUIT: 3, SIGKILL: 9, SIGTERM: 15 };
25
+
26
+ async function agentFile() {
27
+ const found = P.newestInstalled();
28
+ if (found) return found.file;
29
+ try {
30
+ return await ensure();
31
+ } catch (e) {
32
+ const message = e instanceof Refused ? e.message : `${e.message}. ${P.NOTHING}`;
33
+ process.stderr.write(
34
+ `devops-agent: ${message}\n` + ` The steps by hand: ${P.INSTALL_PAGE}\n`,
35
+ );
36
+ process.exit(1);
37
+ }
38
+ }
39
+
40
+ agentFile().then((file) => {
41
+ const child = spawn(file, process.argv.slice(2), { stdio: 'inherit', shell: false });
42
+
43
+ // Ctrl-C reaches the child through the terminal already; these cover a signal sent to this
44
+ // process alone, as a supervisor or a CI runner does.
45
+ let stoppedBy = null;
46
+ for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) {
47
+ process.on(signal, () => {
48
+ stoppedBy = signal;
49
+ if (!child.killed) child.kill(signal);
50
+ });
51
+ }
52
+
53
+ child.on('error', (e) => {
54
+ process.stderr.write(`devops-agent: could not run ${file} (${e.message})\n`);
55
+ process.exit(1);
56
+ });
57
+
58
+ child.on('exit', (code, signal) => {
59
+ if (signal) process.exit(128 + (NUMBERS[signal] || 0));
60
+ // A child that tidies up and exits 0 after the signal still means the run was stopped, not that
61
+ // it passed. A supervisor or a CI timeout must not read it as a clean pass; a non-zero code the
62
+ // agent chose itself is kept as the agent's own answer.
63
+ if (stoppedBy && (code === 0 || code === null)) process.exit(128 + NUMBERS[stoppedBy]);
64
+ process.exit(code === null ? 1 : code);
65
+ });
66
+ });
@@ -0,0 +1,164 @@
1
+ // The one place the npm package decides which published build fits this machine.
2
+ //
3
+ // The rules are the shell installers', and they are the authority: scripts/public/install.sh for
4
+ // macOS and Linux, scripts/public/install.ps1 for Windows. tests/npmPackage/test_tables_match.py
5
+ // reads all three files and fails when one changes alone, because a second copy of these rules that
6
+ // drifts is worse than no copy at all.
7
+ 'use strict';
8
+
9
+ const SITE = 'https://www.devsecops-agent.com';
10
+ const RELEASES = `${SITE}/releases`;
11
+ const INSTALL_PAGE = `${SITE}/install.html`;
12
+
13
+ // A pointer file holds one version and nothing else. The strict form is install.ps1's; install.sh
14
+ // uses a glob, which `v0.1.2/../../etc/passwd` passes, so this file never copies the glob.
15
+ const VERSION = /^v\d+\.\d+\.\d+$/;
16
+
17
+ // platform/arch, as Node reports them, to the triple published under releases/<version>/.
18
+ // Windows on ARM64 runs the x64 build under emulation, as install.ps1 says.
19
+ const TRIPLES = {
20
+ 'darwin/arm64': 'aarch64-apple-darwin',
21
+ 'darwin/x64': 'x86_64-apple-darwin',
22
+ 'linux/arm64': 'aarch64-unknown-linux-gnu',
23
+ 'linux/x64': 'x86_64-unknown-linux-gnu',
24
+ 'win32/x64': 'x86_64-pc-windows-msvc',
25
+ 'win32/arm64': 'x86_64-pc-windows-msvc',
26
+ };
27
+
28
+ // The name of the file in the release, and the name it is placed under. The placed name is what
29
+ // Activity Monitor and Task Manager show, so it is the product's name, not the crate's.
30
+ function downloadName(triple) {
31
+ return triple.includes('windows') ? 'devops_agent.exe' : 'devops_agent';
32
+ }
33
+
34
+ function placedName(triple) {
35
+ return triple.includes('windows') ? 'DevOpsAgent.exe' : 'DevSecOpsAgent';
36
+ }
37
+
38
+ // A glibc build on a musl system downloads and verifies, then will not run: `node:alpine` reports
39
+ // linux/x64 like any other Linux. Node names the runtime glibc only when it is linked against one.
40
+ function isMusl(platform = process.platform) {
41
+ if (platform !== 'linux') return false;
42
+ try {
43
+ const report = process.report && process.report.getReport();
44
+ const header = report && report.header;
45
+ if (!header) return false;
46
+ return !header.glibcVersionRuntime;
47
+ } catch {
48
+ return false;
49
+ }
50
+ }
51
+
52
+ // `Err` holds the whole sentence a person reads. Every refusal ends the same way, because the one
53
+ // thing they need to know is that their machine was not changed.
54
+ const NOTHING = 'Nothing was installed.';
55
+
56
+ /**
57
+ * The triple for this machine, or a refusal to print.
58
+ * `env` is passed in so the tests drive it without touching the process environment.
59
+ */
60
+ function chooseTriple(env = process.env, platform = process.platform, arch = process.arch) {
61
+ const named = (env.DEVOPS_AGENT_TRIPLE || '').trim();
62
+ if (named) {
63
+ return Object.values(TRIPLES).includes(named)
64
+ ? { triple: named }
65
+ : { error: `no release is published for ${named}. ${NOTHING}` };
66
+ }
67
+ if (isMusl(platform)) {
68
+ return {
69
+ error:
70
+ 'this Linux uses musl (Alpine), and the published build needs glibc. ' +
71
+ `Use a glibc image, or the steps at ${INSTALL_PAGE}. ${NOTHING}`,
72
+ };
73
+ }
74
+ const triple = TRIPLES[`${platform}/${arch}`];
75
+ return triple
76
+ ? { triple }
77
+ : { error: `no release for ${platform}/${arch}. See ${INSTALL_PAGE}. ${NOTHING}` };
78
+ }
79
+
80
+ /**
81
+ * Where the releases are read from. The host is a constant on purpose: an environment variable that
82
+ * can be set by a CI job, a project .npmrc or another package's install script must not decide where
83
+ * executable code comes from, and the checksum beside the file cannot help, because it would come
84
+ * from the same place. The override stays for our own tests, and only for a loopback address.
85
+ */
86
+ function releasesUrl(env = process.env) {
87
+ const named = (env.DEVOPS_AGENT_RELEASES_URL || '').trim();
88
+ if (!named) return { url: RELEASES };
89
+ let parsed;
90
+ try {
91
+ parsed = new URL(named);
92
+ } catch {
93
+ return { error: `DEVOPS_AGENT_RELEASES_URL is not a URL. ${NOTHING}` };
94
+ }
95
+ if (parsed.hostname !== '127.0.0.1' && parsed.hostname !== 'localhost') {
96
+ return {
97
+ error:
98
+ `this package downloads only from ${SITE}, and DEVOPS_AGENT_RELEASES_URL names ` +
99
+ `${parsed.hostname}. ${NOTHING}`,
100
+ };
101
+ }
102
+ return { url: named.replace(/\/+$/, '') };
103
+ }
104
+
105
+ /** The app folder both installers use, so the key, the sign-in and the database are the same ones. */
106
+ function appDir(env = process.env) {
107
+ const named = (env.DEVOPS_AGENT_INSTALL_DIR || '').trim();
108
+ if (named) return named;
109
+ const home = env.HOME || env.USERPROFILE;
110
+ if (!home) return null;
111
+ return require('node:path').join(home, '.local', 'share', 'devops-agent');
112
+ }
113
+
114
+ /**
115
+ * The newest installed agent in the app folder, or null. The launcher resolves it on every run
116
+ * rather than remembering a path: a later install, the chat's own `/update`, or the website
117
+ * installer may have replaced the version this package placed.
118
+ */
119
+ function newestInstalled(env = process.env, triple = null) {
120
+ const fs = require('node:fs');
121
+ const path = require('node:path');
122
+ const app = appDir(env);
123
+ if (!app) return null;
124
+ const chosen = triple || (chooseTriple(env).triple ?? null);
125
+ if (!chosen) return null;
126
+ const versions = path.join(app, 'versions');
127
+ let names;
128
+ try {
129
+ names = fs.readdirSync(versions).filter((n) => VERSION.test(n));
130
+ } catch {
131
+ return null;
132
+ }
133
+ const order = (n) => n.slice(1).split('.').map(Number);
134
+ names.sort((a, b) => {
135
+ const [x, y] = [order(a), order(b)];
136
+ return y[0] - x[0] || y[1] - x[1] || y[2] - x[2];
137
+ });
138
+ for (const name of names) {
139
+ const file = path.join(versions, name, placedName(chosen));
140
+ try {
141
+ fs.accessSync(file, fs.constants.X_OK);
142
+ return { version: name, file };
143
+ } catch {
144
+ // a half-removed version folder: try the next one down
145
+ }
146
+ }
147
+ return null;
148
+ }
149
+
150
+ module.exports = {
151
+ SITE,
152
+ RELEASES,
153
+ INSTALL_PAGE,
154
+ VERSION,
155
+ TRIPLES,
156
+ NOTHING,
157
+ downloadName,
158
+ placedName,
159
+ isMusl,
160
+ chooseTriple,
161
+ releasesUrl,
162
+ appDir,
163
+ newestInstalled,
164
+ };
package/package.json CHANGED
@@ -1,6 +1,16 @@
1
1
  {
2
2
  "name": "@verbodhpteltd/devops-agent",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "The AgenticDevOps DevOps agent in your terminal: asks your AWS estate questions, runs checks, reports findings, and makes an approved change behind an approval.",
5
+ "bin": { "devops-agent": "bin/devops-agent.js" },
6
+ "files": ["bin", "lib", "scripts", "README.md", "LICENSE.md"],
7
+ "scripts": {
8
+ "test": "python3 ../tests/npmPackage/run_all.py"
9
+ },
10
+ "engines": { "node": ">=18" },
11
+ "keywords": ["aws", "devops", "devsecops", "agent", "cli", "estate", "agenticdevops"],
12
+ "repository": { "type": "git", "url": "git+https://github.com/verbodh-pte-ltd/AgenticDevOps.git" },
13
+ "homepage": "https://www.devsecops-agent.com",
14
+ "author": "VerBodh <support@verbodh.com>",
15
+ "license": "SEE LICENSE IN LICENSE.md"
16
+ }
@@ -0,0 +1,241 @@
1
+ #!/usr/bin/env node
2
+ // Download the published DevOps agent for this machine and place it in the person's own app folder,
3
+ // the same folder scripts/public/install.sh uses.
4
+ //
5
+ // node scripts/install.js # fetch it now
6
+ // devops-agent <anything> # the command does this on its first run
7
+ //
8
+ // This is NOT an npm install script, on purpose. npm 12 blocks a dependency's install scripts
9
+ // unless the installing project allowlists the package ("Dependency install scripts are blocked by
10
+ // default", docs.npmjs.com/cli/v12/commands/npm-approve-scripts; `allow-scripts` defaults to ""),
11
+ // so a `postinstall` here would be skipped for most people and leave the command with no program
12
+ // behind it. The download therefore happens on the first run of the command, which npm does not gate.
13
+ //
14
+ // It is install.sh's download half, in Node, and nothing more:
15
+ // * no second copy of the command in ~/.local/bin (npm owns the command name)
16
+ // * no login item and no autostart (install.sh's job, not npm's)
17
+ // * no write to <app>/env (that file holds the person's model key)
18
+ //
19
+ // The agent reads its key file, its sign-in and its database from the folder above its own
20
+ // `versions/<version>/` directory (backend/src/main.rs:81-88), which is why the binary goes here
21
+ // and not inside node_modules: a copy in node_modules has no key file and falls back to a database
22
+ // path relative to the current folder.
23
+ 'use strict';
24
+
25
+ const fs = require('node:fs');
26
+ const path = require('node:path');
27
+ const crypto = require('node:crypto');
28
+ const http = require('node:http');
29
+ const https = require('node:https');
30
+ const { URL } = require('node:url');
31
+
32
+ const P = require('../lib/platform.js');
33
+
34
+ const TIMEOUT_MS = 120000;
35
+ const MAX_BYTES = 200 * 1024 * 1024; // a published agent is about 55 MB; this refuses a surprise
36
+
37
+ // A refusal a person reads. `ensure` throws it; the command and the direct run both print it and
38
+ // stop, so one sentence covers both doors.
39
+ class Refused extends Error {}
40
+
41
+ function fail(message) {
42
+ throw new Refused(message);
43
+ }
44
+
45
+ // The progress lines go to stderr: a person running `devops-agent ask ... > answer.txt` must not
46
+ // find "Installing..." at the top of the file.
47
+ let say = (message) => process.stderr.write(`${message}\n`);
48
+
49
+ /**
50
+ * One request, to one host, with no redirect followed. A 3xx is refused by name: following one
51
+ * would let the answer move the download off the host this package trusts.
52
+ */
53
+ function get(url, onResponse) {
54
+ const parsed = new URL(url);
55
+ const client = parsed.protocol === 'http:' ? http : https;
56
+ return new Promise((resolve, reject) => {
57
+ const req = client.get(url, { timeout: TIMEOUT_MS }, (res) => {
58
+ const code = res.statusCode || 0;
59
+ if (code >= 300 && code < 400) {
60
+ res.resume();
61
+ const e = new Error(`the download did not stay on one host (${code} from ${parsed.hostname})`);
62
+ e.kind = 'redirect';
63
+ reject(e);
64
+ return;
65
+ }
66
+ if (code !== 200) {
67
+ res.resume();
68
+ reject(new Error(`${url} answered ${code}`));
69
+ return;
70
+ }
71
+ onResponse(res, resolve, reject);
72
+ });
73
+ req.on('timeout', () => req.destroy(new Error(`no answer from ${parsed.hostname} in 120 seconds`)));
74
+ req.on('error', reject);
75
+ });
76
+ }
77
+
78
+ /** A small text file, as a trimmed string. */
79
+ function fetchText(url) {
80
+ return get(url, (res, resolve, reject) => {
81
+ let body = '';
82
+ res.setEncoding('utf8');
83
+ res.on('data', (chunk) => {
84
+ body += chunk;
85
+ if (body.length > 4096) {
86
+ res.destroy();
87
+ reject(new Error(`${url} is larger than a version or a checksum should be`));
88
+ }
89
+ });
90
+ res.on('end', () => resolve(body.trim()));
91
+ res.on('error', reject);
92
+ });
93
+ }
94
+
95
+ /**
96
+ * The binary, streamed to a file, hashed as it arrives. The bytes that are hashed are the bytes on
97
+ * disk: nothing is downloaded again between the hash and the move.
98
+ */
99
+ function fetchBinary(url, into) {
100
+ return get(url, (res, resolve, reject) => {
101
+ const hash = crypto.createHash('sha256');
102
+ const out = fs.createWriteStream(into, { mode: 0o755 });
103
+ let size = 0;
104
+ res.on('data', (chunk) => {
105
+ size += chunk.length;
106
+ if (size > MAX_BYTES) {
107
+ res.destroy();
108
+ out.destroy();
109
+ reject(new Error(`${url} is larger than ${MAX_BYTES} bytes`));
110
+ return;
111
+ }
112
+ hash.update(chunk);
113
+ });
114
+ res.pipe(out);
115
+ out.on('error', reject);
116
+ out.on('finish', () => resolve({ digest: hash.digest('hex'), size }));
117
+ res.on('error', reject);
118
+ });
119
+ }
120
+
121
+ function sha256OfFile(file) {
122
+ return crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex');
123
+ }
124
+
125
+ /** Keep the one just installed and the one before it, newest by version number, not by file time. */
126
+ function prune(versionsDir, keep) {
127
+ let names;
128
+ try {
129
+ names = fs.readdirSync(versionsDir).filter((n) => P.VERSION.test(n));
130
+ } catch {
131
+ return;
132
+ }
133
+ const order = (n) => n.slice(1).split('.').map(Number);
134
+ names.sort((a, b) => {
135
+ const [x, y] = [order(a), order(b)];
136
+ return y[0] - x[0] || y[1] - x[1] || y[2] - x[2];
137
+ });
138
+ for (const old of names.slice(2)) {
139
+ if (old === keep) continue;
140
+ fs.rmSync(path.join(versionsDir, old), { recursive: true, force: true });
141
+ }
142
+ }
143
+
144
+ /**
145
+ * Make sure the agent is on this machine, and answer with the file to run.
146
+ * Throws `Refused` with the whole sentence a person reads.
147
+ */
148
+ async function ensure({ quiet = false } = {}) {
149
+ if (quiet) say = () => {};
150
+ const chosen = P.chooseTriple();
151
+ if (chosen.error) fail(chosen.error);
152
+ const triple = chosen.triple;
153
+
154
+ const releases = P.releasesUrl();
155
+ if (releases.error) fail(releases.error);
156
+ const base = releases.url;
157
+
158
+ const app = P.appDir();
159
+ if (!app) fail(`cannot find your home folder. ${P.NOTHING}`);
160
+
161
+ let version;
162
+ try {
163
+ version = await fetchText(`${base}/latest-${triple}`);
164
+ } catch (e) {
165
+ // A redirect is its own answer: "no release yet" would hide that the host moved the download.
166
+ if (e.kind === 'redirect') fail(`${e.message}. ${P.NOTHING}`);
167
+ fail(`no release for ${triple} yet. ${P.NOTHING}`);
168
+ }
169
+ if (!P.VERSION.test(version)) {
170
+ fail(`the release pointer for ${triple} is not a version ('${version}'). ${P.NOTHING}`);
171
+ }
172
+
173
+ const dir = path.join(app, 'versions', version);
174
+ const target = path.join(dir, P.placedName(triple));
175
+ fs.mkdirSync(dir, { recursive: true });
176
+ fs.mkdirSync(path.join(app, 'database'), { recursive: true });
177
+ fs.mkdirSync(path.join(app, 'run'), { recursive: true });
178
+
179
+ let want;
180
+ try {
181
+ want = (await fetchText(`${base}/${version}/${triple}/${P.downloadName(triple)}.sha256`)).toLowerCase();
182
+ } catch (e) {
183
+ fail(`could not download the checksum for ${version} (${e.message}). ${P.NOTHING}`);
184
+ }
185
+ if (!/^[0-9a-f]{64}$/.test(want)) {
186
+ fail(`the published checksum for ${version}/${triple} is not a sha256. ${P.NOTHING}`);
187
+ }
188
+
189
+ // The same version already in place, byte for byte, is kept. Windows will not replace a running
190
+ // .exe (install.ps1:54-58), and re-installing while the agent is open must still work.
191
+ if (fs.existsSync(target) && sha256OfFile(target) === want) {
192
+ say(`devops-agent ${version} is already installed: ${target}`);
193
+ prune(path.join(app, 'versions'), version);
194
+ return target;
195
+ }
196
+
197
+ // The temporary file lives beside the target, so the move below is a rename on one filesystem.
198
+ const tmp = path.join(dir, `.download-${process.pid}-${Date.now()}`);
199
+ say(`Installing devops-agent ${version} for ${triple} from ${new URL(base).host}...`);
200
+ let got;
201
+ try {
202
+ got = await fetchBinary(`${base}/${version}/${triple}/${P.downloadName(triple)}`, tmp);
203
+ } catch (e) {
204
+ fs.rmSync(tmp, { force: true });
205
+ fail(`could not download ${version} for ${triple} (${e.message}). ${P.NOTHING}`);
206
+ }
207
+ if (got.digest !== want) {
208
+ fs.rmSync(tmp, { force: true });
209
+ fail(
210
+ `checksum mismatch for ${version}/${triple}: the download is not what was published. ${P.NOTHING}`,
211
+ );
212
+ }
213
+
214
+ try {
215
+ fs.chmodSync(tmp, 0o755);
216
+ // Rename, never copy over a binary that has run: macOS kills a process whose file was
217
+ // overwritten in place (install.sh:99-100).
218
+ fs.renameSync(tmp, target);
219
+ } catch (e) {
220
+ fs.rmSync(tmp, { force: true });
221
+ fail(`could not put the agent at ${target} (${e.message}). Close devops-agent and try again.`);
222
+ }
223
+
224
+ prune(path.join(app, 'versions'), version);
225
+ say(`devops-agent ${version} installed: ${target}`);
226
+ say('Run `devops-agent login` to sign in, then `devops-agent` for the chat.');
227
+ return target;
228
+ }
229
+
230
+ module.exports = { ensure, Refused };
231
+
232
+ // Run directly: fetch it now, and print the one sentence if it cannot be fetched.
233
+ if (require.main === module) {
234
+ ensure()
235
+ .then(() => process.exit(0))
236
+ .catch((e) => {
237
+ const message = e instanceof Refused ? e.message : `${e.message}. ${P.NOTHING}`;
238
+ process.stderr.write(`devops-agent: ${message}\n`);
239
+ process.exit(1);
240
+ });
241
+ }