megacode-agent-sdk 0.0.0-stage → 0.31.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-APACHE +176 -0
- package/LICENSE-MIT +23 -0
- package/README.md +38 -2
- package/dist/binary/archive.d.ts +7 -0
- package/dist/binary/archive.js +215 -0
- package/dist/binary/cache.d.ts +21 -0
- package/dist/binary/cache.js +256 -0
- package/dist/binary/download.d.ts +16 -0
- package/dist/binary/download.js +174 -0
- package/dist/binary/index.d.ts +49 -0
- package/dist/binary/index.js +160 -0
- package/dist/client.d.ts +94 -0
- package/dist/client.js +868 -0
- package/dist/errors.d.ts +58 -0
- package/dist/errors.js +97 -0
- package/dist/index.d.ts +52 -0
- package/dist/index.js +42 -0
- package/dist/options.d.ts +48 -0
- package/dist/options.js +49 -0
- package/dist/pins.d.ts +5 -0
- package/dist/pins.js +22 -0
- package/dist/process.d.ts +72 -0
- package/dist/process.js +255 -0
- package/dist/tools.d.ts +74 -0
- package/dist/tools.js +256 -0
- package/dist/version.d.ts +1 -0
- package/dist/version.js +3 -0
- package/dist/wire.d.ts +241 -0
- package/dist/wire.js +620 -0
- package/package.json +33 -4
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
// The verified cache (spec slice-ar R12.3–R12.4):
|
|
2
|
+
// `<cache>/megacode-agent-sdk/<version>/<target>/harness`.
|
|
3
|
+
//
|
|
4
|
+
// Every ancestor of `<cache>` is a real folder owned by this user or root and
|
|
5
|
+
// not writable by group or others unless sticky; `<cache>` and each folder
|
|
6
|
+
// below it is a real folder owned by this user and not writable by group or
|
|
7
|
+
// others; the file is a regular file owned by this user with no group or other
|
|
8
|
+
// write. With those rules no other user can change the file, or move a folder
|
|
9
|
+
// on its path, between the check and the run. Every descriptor Node opens is
|
|
10
|
+
// close-on-exec (libuv opens with `O_CLOEXEC`).
|
|
11
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
12
|
+
import { constants as C, promises as fsp } from "node:fs";
|
|
13
|
+
import * as path from "node:path";
|
|
14
|
+
import { BinaryUnavailable } from "../errors.js";
|
|
15
|
+
/** The environment variable naming a harness binary (R12.1). */
|
|
16
|
+
export const BINARY_ENV = "MEGACODE_AGENT_SDK_BINARY";
|
|
17
|
+
/** Where one version's executable for one target lives. */
|
|
18
|
+
export class Layout {
|
|
19
|
+
root;
|
|
20
|
+
/** `<cache>` and each folder below it, top down, the last holding the file. */
|
|
21
|
+
folders;
|
|
22
|
+
dir;
|
|
23
|
+
file;
|
|
24
|
+
constructor(root, version, target) {
|
|
25
|
+
this.root = root;
|
|
26
|
+
const sdk = path.join(root, "megacode-agent-sdk");
|
|
27
|
+
const ver = path.join(sdk, version);
|
|
28
|
+
this.dir = path.join(ver, target);
|
|
29
|
+
this.folders = [root, sdk, ver, this.dir];
|
|
30
|
+
this.file = path.join(this.dir, "harness");
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
/** A `.harness.*.tmp` older than this was left by a program that stopped
|
|
34
|
+
* mid-write; a live writer's file is far younger. */
|
|
35
|
+
const STALE_MS = 60 * 60 * 1000;
|
|
36
|
+
function euid() {
|
|
37
|
+
// `process.geteuid` exists on every POSIX platform; the targets are POSIX.
|
|
38
|
+
return process.geteuid();
|
|
39
|
+
}
|
|
40
|
+
function reason(e) {
|
|
41
|
+
return e instanceof Error ? e.message : String(e);
|
|
42
|
+
}
|
|
43
|
+
function code(e) {
|
|
44
|
+
return e?.code;
|
|
45
|
+
}
|
|
46
|
+
function refuseFolder(folder, why) {
|
|
47
|
+
return new BinaryUnavailable(`the cache folder ${folder} ${why}: it must be a real folder (not a symlink), owned by you, ` +
|
|
48
|
+
`not writable by group or others. Fix the folder, or name a harness with ` +
|
|
49
|
+
`Options::binary or ${BINARY_ENV}`);
|
|
50
|
+
}
|
|
51
|
+
function refuseAncestor(folder, why) {
|
|
52
|
+
return new BinaryUnavailable(`the folder ${folder} above the cache ${why}: every folder above the cache must be a real ` +
|
|
53
|
+
`folder (not a symlink), owned by you or root, not writable by group or others unless ` +
|
|
54
|
+
`sticky (as /tmp is). Fix the folder, or name a harness with Options::binary or ` +
|
|
55
|
+
`${BINARY_ENV}`);
|
|
56
|
+
}
|
|
57
|
+
function refuseFile(file, why) {
|
|
58
|
+
return new BinaryUnavailable(`the cached harness ${file} ${why}: it must be a regular file (not a symlink), owned by you, ` +
|
|
59
|
+
`not writable by group or others. Remove it, or name a harness with Options::binary or ` +
|
|
60
|
+
`${BINARY_ENV}`);
|
|
61
|
+
}
|
|
62
|
+
/** Every folder above `root`, top down (`/` first). */
|
|
63
|
+
function ancestors(root) {
|
|
64
|
+
const out = [];
|
|
65
|
+
let p = path.dirname(root);
|
|
66
|
+
for (;;) {
|
|
67
|
+
out.push(p);
|
|
68
|
+
const parent = path.dirname(p);
|
|
69
|
+
if (parent === p)
|
|
70
|
+
break;
|
|
71
|
+
p = parent;
|
|
72
|
+
}
|
|
73
|
+
return out.reverse();
|
|
74
|
+
}
|
|
75
|
+
/** Checks every ancestor of `<cache>`, top down. The path is taken as given,
|
|
76
|
+
* not resolved: a symlink on it (macOS's `/var`, say) is refused. */
|
|
77
|
+
async function checkAncestors(root) {
|
|
78
|
+
if (!path.isAbsolute(root))
|
|
79
|
+
throw refuseFolder(root, "is not an absolute path");
|
|
80
|
+
const me = euid();
|
|
81
|
+
for (const folder of ancestors(root)) {
|
|
82
|
+
let m;
|
|
83
|
+
try {
|
|
84
|
+
m = await fsp.lstat(folder);
|
|
85
|
+
}
|
|
86
|
+
catch (e) {
|
|
87
|
+
throw refuseAncestor(folder, `cannot be read (${reason(e)})`);
|
|
88
|
+
}
|
|
89
|
+
if (m.isSymbolicLink())
|
|
90
|
+
throw refuseAncestor(folder, "is a symlink");
|
|
91
|
+
if (!m.isDirectory())
|
|
92
|
+
throw refuseAncestor(folder, "is not a folder");
|
|
93
|
+
if (m.uid !== me && m.uid !== 0)
|
|
94
|
+
throw refuseAncestor(folder, "is owned by another user");
|
|
95
|
+
if (m.mode & 0o022 && !(m.mode & 0o1000))
|
|
96
|
+
throw refuseAncestor(folder, "is writable by group or others");
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
/** Checks one of the cache's own folders; `false` when it does not exist. */
|
|
100
|
+
async function checkFolder(folder) {
|
|
101
|
+
let m;
|
|
102
|
+
try {
|
|
103
|
+
m = await fsp.lstat(folder);
|
|
104
|
+
}
|
|
105
|
+
catch (e) {
|
|
106
|
+
if (code(e) === "ENOENT")
|
|
107
|
+
return false;
|
|
108
|
+
throw refuseFolder(folder, `cannot be read (${reason(e)})`);
|
|
109
|
+
}
|
|
110
|
+
if (m.isSymbolicLink())
|
|
111
|
+
throw refuseFolder(folder, "is a symlink");
|
|
112
|
+
if (!m.isDirectory())
|
|
113
|
+
throw refuseFolder(folder, "is not a folder");
|
|
114
|
+
if (m.uid !== euid())
|
|
115
|
+
throw refuseFolder(folder, "is owned by another user");
|
|
116
|
+
if (m.mode & 0o022)
|
|
117
|
+
throw refuseFolder(folder, "is writable by group or others");
|
|
118
|
+
return true;
|
|
119
|
+
}
|
|
120
|
+
async function hash(handle) {
|
|
121
|
+
const h = createHash("sha256");
|
|
122
|
+
const buf = Buffer.alloc(256 * 1024);
|
|
123
|
+
let position = 0;
|
|
124
|
+
for (;;) {
|
|
125
|
+
const { bytesRead } = await handle.read(buf, 0, buf.length, position);
|
|
126
|
+
if (bytesRead === 0)
|
|
127
|
+
return h.digest("hex");
|
|
128
|
+
h.update(buf.subarray(0, bytesRead));
|
|
129
|
+
position += bytesRead;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
/** R12.4: opens the cached file, checks it on the open file, and hashes it. */
|
|
133
|
+
export async function check(layout, executableSha256) {
|
|
134
|
+
await checkAncestors(layout.root);
|
|
135
|
+
for (const folder of layout.folders) {
|
|
136
|
+
if (!(await checkFolder(folder)))
|
|
137
|
+
return "missing";
|
|
138
|
+
}
|
|
139
|
+
const file = layout.file;
|
|
140
|
+
let handle;
|
|
141
|
+
try {
|
|
142
|
+
handle = await fsp.open(file, C.O_RDONLY | C.O_NOFOLLOW | C.O_NONBLOCK);
|
|
143
|
+
}
|
|
144
|
+
catch (e) {
|
|
145
|
+
if (code(e) === "ENOENT")
|
|
146
|
+
return "missing";
|
|
147
|
+
if (code(e) === "ELOOP")
|
|
148
|
+
throw refuseFile(file, "is a symlink");
|
|
149
|
+
throw refuseFile(file, `cannot be opened (${reason(e)})`);
|
|
150
|
+
}
|
|
151
|
+
try {
|
|
152
|
+
let m;
|
|
153
|
+
try {
|
|
154
|
+
m = await handle.stat();
|
|
155
|
+
}
|
|
156
|
+
catch (e) {
|
|
157
|
+
throw refuseFile(file, `cannot be read (${reason(e)})`);
|
|
158
|
+
}
|
|
159
|
+
if (!m.isFile())
|
|
160
|
+
throw refuseFile(file, "is not a regular file");
|
|
161
|
+
if (m.uid !== euid())
|
|
162
|
+
throw refuseFile(file, "is owned by another user");
|
|
163
|
+
if (m.mode & 0o022)
|
|
164
|
+
throw refuseFile(file, "is writable by group or others");
|
|
165
|
+
let digest;
|
|
166
|
+
try {
|
|
167
|
+
digest = await hash(handle);
|
|
168
|
+
}
|
|
169
|
+
catch (e) {
|
|
170
|
+
throw refuseFile(file, `cannot be read (${reason(e)})`);
|
|
171
|
+
}
|
|
172
|
+
return digest === executableSha256 ? "verified" : "mismatch";
|
|
173
|
+
}
|
|
174
|
+
finally {
|
|
175
|
+
await handle.close();
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
/** R12.3 writing: makes the missing folders (`0700`), writes `executable` to
|
|
179
|
+
* `.harness.<pid>.<random>.tmp` (created exclusively), checks it against the
|
|
180
|
+
* pinned digest, makes it `0755`, and renames it into place, over any file
|
|
181
|
+
* there. The temporary file is removed on any failure. */
|
|
182
|
+
export async function install(layout, executable, executableSha256) {
|
|
183
|
+
await checkAncestors(layout.root);
|
|
184
|
+
for (const folder of layout.folders) {
|
|
185
|
+
if (await checkFolder(folder))
|
|
186
|
+
continue;
|
|
187
|
+
try {
|
|
188
|
+
await fsp.mkdir(folder, { mode: 0o700 });
|
|
189
|
+
}
|
|
190
|
+
catch (e) {
|
|
191
|
+
// EEXIST: another program made it first; it is checked as any other.
|
|
192
|
+
if (code(e) !== "EEXIST")
|
|
193
|
+
throw refuseFolder(folder, `cannot be made (${reason(e)})`);
|
|
194
|
+
}
|
|
195
|
+
if (!(await checkFolder(folder)))
|
|
196
|
+
throw refuseFolder(folder, "vanished after it was made");
|
|
197
|
+
}
|
|
198
|
+
await sweepStale(layout.dir);
|
|
199
|
+
const tmp = path.join(layout.dir, `.harness.${process.pid}.${randomBytes(8).toString("hex")}.tmp`);
|
|
200
|
+
try {
|
|
201
|
+
await writeChecked(tmp, executable, executableSha256);
|
|
202
|
+
await fsp.rename(tmp, layout.file);
|
|
203
|
+
}
|
|
204
|
+
catch (e) {
|
|
205
|
+
await fsp.unlink(tmp).catch(() => undefined);
|
|
206
|
+
throw new BinaryUnavailable(`cannot write the harness into ${layout.dir} (${reason(e)}); nothing was cached`);
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
/** Removes stale `.harness.*.tmp` regular files from `dir`, each by name;
|
|
210
|
+
* nothing else is touched. */
|
|
211
|
+
async function sweepStale(dir) {
|
|
212
|
+
let names;
|
|
213
|
+
try {
|
|
214
|
+
names = await fsp.readdir(dir);
|
|
215
|
+
}
|
|
216
|
+
catch {
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
const now = Date.now();
|
|
220
|
+
for (const name of names) {
|
|
221
|
+
if (!(name.startsWith(".harness.") && name.endsWith(".tmp")))
|
|
222
|
+
continue;
|
|
223
|
+
const p = path.join(dir, name);
|
|
224
|
+
try {
|
|
225
|
+
const m = await fsp.lstat(p);
|
|
226
|
+
if (m.isFile() && now - m.mtimeMs > STALE_MS)
|
|
227
|
+
await fsp.unlink(p);
|
|
228
|
+
}
|
|
229
|
+
catch {
|
|
230
|
+
// Gone already, or another program's to finish.
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
async function writeChecked(tmp, executable, executableSha256) {
|
|
235
|
+
const handle = await fsp.open(tmp, C.O_RDWR | C.O_CREAT | C.O_EXCL | C.O_NOFOLLOW, 0o700);
|
|
236
|
+
try {
|
|
237
|
+
let done = 0;
|
|
238
|
+
while (done < executable.length) {
|
|
239
|
+
const { bytesWritten } = await handle.write(executable, done, executable.length - done, done);
|
|
240
|
+
done += bytesWritten;
|
|
241
|
+
}
|
|
242
|
+
// `fsync`. On macOS that stops at the drive's cache: Rust's `sync_all`
|
|
243
|
+
// uses `F_FULLFSYNC` there, which Node does not expose. The digest is
|
|
244
|
+
// checked again on every start, so a torn file is never run.
|
|
245
|
+
await handle.sync();
|
|
246
|
+
const digest = await hash(handle);
|
|
247
|
+
if (digest !== executableSha256) {
|
|
248
|
+
throw new Error(`the written file's SHA-256 is ${digest}, not the pinned ${executableSha256}`);
|
|
249
|
+
}
|
|
250
|
+
await handle.chmod(0o755);
|
|
251
|
+
await handle.sync();
|
|
252
|
+
}
|
|
253
|
+
finally {
|
|
254
|
+
await handle.close();
|
|
255
|
+
}
|
|
256
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/** The largest archive accepted. */
|
|
2
|
+
export declare const MAX_ARCHIVE: number;
|
|
3
|
+
/** Sets the whole-download deadline (tests only); no argument restores 120 s. */
|
|
4
|
+
export declare function setWholeDownloadMs(ms?: number): void;
|
|
5
|
+
/** The download is refused or failed; the text says why. */
|
|
6
|
+
export declare class DownloadError extends Error {
|
|
7
|
+
}
|
|
8
|
+
/** Whether `url` names a loopback host: an IPv4 127/8 address, `::1`, or
|
|
9
|
+
* `localhost`. */
|
|
10
|
+
export declare function loopback(url: URL): boolean;
|
|
11
|
+
/** Throws unless `url` is https, or http to a loopback host, with no user
|
|
12
|
+
* info. */
|
|
13
|
+
export declare function allowed(url: URL): void;
|
|
14
|
+
/** The archive at `url`, its SHA-256 checked against `archiveSha256`; a
|
|
15
|
+
* `DownloadError` with the full text otherwise. */
|
|
16
|
+
export declare function archive(url: string, archiveSha256: string): Promise<Buffer>;
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
// The release download (spec slice-ar R12.2): every hop https (http only to a
|
|
2
|
+
// loopback host), no user info in any URL, at most 5 redirects, the whole
|
|
3
|
+
// download within 120 s (connect, headers and body: a timer destroys the
|
|
4
|
+
// request), the archive at most 64 MiB, `Accept-Encoding: identity`; the
|
|
5
|
+
// digest is of the exact bytes received.
|
|
6
|
+
//
|
|
7
|
+
// Proxies come from the proxy environment variables (`HTTPS_PROXY`,
|
|
8
|
+
// `NO_PROXY`, …), as the Rust crate's reqwest and the Python SDK read them,
|
|
9
|
+
// through the `proxyEnv` agent option of Node 22.21+ and 24.5+; older Node
|
|
10
|
+
// (20, and 22 before 22.21) ignores the option and connects directly. A
|
|
11
|
+
// loopback release is never proxied: its hops get a plain agent.
|
|
12
|
+
import { createHash } from "node:crypto";
|
|
13
|
+
import * as http from "node:http";
|
|
14
|
+
import * as https from "node:https";
|
|
15
|
+
import { isIP } from "node:net";
|
|
16
|
+
/** The largest archive accepted. */
|
|
17
|
+
export const MAX_ARCHIVE = 64 * 1024 * 1024;
|
|
18
|
+
const MAX_REDIRECTS = 5;
|
|
19
|
+
const WHOLE_DOWNLOAD_MS = 120_000;
|
|
20
|
+
let wholeDownloadMs = WHOLE_DOWNLOAD_MS;
|
|
21
|
+
/** Sets the whole-download deadline (tests only); no argument restores 120 s. */
|
|
22
|
+
export function setWholeDownloadMs(ms = WHOLE_DOWNLOAD_MS) {
|
|
23
|
+
wholeDownloadMs = ms;
|
|
24
|
+
}
|
|
25
|
+
/** The download is refused or failed; the text says why. */
|
|
26
|
+
export class DownloadError extends Error {
|
|
27
|
+
}
|
|
28
|
+
/** Whether `url` names a loopback host: an IPv4 127/8 address, `::1`, or
|
|
29
|
+
* `localhost`. */
|
|
30
|
+
export function loopback(url) {
|
|
31
|
+
const host = url.hostname.replace(/^\[/, "").replace(/\]$/, "");
|
|
32
|
+
switch (isIP(host)) {
|
|
33
|
+
case 4:
|
|
34
|
+
return host.split(".")[0] === "127";
|
|
35
|
+
case 6:
|
|
36
|
+
// The WHATWG parser writes IPv6 compressed, so `::1` has one spelling.
|
|
37
|
+
return host === "::1";
|
|
38
|
+
default:
|
|
39
|
+
return host.toLowerCase() === "localhost";
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
/** Throws unless `url` is https, or http to a loopback host, with no user
|
|
43
|
+
* info. */
|
|
44
|
+
export function allowed(url) {
|
|
45
|
+
if (url.username !== "" || url.password !== "") {
|
|
46
|
+
throw new DownloadError(`${url.hostname || "a URL"} carries user info`);
|
|
47
|
+
}
|
|
48
|
+
if (url.protocol === "https:" || (url.protocol === "http:" && loopback(url)))
|
|
49
|
+
return;
|
|
50
|
+
throw new DownloadError(`${url.href} is not https`);
|
|
51
|
+
}
|
|
52
|
+
const REDIRECTS = new Set([301, 302, 303, 307, 308]);
|
|
53
|
+
/** The archive at `url`, its SHA-256 checked against `archiveSha256`; a
|
|
54
|
+
* `DownloadError` with the full text otherwise. */
|
|
55
|
+
export async function archive(url, archiveSha256) {
|
|
56
|
+
const fail = (why) => new DownloadError(`cannot download ${url}: ${why}; nothing was cached`);
|
|
57
|
+
let current;
|
|
58
|
+
try {
|
|
59
|
+
current = new URL(url);
|
|
60
|
+
allowed(current);
|
|
61
|
+
}
|
|
62
|
+
catch (e) {
|
|
63
|
+
throw fail(e instanceof Error ? e.message : String(e));
|
|
64
|
+
}
|
|
65
|
+
const seconds = wholeDownloadMs / 1000;
|
|
66
|
+
const late = `the download did not finish within ${seconds} s`;
|
|
67
|
+
let expired = false;
|
|
68
|
+
let live;
|
|
69
|
+
const timer = setTimeout(() => {
|
|
70
|
+
expired = true;
|
|
71
|
+
live?.destroy(new DownloadError(late));
|
|
72
|
+
}, wholeDownloadMs);
|
|
73
|
+
try {
|
|
74
|
+
// `hops` counts the requests made; the first plus 5 redirects at most.
|
|
75
|
+
for (let hops = 1;; hops++) {
|
|
76
|
+
const got = await get(current, (req) => {
|
|
77
|
+
live = req;
|
|
78
|
+
if (expired)
|
|
79
|
+
req.destroy(new DownloadError(late));
|
|
80
|
+
});
|
|
81
|
+
if (got.kind === "body") {
|
|
82
|
+
const digest = got.digest;
|
|
83
|
+
if (digest !== archiveSha256) {
|
|
84
|
+
throw fail(`the archive does not match its pinned SHA-256 (got ${digest}, pinned ${archiveSha256})`);
|
|
85
|
+
}
|
|
86
|
+
return got.body;
|
|
87
|
+
}
|
|
88
|
+
if (hops > MAX_REDIRECTS)
|
|
89
|
+
throw fail(`more than ${MAX_REDIRECTS} redirects`);
|
|
90
|
+
let next;
|
|
91
|
+
try {
|
|
92
|
+
next = new URL(got.location, current);
|
|
93
|
+
allowed(next);
|
|
94
|
+
}
|
|
95
|
+
catch (e) {
|
|
96
|
+
throw fail(`redirected: ${e instanceof Error ? e.message : String(e)}`);
|
|
97
|
+
}
|
|
98
|
+
current = next;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
catch (e) {
|
|
102
|
+
if (expired)
|
|
103
|
+
throw fail(late);
|
|
104
|
+
if (e instanceof DownloadError && e.message.startsWith("cannot download "))
|
|
105
|
+
throw e;
|
|
106
|
+
throw fail(e instanceof Error ? e.message : String(e));
|
|
107
|
+
}
|
|
108
|
+
finally {
|
|
109
|
+
clearTimeout(timer);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
/** One GET of `url`: its body (a 2xx), or where it redirects. `track` is
|
|
113
|
+
* given the request, so the deadline can destroy it. */
|
|
114
|
+
function get(url, track) {
|
|
115
|
+
return new Promise((resolve, reject) => {
|
|
116
|
+
const tls = url.protocol === "https:";
|
|
117
|
+
const options = {
|
|
118
|
+
method: "GET",
|
|
119
|
+
headers: { "Accept-Encoding": "identity" },
|
|
120
|
+
// Its own agent per request. Only https reaches a host that is not
|
|
121
|
+
// loopback (`allowed`), so only an https agent takes the proxies.
|
|
122
|
+
agent: loopback(url)
|
|
123
|
+
? tls
|
|
124
|
+
? new https.Agent({ keepAlive: false })
|
|
125
|
+
: new http.Agent({ keepAlive: false })
|
|
126
|
+
: new https.Agent({ keepAlive: false, proxyEnv: process.env }),
|
|
127
|
+
};
|
|
128
|
+
const req = (tls ? https.request : http.request)(url, options, (res) => {
|
|
129
|
+
const status = res.statusCode ?? 0;
|
|
130
|
+
const location = res.headers.location;
|
|
131
|
+
if (REDIRECTS.has(status) && location !== undefined) {
|
|
132
|
+
res.resume();
|
|
133
|
+
req.destroy();
|
|
134
|
+
resolve({ kind: "redirect", location });
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
if (status < 200 || status > 299) {
|
|
138
|
+
res.resume();
|
|
139
|
+
req.destroy();
|
|
140
|
+
reject(new DownloadError(`${status} ${http.STATUS_CODES[status] ?? ""}`.trimEnd()));
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
const over = new DownloadError("the archive is over 64 MiB");
|
|
144
|
+
const length = res.headers["content-length"];
|
|
145
|
+
if (length !== undefined && /^\d+$/.test(length.trim()) && Number(length) > MAX_ARCHIVE) {
|
|
146
|
+
req.destroy(over);
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
const chunks = [];
|
|
150
|
+
// Hashed as it arrives, never in one long call.
|
|
151
|
+
const hash = createHash("sha256");
|
|
152
|
+
let size = 0;
|
|
153
|
+
res.on("data", (chunk) => {
|
|
154
|
+
size += chunk.length;
|
|
155
|
+
if (size > MAX_ARCHIVE) {
|
|
156
|
+
req.destroy(over);
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
hash.update(chunk);
|
|
160
|
+
chunks.push(chunk);
|
|
161
|
+
});
|
|
162
|
+
res.on("end", () => {
|
|
163
|
+
if (res.complete)
|
|
164
|
+
resolve({ kind: "body", body: Buffer.concat(chunks, size), digest: hash.digest("hex") });
|
|
165
|
+
else
|
|
166
|
+
reject(new DownloadError("the connection closed before the whole archive arrived"));
|
|
167
|
+
});
|
|
168
|
+
res.on("error", reject);
|
|
169
|
+
});
|
|
170
|
+
track(req);
|
|
171
|
+
req.on("error", reject);
|
|
172
|
+
req.end();
|
|
173
|
+
});
|
|
174
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import type { Options } from "../options.js";
|
|
2
|
+
import * as download from "./download.js";
|
|
3
|
+
export { BINARY_ENV } from "./cache.js";
|
|
4
|
+
/** Where releases are downloaded from (`crates/cli/src/update.rs`'s `SITE_DL`). */
|
|
5
|
+
export declare const DEFAULT_BASE = "https://megacode-harness.vercel.app/dl";
|
|
6
|
+
/** Overrides `DEFAULT_BASE`. */
|
|
7
|
+
export declare const BASE_ENV = "MEGACODE_AGENT_SDK_DOWNLOAD_BASE";
|
|
8
|
+
/** The release targets (spec R12.6, `release.yml`'s matrix). */
|
|
9
|
+
export declare const TARGETS: readonly ["x86_64-unknown-linux-musl", "aarch64-apple-darwin", "x86_64-apple-darwin"];
|
|
10
|
+
export interface Pin {
|
|
11
|
+
readonly archiveSha256: string;
|
|
12
|
+
readonly executableSha256: string;
|
|
13
|
+
}
|
|
14
|
+
type Pins = Readonly<Record<string, Pin>>;
|
|
15
|
+
/** Replaces the pins `locate` reads (tests only); no arguments restore this
|
|
16
|
+
* package's. */
|
|
17
|
+
export declare function setPins(version?: string, pins?: Pins): void;
|
|
18
|
+
/** The binary a session runs (R12.1). */
|
|
19
|
+
export declare function locate(options: Options): Promise<string>;
|
|
20
|
+
/** The release target for `process.platform` and `process.arch`. Under
|
|
21
|
+
* Rosetta a Node built for x64 reports `x64`, and gets the x64 build. */
|
|
22
|
+
export declare function targetFor(platform: string, arch: string): string;
|
|
23
|
+
/** `<cache>` (R12.3): `~/Library/Caches` on macOS; elsewhere
|
|
24
|
+
* `$XDG_CACHE_HOME` when it is an absolute path, else `~/.cache`. */
|
|
25
|
+
export declare function cacheRootFrom(platform: string, xdgCacheHome: string | undefined, home: string | undefined): string;
|
|
26
|
+
/** The pin for `target` when the pins are for `version`; pins for another
|
|
27
|
+
* version are none. */
|
|
28
|
+
export declare function pinned(pinsVersion: string, pins: Pins, version: string, target: string): Pin | undefined;
|
|
29
|
+
/** One version's release for one target, where it is downloaded from, the
|
|
30
|
+
* cache it goes to, and its pins. */
|
|
31
|
+
export declare class Release {
|
|
32
|
+
readonly version: string;
|
|
33
|
+
readonly target: string;
|
|
34
|
+
readonly cache: string;
|
|
35
|
+
readonly archiveSha256: string;
|
|
36
|
+
readonly executableSha256: string;
|
|
37
|
+
readonly base: string;
|
|
38
|
+
constructor(version: string, target: string, base: string, cache: string, archiveSha256: string, executableSha256: string);
|
|
39
|
+
/** The verified cached executable, downloading it when it is missing or
|
|
40
|
+
* its digest is not the pinned one (R12.3–R12.4). Nothing that fails a
|
|
41
|
+
* check is run or kept. */
|
|
42
|
+
fetch(): Promise<string>;
|
|
43
|
+
/** The archive, checked, and the executable from it, checked; both in
|
|
44
|
+
* memory, before any folder or file is made. */
|
|
45
|
+
private download;
|
|
46
|
+
}
|
|
47
|
+
/** The archive reader, for tests. */
|
|
48
|
+
export declare const readArchive: (gz: Uint8Array) => Promise<Buffer>;
|
|
49
|
+
export declare const setWholeDownloadMs: typeof download.setWholeDownloadMs;
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
// Which harness binary a session runs (spec slice-ar R12). In order: the
|
|
2
|
+
// `binary` option; `MEGACODE_AGENT_SDK_BINARY`; the verified cache; a download
|
|
3
|
+
// of the exact matching release, checked against the digests pinned in this
|
|
4
|
+
// package (`pins.ts`).
|
|
5
|
+
import { createHash } from "node:crypto";
|
|
6
|
+
import * as path from "node:path";
|
|
7
|
+
import { BinaryUnavailable } from "../errors.js";
|
|
8
|
+
import { PINS, PINS_VERSION } from "../pins.js";
|
|
9
|
+
import { VERSION } from "../version.js";
|
|
10
|
+
import * as archive from "./archive.js";
|
|
11
|
+
import { BINARY_ENV, check, install, Layout } from "./cache.js";
|
|
12
|
+
import * as download from "./download.js";
|
|
13
|
+
export { BINARY_ENV } from "./cache.js";
|
|
14
|
+
/** Where releases are downloaded from (`crates/cli/src/update.rs`'s `SITE_DL`). */
|
|
15
|
+
export const DEFAULT_BASE = "https://megacode-harness.vercel.app/dl";
|
|
16
|
+
/** Overrides `DEFAULT_BASE`. */
|
|
17
|
+
export const BASE_ENV = "MEGACODE_AGENT_SDK_DOWNLOAD_BASE";
|
|
18
|
+
/** The release targets (spec R12.6, `release.yml`'s matrix). */
|
|
19
|
+
export const TARGETS = ["x86_64-unknown-linux-musl", "aarch64-apple-darwin", "x86_64-apple-darwin"];
|
|
20
|
+
let pinsInUse = { version: PINS_VERSION, pins: PINS };
|
|
21
|
+
/** Replaces the pins `locate` reads (tests only); no arguments restore this
|
|
22
|
+
* package's. */
|
|
23
|
+
export function setPins(version, pins) {
|
|
24
|
+
pinsInUse = version === undefined || pins === undefined ? { version: PINS_VERSION, pins: PINS } : { version, pins };
|
|
25
|
+
}
|
|
26
|
+
/** The binary a session runs (R12.1). */
|
|
27
|
+
export async function locate(options) {
|
|
28
|
+
const named = namedBinary(options.binary, process.env[BINARY_ENV]);
|
|
29
|
+
if (named !== undefined)
|
|
30
|
+
return named;
|
|
31
|
+
return current().fetch();
|
|
32
|
+
}
|
|
33
|
+
/** The binary the program named: the option, else the environment variable.
|
|
34
|
+
* Both are trusted as given. */
|
|
35
|
+
function namedBinary(option, env) {
|
|
36
|
+
if (option !== undefined)
|
|
37
|
+
return option;
|
|
38
|
+
if (env !== undefined && env !== "")
|
|
39
|
+
return env;
|
|
40
|
+
return undefined;
|
|
41
|
+
}
|
|
42
|
+
/** The release target for `process.platform` and `process.arch`. Under
|
|
43
|
+
* Rosetta a Node built for x64 reports `x64`, and gets the x64 build. */
|
|
44
|
+
export function targetFor(platform, arch) {
|
|
45
|
+
if (platform === "linux" && arch === "x64")
|
|
46
|
+
return TARGETS[0];
|
|
47
|
+
if (platform === "darwin" && arch === "arm64")
|
|
48
|
+
return TARGETS[1];
|
|
49
|
+
if (platform === "darwin" && arch === "x64")
|
|
50
|
+
return TARGETS[2];
|
|
51
|
+
throw new BinaryUnavailable(`no harness release is built for ${platform} on ${arch}: releases exist for ${TARGETS[0]}, ` +
|
|
52
|
+
`${TARGETS[1]} and ${TARGETS[2]}. Name an installed harness with the \`binary\` option ` +
|
|
53
|
+
`(Options::binary) or ${BINARY_ENV}`);
|
|
54
|
+
}
|
|
55
|
+
/** `<cache>` (R12.3): `~/Library/Caches` on macOS; elsewhere
|
|
56
|
+
* `$XDG_CACHE_HOME` when it is an absolute path, else `~/.cache`. */
|
|
57
|
+
export function cacheRootFrom(platform, xdgCacheHome, home) {
|
|
58
|
+
if (platform !== "darwin" && xdgCacheHome !== undefined && path.isAbsolute(xdgCacheHome))
|
|
59
|
+
return xdgCacheHome;
|
|
60
|
+
if (home === undefined || !path.isAbsolute(home)) {
|
|
61
|
+
throw new BinaryUnavailable("no cache folder for the harness download: HOME is not set to an absolute " +
|
|
62
|
+
`path. Name an installed harness with Options::binary or ${BINARY_ENV}`);
|
|
63
|
+
}
|
|
64
|
+
return platform === "darwin" ? path.join(home, "Library", "Caches") : path.join(home, ".cache");
|
|
65
|
+
}
|
|
66
|
+
/** The pin for `target` when the pins are for `version`; pins for another
|
|
67
|
+
* version are none. */
|
|
68
|
+
export function pinned(pinsVersion, pins, version, target) {
|
|
69
|
+
if (pinsVersion !== version)
|
|
70
|
+
return undefined;
|
|
71
|
+
return Object.prototype.hasOwnProperty.call(pins, target) ? pins[target] : undefined;
|
|
72
|
+
}
|
|
73
|
+
/** One version's release for one target, where it is downloaded from, the
|
|
74
|
+
* cache it goes to, and its pins. */
|
|
75
|
+
export class Release {
|
|
76
|
+
version;
|
|
77
|
+
target;
|
|
78
|
+
cache;
|
|
79
|
+
archiveSha256;
|
|
80
|
+
executableSha256;
|
|
81
|
+
base;
|
|
82
|
+
constructor(version, target, base, cache, archiveSha256, executableSha256) {
|
|
83
|
+
this.version = version;
|
|
84
|
+
this.target = target;
|
|
85
|
+
this.cache = cache;
|
|
86
|
+
this.archiveSha256 = archiveSha256;
|
|
87
|
+
this.executableSha256 = executableSha256;
|
|
88
|
+
this.base = base.replace(/\/+$/, "");
|
|
89
|
+
}
|
|
90
|
+
/** The verified cached executable, downloading it when it is missing or
|
|
91
|
+
* its digest is not the pinned one (R12.3–R12.4). Nothing that fails a
|
|
92
|
+
* check is run or kept. */
|
|
93
|
+
async fetch() {
|
|
94
|
+
const layout = new Layout(this.cache, this.version, this.target);
|
|
95
|
+
// A file with another digest is never run; the verified download is
|
|
96
|
+
// renamed over it. It is not removed first: another program may have
|
|
97
|
+
// renamed its own verified file into place since this check.
|
|
98
|
+
if ((await check(layout, this.executableSha256)) === "verified")
|
|
99
|
+
return layout.file;
|
|
100
|
+
const executable = await this.download();
|
|
101
|
+
await install(layout, executable, this.executableSha256);
|
|
102
|
+
if ((await check(layout, this.executableSha256)) !== "verified") {
|
|
103
|
+
throw new BinaryUnavailable(`the harness cached at ${layout.file} does not match its pinned SHA-256 after a fresh ` +
|
|
104
|
+
"download; it is not run");
|
|
105
|
+
}
|
|
106
|
+
return layout.file;
|
|
107
|
+
}
|
|
108
|
+
/** The archive, checked, and the executable from it, checked; both in
|
|
109
|
+
* memory, before any folder or file is made. */
|
|
110
|
+
async download() {
|
|
111
|
+
const url = `${this.base}/v${this.version}/harness-${this.target}.tar.gz`;
|
|
112
|
+
let gz;
|
|
113
|
+
try {
|
|
114
|
+
gz = await download.archive(url, this.archiveSha256);
|
|
115
|
+
}
|
|
116
|
+
catch (e) {
|
|
117
|
+
throw new BinaryUnavailable(e instanceof Error ? e.message : String(e));
|
|
118
|
+
}
|
|
119
|
+
let executable;
|
|
120
|
+
try {
|
|
121
|
+
executable = await archive.executable(gz);
|
|
122
|
+
}
|
|
123
|
+
catch (e) {
|
|
124
|
+
throw new BinaryUnavailable(`cannot use ${url}: ${e instanceof Error ? e.message : String(e)}; nothing was cached`);
|
|
125
|
+
}
|
|
126
|
+
const got = await sha256(executable);
|
|
127
|
+
if (got !== this.executableSha256) {
|
|
128
|
+
throw new BinaryUnavailable(`cannot use ${url}: the harness in the archive does not match its pinned SHA-256 ` +
|
|
129
|
+
`(got ${got}, pinned ${this.executableSha256}); nothing was cached`);
|
|
130
|
+
}
|
|
131
|
+
return executable;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
/** The SHA-256 of `data`, hashed 1 MiB at a time with a turn of the event
|
|
135
|
+
* loop between slices, so a large executable does not stall other sessions. */
|
|
136
|
+
async function sha256(data) {
|
|
137
|
+
const h = createHash("sha256");
|
|
138
|
+
const SLICE = 1024 * 1024;
|
|
139
|
+
for (let at = 0; at < data.length; at += SLICE) {
|
|
140
|
+
h.update(data.subarray(at, at + SLICE));
|
|
141
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
142
|
+
}
|
|
143
|
+
return h.digest("hex");
|
|
144
|
+
}
|
|
145
|
+
/** This package's version for this platform, with its pins. */
|
|
146
|
+
function current() {
|
|
147
|
+
const target = targetFor(process.platform, process.arch);
|
|
148
|
+
const pin = pinned(pinsInUse.version, pinsInUse.pins, VERSION, target);
|
|
149
|
+
if (pin === undefined) {
|
|
150
|
+
throw new BinaryUnavailable(`this build of megacode-agent-sdk ${VERSION} carries no pinned harness release ` +
|
|
151
|
+
`for ${target}, so it cannot download one. Name an installed harness with ` +
|
|
152
|
+
`Options::binary or ${BINARY_ENV}`);
|
|
153
|
+
}
|
|
154
|
+
const base = process.env[BASE_ENV] || DEFAULT_BASE;
|
|
155
|
+
const cache = cacheRootFrom(process.platform, process.env["XDG_CACHE_HOME"], process.env["HOME"]);
|
|
156
|
+
return new Release(VERSION, target, base, cache, pin.archiveSha256, pin.executableSha256);
|
|
157
|
+
}
|
|
158
|
+
/** The archive reader, for tests. */
|
|
159
|
+
export const readArchive = (gz) => archive.executable(gz);
|
|
160
|
+
export const setWholeDownloadMs = download.setWholeDownloadMs;
|