@prplkane/agentlink 0.0.0-stage → 0.3.0-beta.2
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 +201 -0
- package/NOTICE +15 -0
- package/README.md +296 -2
- package/docs/acp-qualification.md +165 -0
- package/docs/architecture.md +151 -0
- package/docs/laptop-testing.md +184 -0
- package/docs/licenses/roundtable-MIT.txt +21 -0
- package/examples/acp-check.mjs +33 -0
- package/examples/connect.mjs +40 -0
- package/package.json +41 -4
- package/src/artifacts.mjs +173 -0
- package/src/bridges.mjs +258 -0
- package/src/child-process.mjs +33 -0
- package/src/cli.mjs +38 -0
- package/src/client.mjs +309 -0
- package/src/discovery.mjs +168 -0
- package/src/doctor.mjs +63 -0
- package/src/gateway.mjs +106 -0
- package/src/index.mjs +232 -0
- package/src/management-cli.mjs +167 -0
- package/src/probe.mjs +57 -0
- package/src/process.mjs +112 -0
- package/src/profiles.mjs +107 -0
- package/src/providers.mjs +58 -0
- package/src/replace-file.mjs +14 -0
- package/src/runtime.mjs +87 -0
- package/src/storage.mjs +63 -0
- package/src/terminal-auth.mjs +62 -0
- package/src/version.mjs +1 -0
- package/src/wire.mjs +50 -0
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { gunzipSync, inflateRawSync } from 'node:zlib';
|
|
3
|
+
import { mkdir, readFile, writeFile } from 'node:fs/promises';
|
|
4
|
+
import { dirname } from 'node:path';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
import { inside } from './storage.mjs';
|
|
7
|
+
import { error } from './profiles.mjs';
|
|
8
|
+
|
|
9
|
+
export async function readArtifact(source, { maxBytes = 256 * 1024 * 1024, timeoutMs = 60000, offline = false, signal } = {}) {
|
|
10
|
+
signal?.throwIfAborted();
|
|
11
|
+
const url = new URL(source);
|
|
12
|
+
if (url.username || url.password || !['file:', 'https:'].includes(url.protocol)) {
|
|
13
|
+
throw error('INVALID_SOURCE', 'Use an HTTPS URL without embedded credentials, or an explicit file URL.');
|
|
14
|
+
}
|
|
15
|
+
if (url.protocol === 'file:') {
|
|
16
|
+
const { stat } = await import('node:fs/promises');
|
|
17
|
+
const path = fileURLToPath(url);
|
|
18
|
+
if ((await stat(path)).size > maxBytes) throw error('DOWNLOAD_LIMIT', 'Artifact exceeds the download limit.');
|
|
19
|
+
return readFile(path, { signal });
|
|
20
|
+
}
|
|
21
|
+
if (offline) throw error('OFFLINE', 'This artifact is not available locally.');
|
|
22
|
+
const deadline = signal ? AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]) : AbortSignal.timeout(timeoutMs);
|
|
23
|
+
let response, next = url;
|
|
24
|
+
for (let redirects = 0; ; redirects++) {
|
|
25
|
+
if (next.protocol !== 'https:' || next.username || next.password) {
|
|
26
|
+
throw error('INVALID_SOURCE', 'Artifact redirects must use HTTPS without embedded credentials.');
|
|
27
|
+
}
|
|
28
|
+
response = await fetch(next, { signal: deadline, redirect: 'manual' });
|
|
29
|
+
if (![301, 302, 303, 307, 308].includes(response.status)) break;
|
|
30
|
+
const location = response.headers.get('location');
|
|
31
|
+
await response.body?.cancel();
|
|
32
|
+
if (!location || redirects >= 5) throw error('DOWNLOAD_FAILED', 'Invalid or excessive artifact redirects.');
|
|
33
|
+
next = new URL(location, next);
|
|
34
|
+
}
|
|
35
|
+
if (!response.ok) {
|
|
36
|
+
await response.body?.cancel();
|
|
37
|
+
throw error('DOWNLOAD_FAILED', 'Artifact download failed (HTTP ' + response.status + ').');
|
|
38
|
+
}
|
|
39
|
+
const parts = []; let bytes = 0;
|
|
40
|
+
for await (const chunk of response.body) {
|
|
41
|
+
bytes += chunk.length;
|
|
42
|
+
if (bytes > maxBytes) throw error('DOWNLOAD_LIMIT', 'Artifact exceeds the download limit.');
|
|
43
|
+
parts.push(chunk);
|
|
44
|
+
}
|
|
45
|
+
return Buffer.concat(parts, bytes);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function checkDigest(bytes, expected) {
|
|
49
|
+
const actual = createHash('sha256').update(bytes).digest('hex');
|
|
50
|
+
if (expected !== undefined && (!/^[a-f0-9]{64}$/i.test(expected) || expected.toLowerCase() !== actual)) {
|
|
51
|
+
throw error('INTEGRITY_MISMATCH', 'Downloaded artifact does not match its SHA-256.');
|
|
52
|
+
}
|
|
53
|
+
return actual;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// Small archive reader for ordinary binary releases. Links, devices, traversal,
|
|
57
|
+
// duplicate paths, ZIP64 and unsupported formats fail before publication.
|
|
58
|
+
export async function extractArtifact(bytes, root, format, { maxBytes = 512 * 1024 * 1024, maxFiles = 10000 } = {}) {
|
|
59
|
+
let total = 0, count = 0;
|
|
60
|
+
const account = size => {
|
|
61
|
+
if (++count > maxFiles || (total += size) > maxBytes) throw error('EXTRACT_LIMIT', 'Archive exceeds the extraction limit.');
|
|
62
|
+
};
|
|
63
|
+
const reserve = (name, size, directory) => {
|
|
64
|
+
account(size);
|
|
65
|
+
if (directory && size) throw error('INVALID_ARCHIVE', 'Archive directories must not contain data.');
|
|
66
|
+
if (name === '.' || name === './') {
|
|
67
|
+
if (!directory) throw error('INVALID_ARCHIVE', 'The archive root must be an empty directory.');
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
if (!name || /[\\:\0-\x1f]/.test(name) || name.startsWith('/') || name.split('/').includes('..') ||
|
|
71
|
+
name.split('/').some(part => /[. ]$/.test(part) && part !== '.') ||
|
|
72
|
+
name.split('/').some(part => /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(part))) {
|
|
73
|
+
throw error('INVALID_ARCHIVE', 'Archive contains an unsafe path.');
|
|
74
|
+
}
|
|
75
|
+
return inside(root, name);
|
|
76
|
+
};
|
|
77
|
+
const put = async (path, data, directory) => {
|
|
78
|
+
if (path === undefined) return;
|
|
79
|
+
if (directory) await mkdir(path, { recursive: true });
|
|
80
|
+
else {
|
|
81
|
+
await mkdir(dirname(path), { recursive: true });
|
|
82
|
+
await writeFile(path, data, { flag: 'wx', mode: 0o644 });
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
if (format === 'tar.gz' || format === 'tgz') {
|
|
86
|
+
const tar = gunzipSync(bytes, { maxOutputLength: maxBytes + maxFiles * 1024 });
|
|
87
|
+
const str = value => new TextDecoder('utf-8', { fatal: true }).decode(value).split('\0')[0];
|
|
88
|
+
const octal = value => {
|
|
89
|
+
const text = str(value).trim();
|
|
90
|
+
if (!/^[0-7]*$/.test(text)) throw error('INVALID_ARCHIVE', 'Unsupported tar number.');
|
|
91
|
+
return text ? parseInt(text, 8) : 0;
|
|
92
|
+
};
|
|
93
|
+
let nextName;
|
|
94
|
+
for (let offset = 0; offset + 512 <= tar.length;) {
|
|
95
|
+
const head = tar.subarray(offset, offset + 512);
|
|
96
|
+
if (head.every(byte => byte === 0)) break;
|
|
97
|
+
const checksum = head.reduce((sum, byte, index) => sum + (index >= 148 && index < 156 ? 32 : byte), 0);
|
|
98
|
+
if (checksum !== octal(head.subarray(148, 156))) throw error('INVALID_ARCHIVE', 'Invalid tar checksum.');
|
|
99
|
+
const size = octal(head.subarray(124, 136));
|
|
100
|
+
const type = head[156];
|
|
101
|
+
const prefix = str(head.subarray(345, 500));
|
|
102
|
+
const name = nextName || (prefix ? prefix + '/' : '') + str(head.subarray(0, 100));
|
|
103
|
+
nextName = undefined;
|
|
104
|
+
if (size > maxBytes || offset + 512 + size > tar.length) throw error('INVALID_ARCHIVE', 'Truncated or oversized tar entry.');
|
|
105
|
+
const data = tar.subarray(offset + 512, offset + 512 + size);
|
|
106
|
+
offset += 512 + Math.ceil(size / 512) * 512;
|
|
107
|
+
if (type === 76) { account(size); nextName = str(data); continue; } // GNU long filename
|
|
108
|
+
if (type === 120 || type === 103) { // POSIX extended metadata
|
|
109
|
+
account(size);
|
|
110
|
+
for (let cursor = 0; cursor < data.length;) {
|
|
111
|
+
const space = data.indexOf(32, cursor);
|
|
112
|
+
const length = Number(data.subarray(cursor, space).toString('ascii'));
|
|
113
|
+
if (space < cursor || !Number.isSafeInteger(length) || length <= space - cursor + 1 || cursor + length > data.length) {
|
|
114
|
+
throw error('INVALID_ARCHIVE', 'Invalid tar extended metadata.');
|
|
115
|
+
}
|
|
116
|
+
const entry = data.subarray(space + 1, cursor + length - 1).toString('utf8');
|
|
117
|
+
if (entry.startsWith('path=')) {
|
|
118
|
+
if (type === 103) throw error('INVALID_ARCHIVE', 'Global tar paths are unsupported.');
|
|
119
|
+
nextName = entry.slice(5);
|
|
120
|
+
}
|
|
121
|
+
if (/^(linkpath|GNU\.sparse\.)/.test(entry)) throw error('INVALID_ARCHIVE', 'Tar links and sparse files are unsupported.');
|
|
122
|
+
cursor += length;
|
|
123
|
+
}
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
126
|
+
if (![0, 48, 53].includes(type)) throw error('INVALID_ARCHIVE', 'Only regular files and directories are supported in tar archives.');
|
|
127
|
+
await put(reserve(name, size, type === 53), data, type === 53);
|
|
128
|
+
}
|
|
129
|
+
} else if (format === 'zip') {
|
|
130
|
+
let end = -1;
|
|
131
|
+
for (let offset = bytes.length - 22; offset >= Math.max(0, bytes.length - 65557); offset--) {
|
|
132
|
+
if (bytes.readUInt32LE(offset) === 0x06054b50 && offset + 22 + bytes.readUInt16LE(offset + 20) === bytes.length) { end = offset; break; }
|
|
133
|
+
}
|
|
134
|
+
if (end < 0 || bytes.readUInt16LE(end + 4) || bytes.readUInt16LE(end + 6)) throw error('INVALID_ARCHIVE', 'Invalid or multi-disk ZIP.');
|
|
135
|
+
const entries = bytes.readUInt16LE(end + 10);
|
|
136
|
+
let offset = bytes.readUInt32LE(end + 16);
|
|
137
|
+
if (entries === 65535 || entries > maxFiles) throw error('INVALID_ARCHIVE', 'ZIP64 or excessive ZIP entries are unsupported.');
|
|
138
|
+
for (let index = 0; index < entries; index++) {
|
|
139
|
+
if (offset + 46 > bytes.length || bytes.readUInt32LE(offset) !== 0x02014b50) throw error('INVALID_ARCHIVE', 'Invalid ZIP directory.');
|
|
140
|
+
const flags = bytes.readUInt16LE(offset + 8), method = bytes.readUInt16LE(offset + 10);
|
|
141
|
+
const compressed = bytes.readUInt32LE(offset + 20), size = bytes.readUInt32LE(offset + 24);
|
|
142
|
+
const nameSize = bytes.readUInt16LE(offset + 28), extraSize = bytes.readUInt16LE(offset + 30), commentSize = bytes.readUInt16LE(offset + 32);
|
|
143
|
+
const mode = bytes.readUInt32LE(offset + 38) >>> 16, local = bytes.readUInt32LE(offset + 42);
|
|
144
|
+
if (flags & 1 || ![0, 8].includes(method) || (mode & 0xf000) === 0xa000 ||
|
|
145
|
+
local + 30 > bytes.length || bytes.readUInt32LE(local) !== 0x04034b50 ||
|
|
146
|
+
offset + 46 + nameSize + extraSize + commentSize > end) {
|
|
147
|
+
throw error('INVALID_ARCHIVE', 'Unsupported or oversized ZIP entry.');
|
|
148
|
+
}
|
|
149
|
+
const name = new TextDecoder('utf-8', { fatal: true }).decode(bytes.subarray(offset + 46, offset + 46 + nameSize));
|
|
150
|
+
const directory = name.endsWith('/') || (mode & 0xf000) === 0x4000;
|
|
151
|
+
// Reserve advertised expanded bytes before allocating or decompressing,
|
|
152
|
+
// including root and directory entries that will not be written.
|
|
153
|
+
const path = reserve(name, size, directory);
|
|
154
|
+
const start = local + 30 + bytes.readUInt16LE(local + 26) + bytes.readUInt16LE(local + 28);
|
|
155
|
+
if (start + compressed > bytes.length) throw error('INVALID_ARCHIVE', 'Truncated ZIP entry.');
|
|
156
|
+
const packed = bytes.subarray(start, start + compressed);
|
|
157
|
+
const data = method === 0 ? packed : inflateRawSync(packed, { maxOutputLength: Math.max(1, size) });
|
|
158
|
+
if (data.length !== size || crc32(data) !== bytes.readUInt32LE(offset + 16)) throw error('INVALID_ARCHIVE', 'Invalid ZIP contents.');
|
|
159
|
+
await put(path, data, directory);
|
|
160
|
+
offset += 46 + nameSize + extraSize + commentSize;
|
|
161
|
+
}
|
|
162
|
+
} else throw error('UNSUPPORTED_ARCHIVE', 'Managed binary releases support raw files, ZIP and tar.gz archives.');
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
const crcTable = Array.from({ length: 256 }, (_, value) => {
|
|
166
|
+
for (let bit = 0; bit < 8; bit++) value = value & 1 ? 0xedb88320 ^ value >>> 1 : value >>> 1;
|
|
167
|
+
return value >>> 0;
|
|
168
|
+
});
|
|
169
|
+
function crc32(bytes) {
|
|
170
|
+
let crc = 0xffffffff;
|
|
171
|
+
for (const byte of bytes) crc = crcTable[(crc ^ byte) & 255] ^ crc >>> 8;
|
|
172
|
+
return (crc ^ 0xffffffff) >>> 0;
|
|
173
|
+
}
|
package/src/bridges.mjs
ADDED
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { chmod, mkdir, open, readdir, realpath, rm, stat, unlink, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { basename, delimiter, dirname, join, resolve } from 'node:path';
|
|
4
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
5
|
+
import { error, profileName, strings } from './profiles.mjs';
|
|
6
|
+
import { BridgeRegistry } from './runtime.mjs';
|
|
7
|
+
import { inside, readJson, withLock, writeJson } from './storage.mjs';
|
|
8
|
+
import { readArtifact, checkDigest, extractArtifact } from './artifacts.mjs';
|
|
9
|
+
import { resolveCommand, runCommand } from './process.mjs';
|
|
10
|
+
import { inProbeDirectory, verifyAgent } from './discovery.mjs';
|
|
11
|
+
|
|
12
|
+
const npmName = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/;
|
|
13
|
+
const exactVersion = /^[0-9]+(?:\.[0-9A-Za-z+-]+)+$/;
|
|
14
|
+
export const environment = value => value === undefined || (value && typeof value === 'object' && !Array.isArray(value) &&
|
|
15
|
+
Object.entries(value).every(([key, item]) => /^[A-Za-z_][A-Za-z0-9_]*$/.test(key) && typeof item === 'string' && !item.includes('\0')));
|
|
16
|
+
const sourceURL = value => {
|
|
17
|
+
if (/^[a-z]+:\/\//i.test(value)) return new URL(value).href;
|
|
18
|
+
return pathToFileURL(resolve(value)).href;
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
async function fileLaunch(file, root) {
|
|
22
|
+
inside(root, await realpath(file));
|
|
23
|
+
const handle = await open(file, 'r'), bytes = Buffer.alloc(256);
|
|
24
|
+
let size;
|
|
25
|
+
try { size = (await handle.read(bytes, 0, bytes.length, 0)).bytesRead; } finally { await handle.close(); }
|
|
26
|
+
const header = bytes.subarray(0, size).toString('utf8');
|
|
27
|
+
return /\.(?:mjs|cjs|js)$/.test(file) || /^#!.*\bnode\b/.test(header)
|
|
28
|
+
? { command: process.execPath, prefixArgs: [file] } : { command: file, prefixArgs: [] };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
async function npmRunner(env) {
|
|
32
|
+
// npm's Windows launcher differs from ordinary npm-created package shims.
|
|
33
|
+
// Locate npm's JS entry directly and never invoke cmd.exe or a shell body.
|
|
34
|
+
const path = Object.entries(env).find(([key]) => key.toLowerCase() === 'path')?.[1] || '';
|
|
35
|
+
for (const directory of [dirname(process.execPath), ...path.split(delimiter).filter(Boolean)]) {
|
|
36
|
+
for (const file of [join(directory, 'node_modules/npm/bin/npm-cli.js'), join(directory, '../lib/node_modules/npm/bin/npm-cli.js')]) {
|
|
37
|
+
try { if ((await stat(file)).isFile()) return { command: process.execPath, args: [resolve(file)] }; }
|
|
38
|
+
catch (cause) { if (!['ENOENT', 'ENOTDIR'].includes(cause.code)) throw cause; }
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
if (process.platform !== 'win32') {
|
|
42
|
+
const found = await resolveCommand('npm', [], env);
|
|
43
|
+
return { command: found.command, args: found.prefixArgs };
|
|
44
|
+
}
|
|
45
|
+
throw error('INSTALLER_MISSING', 'npm is needed to install this bridge. Install Node.js with npm, or use an externally managed bridge.');
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export async function manifestSpec(source, { distribution, offline = false, version, signal } = {}) {
|
|
49
|
+
const url = sourceURL(source);
|
|
50
|
+
const entry = JSON.parse((await readArtifact(url, { maxBytes: 1024 * 1024, offline, signal })).toString('utf8'));
|
|
51
|
+
if (!entry.distribution || !entry.version) throw error('INVALID_MANIFEST', 'Provide an individual ACP registry agent entry, including version and distribution.');
|
|
52
|
+
if (version && version !== entry.version) throw error('INVALID_MANIFEST', 'This manifest pins version ' + entry.version + '. Supply a manifest for the requested version.');
|
|
53
|
+
const target = (process.platform === 'win32' ? 'windows' : process.platform) + '-' +
|
|
54
|
+
({ x64: 'x86_64', arm64: 'aarch64' }[process.arch] || process.arch);
|
|
55
|
+
const binary = entry.distribution.binary?.[target];
|
|
56
|
+
let kind = distribution || (binary ? 'binary' : entry.distribution.npx ? 'npm' : entry.distribution.uvx ? 'python' : undefined);
|
|
57
|
+
let spec;
|
|
58
|
+
if (kind === 'binary' && binary) {
|
|
59
|
+
spec = { kind, version: entry.version, url: binary.archive, sha256: binary.sha256, bin: binary.cmd,
|
|
60
|
+
args: binary.args || [], env: binary.env || {} };
|
|
61
|
+
} else if (kind === 'npm' && entry.distribution.npx) {
|
|
62
|
+
const value = entry.distribution.npx;
|
|
63
|
+
const match = /^((?:@[^/]+\/)?[^@]+)(?:@(.+))?$/.exec(value.package || '');
|
|
64
|
+
if (!match) throw error('INVALID_MANIFEST', 'Invalid npm package specification.');
|
|
65
|
+
if (match[2] && match[2] !== entry.version) throw error('INVALID_MANIFEST', 'Manifest and npm package versions disagree.');
|
|
66
|
+
spec = { kind, package: match[1], version: match[2] || entry.version, args: value.args || [], env: value.env || {} };
|
|
67
|
+
} else if (kind === 'python' && entry.distribution.uvx) {
|
|
68
|
+
const value = entry.distribution.uvx;
|
|
69
|
+
const match = /^([A-Za-z0-9_.-]+)(?:==(.+))?$/.exec(value.package || '');
|
|
70
|
+
if (!match) throw error('UNSUPPORTED_DISTRIBUTION', 'This Python package requires a custom installer; connect its installed executable instead.');
|
|
71
|
+
if (match[2] && match[2] !== entry.version) throw error('INVALID_MANIFEST', 'Manifest and Python package versions disagree.');
|
|
72
|
+
spec = { kind, package: match[1], version: match[2] || entry.version, args: value.args || [], env: value.env || {} };
|
|
73
|
+
} else throw error('UNSUPPORTED_DISTRIBUTION', 'No supported distribution for this platform. An installed ACP executable can still be configured directly.');
|
|
74
|
+
return { ...spec, manifestSource: url, sourcePage: entry.repository || entry.website };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function validateSpec(input) {
|
|
78
|
+
const spec = JSON.parse(JSON.stringify(input));
|
|
79
|
+
if (!['npm', 'python', 'binary'].includes(spec.kind) || !strings(spec.args ?? []) || !environment(spec.env)) {
|
|
80
|
+
throw error('INVALID_BRIDGE', 'Invalid bridge distribution or launch arguments.');
|
|
81
|
+
}
|
|
82
|
+
spec.args ??= []; spec.env ??= {};
|
|
83
|
+
if (spec.kind === 'npm' && !npmName.test(spec.package || '')) throw error('INVALID_BRIDGE', 'Use a registry npm package name.');
|
|
84
|
+
if (spec.kind === 'python' && !/^[A-Za-z0-9][A-Za-z0-9_.-]*$/.test(spec.package || '')) throw error('INVALID_BRIDGE', 'Invalid Python package name.');
|
|
85
|
+
if (spec.kind !== 'npm' && (typeof spec.version !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._+-]{0,127}$/.test(spec.version))) {
|
|
86
|
+
throw error('INVALID_BRIDGE', 'Pin a version for binary and Python bridges.');
|
|
87
|
+
}
|
|
88
|
+
if (spec.bin !== undefined && (typeof spec.bin !== 'string' || !spec.bin || spec.bin.includes('\0'))) throw error('INVALID_BRIDGE', 'Invalid executable name.');
|
|
89
|
+
if (spec.source) spec.source = sourceURL(spec.source);
|
|
90
|
+
if (spec.kind === 'binary') {
|
|
91
|
+
if (!spec.bin || !spec.url) throw error('INVALID_BRIDGE', 'Binary distributions need a URL and relative executable path.');
|
|
92
|
+
spec.url = sourceURL(spec.url);
|
|
93
|
+
if (/\.(?:tar\.bz2|tbz2|msi|dmg|pkg|deb|rpm)$/i.test(new URL(spec.url).pathname)) {
|
|
94
|
+
throw error('UNSUPPORTED_ARCHIVE', 'Use a ZIP, tar.gz or raw binary release, or connect an externally installed bridge.');
|
|
95
|
+
}
|
|
96
|
+
spec.format ??= /\.tar\.gz$|\.tgz$/i.test(new URL(spec.url).pathname) ? 'tar.gz' :
|
|
97
|
+
/\.zip$/i.test(new URL(spec.url).pathname) ? 'zip' : 'file';
|
|
98
|
+
}
|
|
99
|
+
return spec;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export class BridgeStore extends BridgeRegistry {
|
|
103
|
+
async install(id, input, { env = process.env, timeoutMs = 3000, installTimeoutMs = 180000,
|
|
104
|
+
offline = false, signal, validate, publish = record => this.publish(record) } = {}) {
|
|
105
|
+
profileName(id);
|
|
106
|
+
let spec = validateSpec(input);
|
|
107
|
+
await mkdir(this.installations, { recursive: true, mode: 0o700 });
|
|
108
|
+
const runnerOptions = { cwd: this.home, env, timeoutMs: installTimeoutMs, signal };
|
|
109
|
+
let npm;
|
|
110
|
+
if (spec.kind === 'npm') {
|
|
111
|
+
npm = await npmRunner(env);
|
|
112
|
+
const requested = spec.version || 'latest';
|
|
113
|
+
if (!exactVersion.test(requested)) {
|
|
114
|
+
if (!/^[A-Za-z][A-Za-z0-9._-]*$/.test(requested) || spec.source) throw error('INVALID_BRIDGE', 'Use an exact version or a registry tag.');
|
|
115
|
+
if (offline) throw error('OFFLINE', 'Offline npm installation needs an exact version.');
|
|
116
|
+
const value = await runCommand(npm.command, [...npm.args, 'view', spec.package + '@' + requested, 'version', '--json'], runnerOptions);
|
|
117
|
+
const version = JSON.parse(value);
|
|
118
|
+
if (typeof version !== 'string' || !exactVersion.test(version)) throw error('INVALID_BRIDGE', 'Registry did not resolve an exact package version.');
|
|
119
|
+
spec.version = version;
|
|
120
|
+
} else spec.version = requested;
|
|
121
|
+
}
|
|
122
|
+
const identity = { kind: spec.kind, package: spec.package, version: spec.version, source: spec.source,
|
|
123
|
+
url: spec.url, sha256: spec.sha256, format: spec.format,
|
|
124
|
+
bin: spec.kind === 'binary' ? spec.bin : undefined, platform: process.platform, arch: process.arch,
|
|
125
|
+
node: spec.kind === 'npm' ? process.versions.modules : undefined };
|
|
126
|
+
const installKey = createHash('sha256').update(JSON.stringify(identity)).digest('hex');
|
|
127
|
+
const root = inside(this.installations, installKey);
|
|
128
|
+
if (spec.kind === 'python' && process.platform === 'win32' && join(root, 'Scripts/python.exe').length >= 260) {
|
|
129
|
+
throw error('PYTHON_PATH_TOO_LONG', 'This managed Python environment needs a shorter path on Windows. ' +
|
|
130
|
+
'Choose a shorter absolute --home (or AGENTLINK_HOME), or connect an externally installed bridge. ' +
|
|
131
|
+
'The Python executable path would be ' + join(root, 'Scripts/python.exe').length + ' characters.');
|
|
132
|
+
}
|
|
133
|
+
return withLock(join(this.home, 'locks', installKey + '.lock'), async () => {
|
|
134
|
+
let metadata, created = false;
|
|
135
|
+
try {
|
|
136
|
+
try { metadata = await readJson(join(root, 'installation.json')); }
|
|
137
|
+
catch (cause) { if (cause.code !== 'ENOENT') throw cause; }
|
|
138
|
+
if (!metadata) {
|
|
139
|
+
// An unpublished, interrupted installation is never a runnable target.
|
|
140
|
+
try { await stat(root); throw error('INCOMPLETE_INSTALL', 'An interrupted installation remains at ' + root + '. Run agentlink bridge prune after its installer has stopped.'); }
|
|
141
|
+
catch (cause) { if (cause.code !== 'ENOENT') throw cause; }
|
|
142
|
+
await mkdir(root, { recursive: true, mode: 0o700 }); created = true;
|
|
143
|
+
let bins, digest;
|
|
144
|
+
if (spec.kind === 'npm') {
|
|
145
|
+
await writeJson(join(root, 'package.json'), { name: 'agentlink-managed-install', version: '1.0.0', private: true });
|
|
146
|
+
const source = spec.source ? new URL(spec.source) : undefined;
|
|
147
|
+
if (source && (source.username || source.password || !['file:', 'https:'].includes(source.protocol))) throw error('INVALID_SOURCE', 'Use file or HTTPS package sources without embedded credentials.');
|
|
148
|
+
if (offline && source && source.protocol !== 'file:') throw error('OFFLINE', 'Offline installation requires a local package artifact.');
|
|
149
|
+
const target = source ? source.protocol === 'file:' ? fileURLToPath(source) : source.href : spec.package + '@' + spec.version;
|
|
150
|
+
await runCommand(npm.command, [...npm.args, 'install', '--prefix', root, '--cache', join(this.home, 'cache/npm'),
|
|
151
|
+
'--no-audit', '--no-fund', '--omit=dev', '--save-exact', '--install-links', '--loglevel=error',
|
|
152
|
+
...(offline ? ['--offline'] : []), target], { ...runnerOptions, cwd: root });
|
|
153
|
+
const packageRoot = inside(root, 'node_modules/' + spec.package);
|
|
154
|
+
const pkg = await readJson(join(packageRoot, 'package.json'));
|
|
155
|
+
if (pkg.name !== spec.package || pkg.version !== spec.version) throw error('PACKAGE_MISMATCH', 'Installed package identity differs from the selected bridge.');
|
|
156
|
+
const entries = typeof pkg.bin === 'string' ? { [basename(spec.package)]: pkg.bin } : pkg.bin;
|
|
157
|
+
if (!entries || !Object.keys(entries).length) throw error('EXECUTABLE_MISSING', 'The package exposes no command-line executable.');
|
|
158
|
+
bins = Object.create(null);
|
|
159
|
+
for (const [name, relative] of Object.entries(entries)) {
|
|
160
|
+
const file = inside(packageRoot, relative);
|
|
161
|
+
bins[name] = await fileLaunch(file, root);
|
|
162
|
+
}
|
|
163
|
+
} else if (spec.kind === 'python') {
|
|
164
|
+
const python = await resolveCommand(process.platform === 'win32' ? 'python' : 'python3', [], env);
|
|
165
|
+
await runCommand(python.command, [...python.prefixArgs, '-m', 'venv', root], runnerOptions);
|
|
166
|
+
const interpreter = join(root, process.platform === 'win32' ? 'Scripts/python.exe' : 'bin/python');
|
|
167
|
+
let target = spec.package + '==' + spec.version;
|
|
168
|
+
if (spec.source) {
|
|
169
|
+
const url = new URL(spec.source);
|
|
170
|
+
if (url.protocol === 'file:') target = fileURLToPath(url);
|
|
171
|
+
else {
|
|
172
|
+
const bytes = await readArtifact(url.href, { offline, signal });
|
|
173
|
+
target = inside(root, basename(url.pathname));
|
|
174
|
+
await writeFile(target, bytes, { flag: 'wx' });
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
await runCommand(interpreter, ['-m', 'pip', 'install', '--disable-pip-version-check', '--no-input', '--no-compile',
|
|
178
|
+
'--cache-dir', join(this.home, 'cache/pip'),
|
|
179
|
+
...(offline ? ['--no-index'] : []), target], runnerOptions);
|
|
180
|
+
const script = 'import importlib.metadata,json,sys; d=importlib.metadata.distribution(sys.argv[1]); print(json.dumps({"version":d.version,"bins":[e.name for e in d.entry_points if e.group=="console_scripts"]}))';
|
|
181
|
+
const pkg = JSON.parse(await runCommand(interpreter, ['-c', script, spec.package], runnerOptions));
|
|
182
|
+
if (pkg.version !== spec.version) throw error('PACKAGE_MISMATCH', 'Installed Python version differs from the selected bridge.');
|
|
183
|
+
bins = Object.fromEntries(pkg.bins.map(name => [name, {
|
|
184
|
+
command: inside(root, (process.platform === 'win32' ? 'Scripts/' + name + '.exe' : 'bin/' + name)), prefixArgs: []
|
|
185
|
+
}]));
|
|
186
|
+
} else {
|
|
187
|
+
const bytes = await readArtifact(spec.url, { offline, signal });
|
|
188
|
+
digest = checkDigest(bytes, spec.sha256);
|
|
189
|
+
const file = inside(root, spec.bin);
|
|
190
|
+
if (spec.format === 'file') { await mkdir(dirname(file), { recursive: true }); await writeFile(file, bytes, { flag: 'wx', mode: 0o755 }); }
|
|
191
|
+
else await extractArtifact(bytes, root, spec.format);
|
|
192
|
+
await chmod(file, 0o755);
|
|
193
|
+
bins = { [basename(spec.bin)]: await fileLaunch(file, root) };
|
|
194
|
+
}
|
|
195
|
+
metadata = { installKey, bins, digest, createdAt: new Date().toISOString(), identity };
|
|
196
|
+
await writeJson(join(root, 'installation.json'), metadata);
|
|
197
|
+
}
|
|
198
|
+
if (metadata.installKey !== installKey) throw error('INVALID_BRIDGE', 'Installation metadata mismatch.');
|
|
199
|
+
const names = Object.keys(metadata.bins);
|
|
200
|
+
const bin = spec.kind === 'binary' ? basename(spec.bin) : spec.bin || (names.length === 1 ? names[0] : basename(spec.package));
|
|
201
|
+
if (!Object.hasOwn(metadata.bins, bin)) throw error('EXECUTABLE_MISSING', 'Select an executable with --bin. Available: ' + names.join(', '));
|
|
202
|
+
const launch = { ...metadata.bins[bin], acpArgs: spec.args, env: spec.env };
|
|
203
|
+
if (process.platform === 'win32' && /\.(cmd|bat|ps1)$/i.test(launch.command)) throw error('UNSUPPORTED_LAUNCHER', 'Use a native or Node entry point for this managed bridge.');
|
|
204
|
+
const verification = await inProbeDirectory(cwd => verifyAgent(launch, { cwd, env, timeoutMs, signal }));
|
|
205
|
+
await validate?.(launch);
|
|
206
|
+
signal?.throwIfAborted();
|
|
207
|
+
const record = { schemaVersion: 1, id, installKey, spec, launch, verification, updatedAt: new Date().toISOString() };
|
|
208
|
+
await publish(record);
|
|
209
|
+
return record;
|
|
210
|
+
} catch (cause) {
|
|
211
|
+
if (created) {
|
|
212
|
+
// Never delete an installation that a successful/partially recovered
|
|
213
|
+
// publication may reference. Uncertain metadata is left for pruning.
|
|
214
|
+
const records = await this.list().catch(() => [{ error: true }]);
|
|
215
|
+
if (!records.some(record => record.error || record.installKey === installKey)) {
|
|
216
|
+
inside(this.installations, root); await rm(root, { recursive: true, force: true });
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
throw cause;
|
|
220
|
+
}
|
|
221
|
+
}, installTimeoutMs, signal);
|
|
222
|
+
}
|
|
223
|
+
async prune({ cache = false, profiles = [] } = {}) {
|
|
224
|
+
const records = await this.list();
|
|
225
|
+
if (records.some(record => record.error)) throw error('INVALID_BRIDGE', 'Repair unreadable bridge records before pruning installations.');
|
|
226
|
+
const used = new Set(records.map(record => record.installKey));
|
|
227
|
+
for (const profile of profiles) {
|
|
228
|
+
if (profile.bridge) continue; // Managed profiles resolve the active record, not their old snapshot.
|
|
229
|
+
for (const key of this.referencedInstallations(profile)) used.add(key);
|
|
230
|
+
}
|
|
231
|
+
let leases = [], installations = [];
|
|
232
|
+
try { leases = await readdir(this.leases); } catch (cause) { if (cause.code !== 'ENOENT') throw cause; }
|
|
233
|
+
for (const name of leases) {
|
|
234
|
+
if (!name.endsWith('.json')) continue;
|
|
235
|
+
const file = inside(this.leases, name), lease = await readJson(file);
|
|
236
|
+
if (!Number.isSafeInteger(lease.pid) || lease.pid < 1) throw error('INVALID_BRIDGE', 'Invalid running-connection lease.');
|
|
237
|
+
let alive = true;
|
|
238
|
+
try { process.kill(lease.pid, 0); } catch (cause) { if (cause.code === 'ESRCH') alive = false; else throw cause; }
|
|
239
|
+
if (alive) used.add(lease.installKey); else await unlink(file);
|
|
240
|
+
}
|
|
241
|
+
try { installations = await readdir(this.installations); } catch (cause) { if (cause.code !== 'ENOENT') throw cause; }
|
|
242
|
+
const removed = [];
|
|
243
|
+
for (const key of installations) {
|
|
244
|
+
if (!/^[a-f0-9]{64}$/.test(key) || used.has(key)) continue;
|
|
245
|
+
const path = inside(this.installations, key);
|
|
246
|
+
inside(await realpath(this.installations), await realpath(path));
|
|
247
|
+
await rm(path, { recursive: true, force: true }); removed.push(key);
|
|
248
|
+
}
|
|
249
|
+
if (cache) {
|
|
250
|
+
const path = inside(this.home, 'cache');
|
|
251
|
+
try {
|
|
252
|
+
inside(await realpath(this.home), await realpath(path));
|
|
253
|
+
await rm(path, { recursive: true, force: true });
|
|
254
|
+
} catch (cause) { if (cause.code !== 'ENOENT') throw cause; }
|
|
255
|
+
}
|
|
256
|
+
return { removed, ...(cache ? { cacheCleared: true } : {}) };
|
|
257
|
+
}
|
|
258
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { error } from './profiles.mjs';
|
|
4
|
+
|
|
5
|
+
function waitForExit(child, timeoutMs) {
|
|
6
|
+
if (child.exitCode !== null || child.signalCode !== null || !child.pid) return Promise.resolve();
|
|
7
|
+
return new Promise((resolveExit, reject) => {
|
|
8
|
+
const finish = () => { clearTimeout(timer); child.off('exit', finish); resolveExit(); };
|
|
9
|
+
const timer = setTimeout(() => { child.off('exit', finish); reject(error('PROCESS_STOP_FAILED', 'Child process did not exit.')); }, timeoutMs);
|
|
10
|
+
child.once('exit', finish);
|
|
11
|
+
});
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export async function stopProcess(child) {
|
|
15
|
+
if (child.pid) {
|
|
16
|
+
if (process.platform === 'win32') {
|
|
17
|
+
if (child.exitCode === null && child.signalCode === null) {
|
|
18
|
+
const killer = spawn(join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'taskkill.exe'),
|
|
19
|
+
['/PID', String(child.pid), '/T', '/F'], { shell: false, windowsHide: true, stdio: 'ignore' });
|
|
20
|
+
await new Promise(resolveStop => {
|
|
21
|
+
const finish = () => { clearTimeout(timer); resolveStop(); };
|
|
22
|
+
const timer = setTimeout(() => { killer.kill(); finish(); }, 1500);
|
|
23
|
+
killer.once('error', finish); killer.once('exit', finish);
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
} else {
|
|
27
|
+
try { process.kill(-child.pid, 'SIGKILL'); }
|
|
28
|
+
catch (cause) { if (cause.code !== 'ESRCH') throw cause; }
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
try { await waitForExit(child, 1500); }
|
|
32
|
+
finally { child.stdin?.destroy(); child.stdout?.destroy(); child.stderr?.destroy(); }
|
|
33
|
+
}
|
package/src/cli.mjs
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { AgentRuntime } from './runtime.mjs';
|
|
3
|
+
import { runGateway } from './gateway.mjs';
|
|
4
|
+
import { profileName } from './profiles.mjs';
|
|
5
|
+
import { version } from './version.mjs';
|
|
6
|
+
|
|
7
|
+
function gatewayInvocation(argv) {
|
|
8
|
+
let index = 0, home;
|
|
9
|
+
if (argv[index] === '--home') { home = argv[index + 1]; index += 2; }
|
|
10
|
+
else if (argv[index]?.startsWith('--home=')) { home = argv[index].slice(7); index++; }
|
|
11
|
+
if (argv[index] !== 'acp') return;
|
|
12
|
+
const name = argv[index + 1];
|
|
13
|
+
if (name === '--help' || name === '-h') return { help: true };
|
|
14
|
+
profileName(name);
|
|
15
|
+
return { home, name, extraArgs: argv.slice(index + 2) };
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const abort = new AbortController();
|
|
19
|
+
const interrupt = () => abort.abort();
|
|
20
|
+
process.on('SIGINT', interrupt); process.on('SIGTERM', interrupt);
|
|
21
|
+
try {
|
|
22
|
+
const ownVersion = process.argv.length === 3 && ['--version', '-V'].includes(process.argv[2]);
|
|
23
|
+
const gateway = ownVersion ? undefined : gatewayInvocation(process.argv.slice(2));
|
|
24
|
+
if (ownVersion) process.stdout.write(version + '\n');
|
|
25
|
+
else if (gateway?.help) (await import('./management-cli.mjs')).printHelp();
|
|
26
|
+
else if (gateway) {
|
|
27
|
+
const runtime = new AgentRuntime({ ...(gateway.home ? { home: gateway.home } : {}), signal: abort.signal });
|
|
28
|
+
const { launch, release } = await runtime.acquire(gateway.name);
|
|
29
|
+
try {
|
|
30
|
+
process.exitCode = (await runGateway(launch, { extraArgs: gateway.extraArgs, signal: abort.signal })).exitCode;
|
|
31
|
+
} finally { await release(); }
|
|
32
|
+
} else {
|
|
33
|
+
await (await import('./management-cli.mjs')).runManagement(process.argv.slice(2), { signal: abort.signal, cliURL: import.meta.url });
|
|
34
|
+
}
|
|
35
|
+
} catch (cause) {
|
|
36
|
+
process.stderr.write((cause.code || 'INVALID_ARGUMENT') + ': ' + cause.message + '\n');
|
|
37
|
+
process.exitCode = abort.signal.aborted ? 130 : 1;
|
|
38
|
+
} finally { process.off('SIGINT', interrupt); process.off('SIGTERM', interrupt); }
|