-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathinstall.js
More file actions
267 lines (242 loc) · 7.88 KB
/
install.js
File metadata and controls
267 lines (242 loc) · 7.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
#!/usr/bin/env node
/* eslint-disable no-console */
"use strict";
const fs = require("fs");
const os = require("os");
const path = require("path");
const https = require("https");
const { pipeline } = require("stream");
const { promisify } = require("util");
const { spawn } = require("child_process");
const streamPipeline = promisify(pipeline);
const PKG_ROOT = path.resolve(__dirname, "..");
const BIN_DIR = path.join(PKG_ROOT, "vendor");
const BIN_NAME = os.platform() === "win32" ? "agentx.exe" : "agentx";
const BIN_PATH = path.join(BIN_DIR, BIN_NAME);
const VERSION_MARKER = path.join(BIN_DIR, ".agentx-version");
const VERSION = require(path.join(PKG_ROOT, "package.json")).version;
const REPO = "agentsdance/agentx";
function getPlatform() {
const platform = os.platform();
if (platform === "darwin" || platform === "linux" || platform === "win32") {
return platform;
}
throw new Error(`Unsupported platform: ${platform}`);
}
function getArch() {
const arch = os.arch();
if (arch === "x64") return "amd64";
if (arch === "arm64") return "arm64";
throw new Error(`Unsupported architecture: ${arch}`);
}
function getAssetInfo() {
const platform = getPlatform();
const arch = getArch();
const ext = platform === "win32" ? "zip" : "tar.gz";
const osName = platform === "win32" ? "windows" : platform;
const filename = `agentx_${VERSION}_${osName}_${arch}.${ext}`;
return { platform, arch, ext, filename, osName };
}
async function ensureDir(dir) {
await fs.promises.mkdir(dir, { recursive: true });
}
async function downloadTo(url, dest, redirects = 0) {
await new Promise((resolve, reject) => {
https
.get(url, (res) => {
if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
if (redirects >= 5) {
reject(new Error("Too many redirects while downloading."));
res.resume();
return;
}
res.resume();
const nextUrl = new URL(res.headers.location, url).toString();
downloadTo(nextUrl, dest, redirects + 1).then(resolve).catch(reject);
return;
}
if (res.statusCode !== 200) {
const err = new Error(
`Failed to download ${url} (status ${res.statusCode})`
);
err.statusCode = res.statusCode;
reject(err);
res.resume();
return;
}
const file = fs.createWriteStream(dest);
streamPipeline(res, file).then(resolve).catch(reject);
})
.on("error", reject);
});
}
async function extractArchive(archivePath, ext) {
if (ext === "zip") {
if (os.platform() === "win32") {
const escapedArchive = archivePath.replace(/'/g, "''");
const escapedDest = BIN_DIR.replace(/'/g, "''");
await runCommand("powershell", [
"-NoProfile",
"-Command",
`Expand-Archive -LiteralPath '${escapedArchive}' -DestinationPath '${escapedDest}' -Force`,
]);
return;
}
await runCommand("unzip", ["-o", archivePath, "-d", BIN_DIR]);
return;
}
await runCommand("tar", ["-xzf", archivePath, "-C", BIN_DIR]);
}
async function findInstalledBinary() {
const directPath = path.join(BIN_DIR, BIN_NAME);
try {
await fs.promises.access(directPath, fs.constants.X_OK);
return directPath;
} catch (_) {
// continue
}
// Look for nested path like vendor/agentx_<ver>_<os>_<arch>/agentx
const entries = await fs.promises.readdir(BIN_DIR, { withFileTypes: true });
for (const entry of entries) {
if (!entry.isDirectory()) continue;
const candidate = path.join(BIN_DIR, entry.name, BIN_NAME);
try {
await fs.promises.access(candidate, fs.constants.X_OK);
return candidate;
} catch (_) {
// continue
}
}
return null;
}
async function promoteBinary(foundPath) {
if (foundPath === BIN_PATH) return;
await fs.promises.copyFile(foundPath, BIN_PATH);
}
async function makeExecutable(filePath) {
if (os.platform() === "win32") return;
await fs.promises.chmod(filePath, 0o755);
}
function runCommand(cmd, args) {
return new Promise((resolve, reject) => {
const child = spawn(cmd, args, { stdio: "inherit" });
child.on("error", reject);
child.on("exit", (code) => {
if (code === 0) {
resolve();
} else {
reject(new Error(`${cmd} exited with code ${code}`));
}
});
});
}
async function main() {
const { filename, ext, osName, arch } = getAssetInfo();
await ensureDir(BIN_DIR);
if (await isCurrentVersionInstalled()) {
return;
}
const archivePath = path.join(BIN_DIR, filename);
const release = await resolveRelease(filename, osName, arch, ext);
console.log(
`Downloading AgentX ${release.tag} for ${os.platform()} ${os.arch()}...`
);
await downloadTo(release.url, archivePath);
await extractArchive(archivePath, ext);
const found = await findInstalledBinary();
if (!found) {
throw new Error("Downloaded archive but could not find agentx binary.");
}
await promoteBinary(found);
await makeExecutable(BIN_PATH);
await fs.promises.writeFile(VERSION_MARKER, VERSION, "utf8");
}
async function resolveRelease(expectedFilename, osName, arch, ext) {
const tag = `v${VERSION}`;
const byTag = await fetchRelease(`https://api.github.com/repos/${REPO}/releases/tags/${tag}`);
if (byTag) {
const asset = pickAsset(byTag, expectedFilename);
if (asset) return { url: asset.browser_download_url, tag };
}
const latest = await fetchRelease(
`https://api.github.com/repos/${REPO}/releases/latest`
);
if (latest) {
const fallbackName = `agentx_${latest.tag_name.replace(/^v/, "")}_${osName}_${arch}.${ext}`;
const asset = pickAsset(latest, fallbackName);
if (asset) return { url: asset.browser_download_url, tag: latest.tag_name };
}
throw new Error("Could not locate a matching release asset on GitHub.");
}
function pickAsset(release, filename) {
if (!release || !Array.isArray(release.assets)) return null;
return release.assets.find((asset) => asset.name === filename) || null;
}
async function fetchRelease(url) {
try {
return await fetchJson(url);
} catch (err) {
if (err.statusCode === 404) return null;
throw err;
}
}
async function fetchJson(url, redirects = 0) {
return await new Promise((resolve, reject) => {
const options = {
headers: {
"User-Agent": "agentx-npm-installer",
Accept: "application/vnd.github+json",
},
};
https
.get(url, options, (res) => {
if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
if (redirects >= 5) {
const err = new Error("Too many redirects while fetching JSON.");
err.statusCode = res.statusCode;
reject(err);
res.resume();
return;
}
res.resume();
const nextUrl = new URL(res.headers.location, url).toString();
fetchJson(nextUrl, redirects + 1).then(resolve).catch(reject);
return;
}
if (res.statusCode !== 200) {
const err = new Error(`Failed to fetch ${url} (status ${res.statusCode})`);
err.statusCode = res.statusCode;
reject(err);
res.resume();
return;
}
let body = "";
res.setEncoding("utf8");
res.on("data", (chunk) => {
body += chunk;
});
res.on("end", () => {
try {
resolve(JSON.parse(body));
} catch (parseErr) {
reject(parseErr);
}
});
})
.on("error", reject);
});
}
async function isCurrentVersionInstalled() {
try {
const marker = await fs.promises.readFile(VERSION_MARKER, "utf8");
if (marker.trim() !== VERSION) return false;
await fs.promises.access(BIN_PATH, fs.constants.X_OK);
return true;
} catch (_) {
return false;
}
}
main().catch((err) => {
console.error(`AgentX install failed: ${err.message}`);
process.exit(1);
});