@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
package/src/profiles.mjs
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { homedir } from 'node:os';
|
|
2
|
+
import { isAbsolute, join, resolve } from 'node:path';
|
|
3
|
+
import { link, mkdir, open, readdir, readFile, stat, unlink } from 'node:fs/promises';
|
|
4
|
+
import { randomUUID } from 'node:crypto';
|
|
5
|
+
import { replaceFile } from './replace-file.mjs';
|
|
6
|
+
|
|
7
|
+
export const error = (code, message) => Object.assign(new Error(message), { code });
|
|
8
|
+
export const strings = value => Array.isArray(value) && value.every(item => typeof item === 'string' && !item.includes('\0'));
|
|
9
|
+
const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
10
|
+
|
|
11
|
+
export function profileName(name) {
|
|
12
|
+
if (typeof name !== 'string' || !/^[a-z0-9][a-z0-9_-]{0,63}$/.test(name) ||
|
|
13
|
+
/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/.test(name)) {
|
|
14
|
+
throw error('INVALID_PROFILE', 'Profile names must use 1–64 lowercase letters, digits, underscores or hyphens (no reserved device names).');
|
|
15
|
+
}
|
|
16
|
+
return name;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function validateProfile(profile) {
|
|
20
|
+
if (!object(profile) || profile.schemaVersion !== 1) throw error('INVALID_PROFILE', 'Unsupported profile schema.');
|
|
21
|
+
profileName(profile.name);
|
|
22
|
+
if (typeof profile.command !== 'string' || !isAbsolute(profile.command) || profile.command.includes('\0') ||
|
|
23
|
+
!strings(profile.prefixArgs) || !strings(profile.acpArgs) || ![1, 2].includes(profile.protocolVersion) ||
|
|
24
|
+
!object(profile.discovery) || !['known', 'help', 'manual', 'metadata'].includes(profile.discovery.method) ||
|
|
25
|
+
!object(profile.verification) || !['initialize-passed', 'pending'].includes(profile.verification.status) ||
|
|
26
|
+
typeof profile.createdAt !== 'string' || typeof profile.updatedAt !== 'string') {
|
|
27
|
+
throw error('INVALID_PROFILE', 'Invalid ACP launch profile.');
|
|
28
|
+
}
|
|
29
|
+
if (profile.bridge !== undefined) {
|
|
30
|
+
if (!object(profile.bridge) || typeof profile.bridge.useDefaultArgs !== 'boolean') throw error('INVALID_PROFILE', 'Invalid managed bridge reference.');
|
|
31
|
+
profileName(profile.bridge.id);
|
|
32
|
+
}
|
|
33
|
+
if (profile.env !== undefined && (!object(profile.env) || Object.entries(profile.env).some(([key, value]) =>
|
|
34
|
+
!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key) || typeof value !== 'string' || value.includes('\0')))) {
|
|
35
|
+
throw error('INVALID_PROFILE', 'Invalid launch environment.');
|
|
36
|
+
}
|
|
37
|
+
if (profile.discovery.helpArgs !== undefined && !strings(profile.discovery.helpArgs)) throw error('INVALID_PROFILE', 'Invalid help arguments.');
|
|
38
|
+
// Return an owned JSON value; profiles never contain executable JavaScript.
|
|
39
|
+
return JSON.parse(JSON.stringify(profile));
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export class ProfileStore {
|
|
43
|
+
constructor({ home = process.env.AGENTLINK_HOME || join(homedir(), '.agentlink') } = {}) {
|
|
44
|
+
if (typeof home !== 'string' || !isAbsolute(home)) throw new TypeError('AgentLink home must be an absolute path.');
|
|
45
|
+
this.home = resolve(home);
|
|
46
|
+
this.directory = join(this.home, 'profiles');
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
path(name) { return join(this.directory, `${profileName(name)}.json`); }
|
|
50
|
+
|
|
51
|
+
async get(name) {
|
|
52
|
+
const path = this.path(name);
|
|
53
|
+
try {
|
|
54
|
+
if ((await stat(path)).size > 256 * 1024) throw error('INVALID_PROFILE', 'Profile exceeds 256 KiB.');
|
|
55
|
+
const profile = validateProfile(JSON.parse(await readFile(path, 'utf8')));
|
|
56
|
+
if (profile.name !== name) throw error('INVALID_PROFILE', 'Profile name does not match its filename.');
|
|
57
|
+
return profile;
|
|
58
|
+
} catch (cause) {
|
|
59
|
+
if (cause.code === 'ENOENT') throw error('PROFILE_NOT_FOUND', `No profile named "${name}". Add it once with agentlink add.`);
|
|
60
|
+
if (cause instanceof SyntaxError) throw error('INVALID_PROFILE', `Profile "${name}" is not valid JSON.`);
|
|
61
|
+
throw cause;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
async list() {
|
|
66
|
+
let files;
|
|
67
|
+
try { files = await readdir(this.directory); }
|
|
68
|
+
catch (cause) { if (cause.code === 'ENOENT') return []; throw cause; }
|
|
69
|
+
const result = [];
|
|
70
|
+
for (const file of files.sort()) {
|
|
71
|
+
if (!file.endsWith('.json')) continue;
|
|
72
|
+
const name = file.slice(0, -5);
|
|
73
|
+
try { result.push(await this.get(name)); }
|
|
74
|
+
catch (cause) { result.push({ name, error: { code: cause.code || 'READ_FAILED', message: cause.message } }); }
|
|
75
|
+
}
|
|
76
|
+
return result;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
async save(value, { replace = false } = {}) {
|
|
80
|
+
const profile = validateProfile(value);
|
|
81
|
+
const destination = this.path(profile.name);
|
|
82
|
+
const data = JSON.stringify(profile, null, 2) + '\n';
|
|
83
|
+
if (Buffer.byteLength(data) > 256 * 1024) throw error('INVALID_PROFILE', 'Profile exceeds 256 KiB.');
|
|
84
|
+
await mkdir(this.directory, { recursive: true, mode: 0o700 });
|
|
85
|
+
const temporary = join(this.directory, `.${profile.name}-${randomUUID()}.tmp`);
|
|
86
|
+
try {
|
|
87
|
+
const handle = await open(temporary, 'wx', 0o600);
|
|
88
|
+
try { await handle.writeFile(data); await handle.sync(); }
|
|
89
|
+
finally { await handle.close(); }
|
|
90
|
+
// A hard link publishes a complete new file without overwriting another user's
|
|
91
|
+
// concurrent add. Updates use rename so readers see the old or the new JSON.
|
|
92
|
+
if (replace) await replaceFile(temporary, destination);
|
|
93
|
+
else await link(temporary, destination);
|
|
94
|
+
} catch (cause) {
|
|
95
|
+
if (cause.code === 'EEXIST') throw error('PROFILE_EXISTS', `Profile "${profile.name}" already exists. Use update or refresh.`);
|
|
96
|
+
throw cause;
|
|
97
|
+
} finally {
|
|
98
|
+
await unlink(temporary).catch(cause => { if (cause.code !== 'ENOENT') throw cause; });
|
|
99
|
+
}
|
|
100
|
+
return profile;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
async remove(name) {
|
|
104
|
+
try { await unlink(this.path(name)); }
|
|
105
|
+
catch (cause) { if (cause.code === 'ENOENT') throw error('PROFILE_NOT_FOUND', `No profile named "${name}".`); throw cause; }
|
|
106
|
+
}
|
|
107
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
// Documented ACP launch recipes, not claims of live-vendor test coverage.
|
|
2
|
+
// Launch recipes. The manager installs selected package-backed bridges;
|
|
3
|
+
// inspection only discovers executables that are already installed.
|
|
4
|
+
const recipes = {
|
|
5
|
+
codex: Object.freeze({
|
|
6
|
+
kind: 'external-acp-bridge', args: [],
|
|
7
|
+
executableName: 'codex-acp',
|
|
8
|
+
source: 'https://github.com/agentclientprotocol/codex-acp',
|
|
9
|
+
package: '@agentclientprotocol/codex-acp',
|
|
10
|
+
note: 'The npm bridge includes a Codex dependency; count it separately.'
|
|
11
|
+
}),
|
|
12
|
+
claude: Object.freeze({
|
|
13
|
+
kind: 'external-acp-bridge', args: [],
|
|
14
|
+
executableName: 'claude-agent-acp',
|
|
15
|
+
source: 'https://github.com/agentclientprotocol/claude-agent-acp',
|
|
16
|
+
package: '@agentclientprotocol/claude-agent-acp',
|
|
17
|
+
note: 'Uses the Claude Agent SDK, which is an external dependency.'
|
|
18
|
+
}),
|
|
19
|
+
kimi: Object.freeze({
|
|
20
|
+
kind: 'native-acp', args: ['acp'], executableName: 'kimi',
|
|
21
|
+
source: 'https://github.com/MoonshotAI/kimi-code',
|
|
22
|
+
note: 'The old Python kimi-cli repository is archived.'
|
|
23
|
+
}),
|
|
24
|
+
opencode: { kind: 'native-acp', args: ['acp'], executableName: 'opencode',
|
|
25
|
+
source: 'https://opencode.ai/docs/acp/' },
|
|
26
|
+
qwen: { kind: 'native-acp', args: ['--acp'], executableName: 'qwen',
|
|
27
|
+
source: 'https://qwenlm.github.io/qwen-code-docs/en/users/integration-zed/' },
|
|
28
|
+
gemini: { kind: 'native-acp', args: ['--acp'], executableName: 'gemini',
|
|
29
|
+
source: 'https://geminicli.com/docs/cli/acp-mode/' },
|
|
30
|
+
cursor: { kind: 'native-acp', args: ['acp'], executableName: 'agent',
|
|
31
|
+
explicitMatch: true, source: 'https://cursor.com/docs/cli/acp' },
|
|
32
|
+
copilot: { kind: 'native-acp', args: ['--acp', '--stdio'], executableName: 'copilot',
|
|
33
|
+
source: 'https://docs.github.com/en/copilot/reference/copilot-cli-reference/acp-server' },
|
|
34
|
+
cline: { kind: 'native-acp', args: ['--acp'], executableName: 'cline',
|
|
35
|
+
source: 'https://github.com/cline/cline/blob/main/apps/cli/README.md' },
|
|
36
|
+
auggie: { kind: 'native-acp', args: ['--acp'], executableName: 'auggie',
|
|
37
|
+
source: 'https://docs.augmentcode.com/cli/v0/acp/agent' },
|
|
38
|
+
vibe: { kind: 'native-acp', args: [], executableName: 'vibe-acp',
|
|
39
|
+
source: 'https://github.com/mistralai/mistral-vibe' },
|
|
40
|
+
antigravity: Object.freeze({
|
|
41
|
+
kind: 'native-acp', args: ['acp'], executableName: 'agy',
|
|
42
|
+
source: 'https://antigravity.google/docs/cli/acp/',
|
|
43
|
+
note: 'Native ACP requires a recent agy CLI. Review vendor terms for your use; native protocol support does not authorize third-party wrappers.'
|
|
44
|
+
})
|
|
45
|
+
};
|
|
46
|
+
export const providers = Object.freeze(Object.fromEntries(Object.entries(recipes).map(([name, recipe]) =>
|
|
47
|
+
[name, Object.freeze({ ...recipe, args: Object.freeze([...recipe.args]) })])));
|
|
48
|
+
|
|
49
|
+
export function planProvider(provider, { executable, prefixArgs = [] } = {}) {
|
|
50
|
+
const recipe = Object.hasOwn(providers, provider) ? providers[provider] : undefined;
|
|
51
|
+
if (!recipe) throw new Error(`Unknown provider: ${provider}`);
|
|
52
|
+
if (recipe.kind === 'unavailable') throw new Error(recipe.note);
|
|
53
|
+
if (typeof executable !== 'string' || !Array.isArray(prefixArgs) ||
|
|
54
|
+
prefixArgs.some(value => typeof value !== 'string')) {
|
|
55
|
+
throw new TypeError('Provide an explicit installed executable and string arguments.');
|
|
56
|
+
}
|
|
57
|
+
return { command: executable, args: [...prefixArgs, ...recipe.args] };
|
|
58
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { rename } from 'node:fs/promises';
|
|
2
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
3
|
+
|
|
4
|
+
// Windows readers can briefly prevent replacing an otherwise writable file.
|
|
5
|
+
// Retry the same atomic rename; never unlink the destination to make it succeed.
|
|
6
|
+
export async function replaceFile(source, destination) {
|
|
7
|
+
for (let attempt = 0; ; attempt++) {
|
|
8
|
+
try { return await rename(source, destination); }
|
|
9
|
+
catch (cause) {
|
|
10
|
+
if (process.platform !== 'win32' || attempt === 5 || !['EACCES', 'EPERM', 'EBUSY'].includes(cause.code)) throw cause;
|
|
11
|
+
await delay(50 * (attempt + 1));
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
}
|
package/src/runtime.mjs
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { readdir, unlink } from 'node:fs/promises';
|
|
3
|
+
import { isAbsolute, join, relative, sep } from 'node:path';
|
|
4
|
+
import { ProfileStore, profileName, error } from './profiles.mjs';
|
|
5
|
+
import { readJson, withLock, writeJson } from './storage.mjs';
|
|
6
|
+
|
|
7
|
+
// Connection startup needs only saved records and leases, never installers,
|
|
8
|
+
// discovery, provider recipes or the legacy application client.
|
|
9
|
+
export class BridgeRegistry {
|
|
10
|
+
constructor(home) {
|
|
11
|
+
this.home = home; this.directory = join(home, 'bridges');
|
|
12
|
+
this.installations = join(home, 'installations'); this.leases = join(home, 'leases');
|
|
13
|
+
}
|
|
14
|
+
path(id) { return join(this.directory, profileName(id) + '.json'); }
|
|
15
|
+
async get(id) {
|
|
16
|
+
try {
|
|
17
|
+
const value = await readJson(this.path(id));
|
|
18
|
+
if (value.schemaVersion !== 1 || value.id !== id || !/^[a-f0-9]{64}$/.test(value.installKey || '')) {
|
|
19
|
+
throw error('INVALID_BRIDGE', 'Invalid managed bridge record.');
|
|
20
|
+
}
|
|
21
|
+
return value;
|
|
22
|
+
} catch (cause) {
|
|
23
|
+
if (cause.code === 'ENOENT') throw error('BRIDGE_NOT_FOUND', 'No managed bridge named "' + id + '".');
|
|
24
|
+
throw cause;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
async list() {
|
|
28
|
+
let names;
|
|
29
|
+
try { names = await readdir(this.directory); } catch (cause) { if (cause.code === 'ENOENT') return []; throw cause; }
|
|
30
|
+
return Promise.all(names.filter(name => name.endsWith('.json')).sort().map(async name => {
|
|
31
|
+
const id = name.slice(0, -5);
|
|
32
|
+
try { return await this.get(id); } catch (cause) { return { id, error: { code: cause.code, message: cause.message } }; }
|
|
33
|
+
}));
|
|
34
|
+
}
|
|
35
|
+
publish(record) { return writeJson(this.path(record.id), record); }
|
|
36
|
+
async lease(record) {
|
|
37
|
+
const file = join(this.leases, process.pid + '-' + randomUUID() + '.json');
|
|
38
|
+
// Publish atomically for concurrent readers. A lease only protects a live
|
|
39
|
+
// process, so it does not need a disk flush to survive a machine restart.
|
|
40
|
+
await writeJson(file, { pid: process.pid, installKey: record.installKey }, { durable: false });
|
|
41
|
+
return () => unlink(file).catch(cause => { if (cause.code !== 'ENOENT') throw cause; });
|
|
42
|
+
}
|
|
43
|
+
async remove(id) { await this.get(id); await unlink(this.path(id)); }
|
|
44
|
+
referencedInstallations(profile) {
|
|
45
|
+
return [...new Set([profile.command, ...profile.prefixArgs].filter(isAbsolute).map(path =>
|
|
46
|
+
relative(this.installations, path).split(sep)[0])
|
|
47
|
+
.map(key => process.platform === 'win32' ? key.toLowerCase() : key)
|
|
48
|
+
.filter(key => /^[a-f0-9]{64}$/.test(key)))];
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export class AgentRuntime {
|
|
53
|
+
constructor(options = {}) {
|
|
54
|
+
this.store = new ProfileStore(options);
|
|
55
|
+
this.bridges = new BridgeRegistry(this.store.home);
|
|
56
|
+
this.signal = options.signal;
|
|
57
|
+
}
|
|
58
|
+
get home() { return this.store.home; }
|
|
59
|
+
list() { return this.store.list(); }
|
|
60
|
+
get(name) { return this.store.get(name); }
|
|
61
|
+
withBridge(profile, record) {
|
|
62
|
+
return { ...profile, ...record.launch,
|
|
63
|
+
acpArgs: profile.bridge.useDefaultArgs ? record.launch.acpArgs : profile.acpArgs,
|
|
64
|
+
env: { ...record.launch.env, ...profile.env } };
|
|
65
|
+
}
|
|
66
|
+
async resolveProfile(profile) {
|
|
67
|
+
return profile.bridge ? this.withBridge(profile, await this.bridges.get(profile.bridge.id)) : profile;
|
|
68
|
+
}
|
|
69
|
+
async acquire(name) {
|
|
70
|
+
const snapshot = await this.get(name);
|
|
71
|
+
// Truly external commands have nothing for AgentLink to prune. They need
|
|
72
|
+
// neither a writable home nor a lock on another project's startup.
|
|
73
|
+
if (!snapshot.bridge && !this.bridges.referencedInstallations(snapshot).length) {
|
|
74
|
+
return { launch: snapshot, release: async () => {} };
|
|
75
|
+
}
|
|
76
|
+
return withLock(join(this.home, 'leases.lock'), async () => {
|
|
77
|
+
const profile = await this.get(name), releases = [];
|
|
78
|
+
try {
|
|
79
|
+
const record = profile.bridge ? await this.bridges.get(profile.bridge.id) : undefined;
|
|
80
|
+
const keys = record ? [record.installKey] : this.bridges.referencedInstallations(profile);
|
|
81
|
+
for (const installKey of keys) releases.push(await this.bridges.lease({ installKey }));
|
|
82
|
+
return { launch: record ? this.withBridge(profile, record) : profile,
|
|
83
|
+
release: async () => { await Promise.all(releases.map(release => release())); } };
|
|
84
|
+
} catch (cause) { await Promise.all(releases.map(release => release())); throw cause; }
|
|
85
|
+
}, 180000, this.signal);
|
|
86
|
+
}
|
|
87
|
+
}
|
package/src/storage.mjs
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { mkdir, open, readFile, stat, unlink } from 'node:fs/promises';
|
|
2
|
+
import { dirname, isAbsolute, relative, resolve, sep } from 'node:path';
|
|
3
|
+
import { randomUUID } from 'node:crypto';
|
|
4
|
+
import { error } from './profiles.mjs';
|
|
5
|
+
import { replaceFile } from './replace-file.mjs';
|
|
6
|
+
|
|
7
|
+
export function inside(root, path) {
|
|
8
|
+
const target = resolve(root, path);
|
|
9
|
+
const part = relative(resolve(root), target);
|
|
10
|
+
if (!part || part === '..' || part.startsWith('..' + sep) || isAbsolute(part)) {
|
|
11
|
+
throw error('INVALID_PATH', 'Path must stay inside its installation directory.');
|
|
12
|
+
}
|
|
13
|
+
return target;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export async function readJson(path, limit = 1024 * 1024) {
|
|
17
|
+
if ((await stat(path)).size > limit) throw error('FILE_LIMIT', 'Metadata file is too large.');
|
|
18
|
+
return JSON.parse(await readFile(path, 'utf8'));
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export async function writeJson(path, value, { durable = true } = {}) {
|
|
22
|
+
await mkdir(dirname(path), { recursive: true, mode: 0o700 });
|
|
23
|
+
const temporary = path + '.' + randomUUID() + '.tmp';
|
|
24
|
+
try {
|
|
25
|
+
const handle = await open(temporary, 'wx', 0o600);
|
|
26
|
+
try {
|
|
27
|
+
await handle.writeFile(JSON.stringify(value, null, 2) + '\n');
|
|
28
|
+
if (durable) await handle.sync();
|
|
29
|
+
}
|
|
30
|
+
finally { await handle.close(); }
|
|
31
|
+
await replaceFile(temporary, path);
|
|
32
|
+
} finally { await unlink(temporary).catch(cause => { if (cause.code !== 'ENOENT') throw cause; }); }
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export async function withLock(path, callback, timeoutMs = 180000, signal) {
|
|
36
|
+
await mkdir(dirname(path), { recursive: true, mode: 0o700 });
|
|
37
|
+
const deadline = Date.now() + timeoutMs;
|
|
38
|
+
let handle;
|
|
39
|
+
while (!handle) {
|
|
40
|
+
signal?.throwIfAborted();
|
|
41
|
+
try { handle = await open(path, 'wx', 0o600); }
|
|
42
|
+
catch (cause) {
|
|
43
|
+
if (cause.code !== 'EEXIST') throw cause;
|
|
44
|
+
try {
|
|
45
|
+
const owner = JSON.parse(await readFile(path, 'utf8'));
|
|
46
|
+
if (Number.isSafeInteger(owner.pid) && owner.pid > 0) {
|
|
47
|
+
try { process.kill(owner.pid, 0); }
|
|
48
|
+
catch (problem) {
|
|
49
|
+
if (problem.code === 'ESRCH') throw error('STALE_LOCK', 'Interrupted operation: process ' + owner.pid +
|
|
50
|
+
' no longer holds ' + path + '. Remove this stale lock file and retry.');
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
} catch (problem) { if (problem.code === 'STALE_LOCK') throw problem; }
|
|
54
|
+
if (Date.now() >= deadline) throw error('MANAGEMENT_BUSY', 'Another operation holds ' + path + '. If interrupted, remove this lock only after its recorded process has stopped.');
|
|
55
|
+
await new Promise(resolveWait => setTimeout(resolveWait, 50));
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
try {
|
|
59
|
+
await handle.writeFile(JSON.stringify({ pid: process.pid, createdAt: new Date().toISOString() }));
|
|
60
|
+
signal?.throwIfAborted();
|
|
61
|
+
return await callback();
|
|
62
|
+
} finally { await handle.close(); await unlink(path); }
|
|
63
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { strings } from './profiles.mjs';
|
|
2
|
+
|
|
3
|
+
export const authMarker = '--agentlink-terminal-auth';
|
|
4
|
+
|
|
5
|
+
// The wire layer has already validated JSON. Locate spans instead of
|
|
6
|
+
// reserializing the response: JSON.parse/stringify would round large numeric
|
|
7
|
+
// IDs and opaque extension values. Nesting is scanned iteratively.
|
|
8
|
+
const whitespace = (text, at) => { while (/\s/.test(text[at] || '') && at < text.length) at++; return at; };
|
|
9
|
+
function valueEnd(text, start) {
|
|
10
|
+
let depth = 0, quoted = false;
|
|
11
|
+
for (let at = start; at < text.length; at++) {
|
|
12
|
+
const char = text[at];
|
|
13
|
+
if (quoted) {
|
|
14
|
+
if (char === '\\') at++;
|
|
15
|
+
else if (char === '"') { quoted = false; if (!depth) return at + 1; }
|
|
16
|
+
} else if (char === '"') quoted = true;
|
|
17
|
+
else if (char === '{' || char === '[') depth++;
|
|
18
|
+
else if (char === '}' || char === ']') { if (!depth) return at; if (!--depth) return at + 1; }
|
|
19
|
+
else if (!depth && (char === ',' || /\s/.test(char))) return at;
|
|
20
|
+
}
|
|
21
|
+
return text.length;
|
|
22
|
+
}
|
|
23
|
+
function member(text, start, name) {
|
|
24
|
+
if (text[start] !== '{') return;
|
|
25
|
+
let found, at = whitespace(text, start + 1);
|
|
26
|
+
while (text[at] !== '}') {
|
|
27
|
+
const end = valueEnd(text, at), key = JSON.parse(text.slice(at, end));
|
|
28
|
+
const value = whitespace(text, whitespace(text, end) + 1);
|
|
29
|
+
const finish = valueEnd(text, value);
|
|
30
|
+
if (key === name) found = [value, finish]; // JSON's last duplicate key wins.
|
|
31
|
+
at = whitespace(text, finish);
|
|
32
|
+
if (text[at] === ',') at = whitespace(text, at + 1);
|
|
33
|
+
}
|
|
34
|
+
return found;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function terminalAuthReply(message, source) {
|
|
38
|
+
const methods = message.result?.authMethods;
|
|
39
|
+
const eligible = method => method?.type === 'terminal' && strings(method.args ?? []);
|
|
40
|
+
if (!Array.isArray(methods) || !methods.some(eligible)) return;
|
|
41
|
+
const result = member(source, whitespace(source, 0), 'result');
|
|
42
|
+
const auth = member(source, result[0], 'authMethods');
|
|
43
|
+
const edits = [];
|
|
44
|
+
let at = whitespace(source, auth[0] + 1);
|
|
45
|
+
for (const method of methods) {
|
|
46
|
+
const end = valueEnd(source, at);
|
|
47
|
+
if (eligible(method)) {
|
|
48
|
+
const args = member(source, at, 'args');
|
|
49
|
+
const replacement = JSON.stringify([authMarker, ...(method.args ?? [])]);
|
|
50
|
+
edits.push(args ? [...args, replacement] : [at + 1, at + 1, '"args":' + replacement + ',']);
|
|
51
|
+
}
|
|
52
|
+
at = whitespace(source, end);
|
|
53
|
+
if (source[at] === ',') at = whitespace(source, at + 1);
|
|
54
|
+
}
|
|
55
|
+
const parts = [];
|
|
56
|
+
let cursor = 0;
|
|
57
|
+
for (const [start, end, replacement] of edits) {
|
|
58
|
+
parts.push(source.slice(cursor, start), replacement); cursor = end;
|
|
59
|
+
}
|
|
60
|
+
parts.push(source.slice(cursor));
|
|
61
|
+
return Buffer.from(parts.join(''));
|
|
62
|
+
}
|
package/src/version.mjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const version = '0.3.0-beta.2';
|
package/src/wire.mjs
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { Transform } from 'node:stream';
|
|
2
|
+
import { error } from './profiles.mjs';
|
|
3
|
+
|
|
4
|
+
// Validate framing, not the evolving ACP method schema. Preserve the original
|
|
5
|
+
// bytes, IDs, extensions and field order. Stream backpressure bounds queued data.
|
|
6
|
+
export class AcpFrames extends Transform {
|
|
7
|
+
constructor({ maxMessageBytes = 16 * 1024 * 1024, onMessage, mapMessage } = {}) {
|
|
8
|
+
super();
|
|
9
|
+
if (!Number.isSafeInteger(maxMessageBytes) || maxMessageBytes < 1) throw new TypeError('Invalid ACP frame limit.');
|
|
10
|
+
this.limit = maxMessageBytes;
|
|
11
|
+
this.parts = [];
|
|
12
|
+
this.bytes = 0;
|
|
13
|
+
this.onMessage = onMessage;
|
|
14
|
+
this.mapMessage = mapMessage;
|
|
15
|
+
}
|
|
16
|
+
_transform(chunk, encoding, done) {
|
|
17
|
+
try {
|
|
18
|
+
let start = 0;
|
|
19
|
+
for (let index = 0; index < chunk.length; index++) {
|
|
20
|
+
if (chunk[index] !== 10) continue;
|
|
21
|
+
this.append(chunk.subarray(start, index));
|
|
22
|
+
const line = Buffer.concat(this.parts, this.bytes);
|
|
23
|
+
this.parts = []; this.bytes = 0;
|
|
24
|
+
const source = new TextDecoder('utf-8', { fatal: true }).decode(line);
|
|
25
|
+
const message = JSON.parse(source);
|
|
26
|
+
if (!message || typeof message !== 'object' || Array.isArray(message) || message.jsonrpc !== '2.0' ||
|
|
27
|
+
!(typeof message.method === 'string' || Object.hasOwn(message, 'result') || Object.hasOwn(message, 'error'))) {
|
|
28
|
+
throw error('PROTOCOL_ERROR', 'Expected an ACP JSON-RPC message.');
|
|
29
|
+
}
|
|
30
|
+
this.onMessage?.(message);
|
|
31
|
+
const mapped = this.mapMessage?.(message, source);
|
|
32
|
+
this.push(mapped === undefined ? line : Buffer.isBuffer(mapped) ? mapped : Buffer.from(JSON.stringify(mapped)));
|
|
33
|
+
this.push(Buffer.from('\n'));
|
|
34
|
+
start = index + 1;
|
|
35
|
+
}
|
|
36
|
+
this.append(chunk.subarray(start));
|
|
37
|
+
done();
|
|
38
|
+
} catch (cause) {
|
|
39
|
+
done(cause.code ? cause : error('PROTOCOL_ERROR', 'Invalid JSON or UTF-8 in the ACP stream.'));
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
append(part) {
|
|
43
|
+
this.bytes += part.length;
|
|
44
|
+
if (this.bytes > this.limit) throw error('MESSAGE_LIMIT', 'ACP message exceeds the configured frame limit.');
|
|
45
|
+
if (part.length) this.parts.push(part);
|
|
46
|
+
}
|
|
47
|
+
_flush(done) {
|
|
48
|
+
done(this.bytes ? error('PROTOCOL_ERROR', 'ACP stream ended inside a message.') : undefined);
|
|
49
|
+
}
|
|
50
|
+
}
|