@prplkane/agentlink 0.0.0-stage → 0.3.0-beta.1
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 +148 -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 +106 -0
- package/src/providers.mjs +58 -0
- package/src/runtime.mjs +87 -0
- package/src/storage.mjs +62 -0
- package/src/terminal-auth.mjs +62 -0
- package/src/version.mjs +1 -0
- package/src/wire.mjs +50 -0
package/src/index.mjs
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
import { join } from 'node:path';
|
|
2
|
+
import { AcpClient } from './client.mjs';
|
|
3
|
+
import { discoverAgent, validateDiscoveryOptions, inProbeDirectory, verifyAgent } from './discovery.mjs';
|
|
4
|
+
import { profileName, error } from './profiles.mjs';
|
|
5
|
+
import { AgentRuntime } from './runtime.mjs';
|
|
6
|
+
import { BridgeStore, environment, manifestSpec } from './bridges.mjs';
|
|
7
|
+
import { withLock } from './storage.mjs';
|
|
8
|
+
import { providers } from './providers.mjs';
|
|
9
|
+
|
|
10
|
+
export { AcpClient } from './client.mjs';
|
|
11
|
+
export { providers, planProvider } from './providers.mjs';
|
|
12
|
+
export { ProfileStore } from './profiles.mjs';
|
|
13
|
+
export { discoverAgent, inspectHelp } from './discovery.mjs';
|
|
14
|
+
export { runGateway } from './gateway.mjs';
|
|
15
|
+
|
|
16
|
+
export class AgentLink extends AgentRuntime {
|
|
17
|
+
constructor(options = {}) {
|
|
18
|
+
super(options);
|
|
19
|
+
this.bridges = new BridgeStore(this.store.home);
|
|
20
|
+
}
|
|
21
|
+
mutate(callback) { return withLock(join(this.home, 'management.lock'), callback, 180000, this.signal); }
|
|
22
|
+
remove(name) { return this.mutate(() => this.store.remove(name)); }
|
|
23
|
+
inspect(options) { return discoverAgent(options); } // Never installs or saves.
|
|
24
|
+
|
|
25
|
+
async installBridge(id, spec, options = {}) {
|
|
26
|
+
return this.mutate(() => this.installBridgeUnlocked(id, spec, options));
|
|
27
|
+
}
|
|
28
|
+
async installBridgeUnlocked(id, spec, options) {
|
|
29
|
+
return this.bridges.install(id, spec, { signal: this.signal, ...options,
|
|
30
|
+
publish: options.publish || (record => withLock(join(this.home, 'leases.lock'),
|
|
31
|
+
() => this.bridges.publish(record), 180000, options.signal || this.signal)),
|
|
32
|
+
validate: async launch => {
|
|
33
|
+
for (const profile of await this.list()) {
|
|
34
|
+
if (profile.error) throw error('INVALID_PROFILE', 'Repair unreadable profiles before changing shared bridges.');
|
|
35
|
+
if (profile.bridge?.id !== id) continue;
|
|
36
|
+
const candidate = this.withBridge(profile, { launch });
|
|
37
|
+
await inProbeDirectory(cwd => verifyAgent(candidate, { ...options, cwd }));
|
|
38
|
+
}
|
|
39
|
+
await options.validateNew?.(launch);
|
|
40
|
+
} });
|
|
41
|
+
}
|
|
42
|
+
async updateBridge(id, options = {}) {
|
|
43
|
+
return this.mutate(async () => {
|
|
44
|
+
const record = await this.bridges.get(id);
|
|
45
|
+
let spec = options.spec || record.spec;
|
|
46
|
+
if (!options.spec && (options.manifest || spec.manifestSource)) {
|
|
47
|
+
spec = await manifestSpec(options.manifest || spec.manifestSource, { ...options, distribution: spec.kind });
|
|
48
|
+
} else if (!options.spec && spec.kind === 'npm') {
|
|
49
|
+
spec = { ...spec, version: options.version || 'latest' };
|
|
50
|
+
if (options.version && options.version !== record.spec.version && !options.source) delete spec.source;
|
|
51
|
+
}
|
|
52
|
+
if (options.version) spec.version = options.version;
|
|
53
|
+
if (options.source) spec.source = options.source;
|
|
54
|
+
if (options.bin) spec.bin = options.bin;
|
|
55
|
+
if (options.acpArgs) spec.args = options.acpArgs;
|
|
56
|
+
if (options.launchEnv) spec.env = options.launchEnv;
|
|
57
|
+
return this.installBridgeUnlocked(id, spec, options);
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
async removeBridge(id) {
|
|
61
|
+
return this.mutate(async () => {
|
|
62
|
+
const profiles = await this.list();
|
|
63
|
+
if (profiles.some(profile => profile.error)) throw error('INVALID_PROFILE', 'Repair unreadable profiles before removing a bridge.');
|
|
64
|
+
const users = profiles.filter(profile => profile.bridge?.id === id).map(profile => profile.name);
|
|
65
|
+
if (users.length) throw error('BRIDGE_IN_USE', 'Bridge is referenced by: ' + users.join(', ') + '. Remove or change those profiles first.');
|
|
66
|
+
await this.bridges.remove(id);
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
pruneBridges(options = {}) { return this.mutate(() => withLock(join(this.home, 'leases.lock'), async () => {
|
|
70
|
+
const profiles = await this.list();
|
|
71
|
+
if (profiles.some(profile => profile.error)) throw error('INVALID_PROFILE', 'Repair unreadable profiles before pruning.');
|
|
72
|
+
return this.bridges.prune({ ...options, profiles });
|
|
73
|
+
}, 180000, this.signal)); }
|
|
74
|
+
|
|
75
|
+
async discoverForSave(name, options, persist) {
|
|
76
|
+
validateDiscoveryOptions(options);
|
|
77
|
+
if (!environment(options.launchEnv)) throw new TypeError('Invalid profile environment.');
|
|
78
|
+
if (options.bridge !== undefined) profileName(options.bridge);
|
|
79
|
+
let bridgeId = options.bridge;
|
|
80
|
+
let spec = options.spec;
|
|
81
|
+
if (options.manifest) {
|
|
82
|
+
spec = await manifestSpec(options.manifest, options);
|
|
83
|
+
if (options.bin) spec.bin = options.bin;
|
|
84
|
+
}
|
|
85
|
+
const recipe = providers[options.provider];
|
|
86
|
+
if (!options.command && !bridgeId && !options.external && recipe?.package) {
|
|
87
|
+
bridgeId = options.provider;
|
|
88
|
+
if (!spec) {
|
|
89
|
+
try {
|
|
90
|
+
const current = await this.bridges.get(bridgeId);
|
|
91
|
+
if (options.version && options.version !== current.spec.version) {
|
|
92
|
+
spec = { ...current.spec, version: options.version };
|
|
93
|
+
delete spec.source;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
catch (cause) {
|
|
97
|
+
if (cause.code !== 'BRIDGE_NOT_FOUND') throw cause;
|
|
98
|
+
spec = { kind: 'npm', package: recipe.package, version: options.version || 'latest', bin: recipe.executableName, args: recipe.args };
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
if (spec) {
|
|
103
|
+
bridgeId ||= name;
|
|
104
|
+
let verification, saved;
|
|
105
|
+
await this.installBridgeUnlocked(bridgeId, spec, { ...options, validateNew: async launch => {
|
|
106
|
+
if (options.acpArgs === undefined && !options.launchEnv) return;
|
|
107
|
+
const candidate = { ...launch, acpArgs: options.acpArgs ?? launch.acpArgs, env: { ...launch.env, ...options.launchEnv } };
|
|
108
|
+
verification = await inProbeDirectory(cwd => verifyAgent(candidate, { ...options, cwd }));
|
|
109
|
+
}, publish: async record => {
|
|
110
|
+
verification ??= record.verification;
|
|
111
|
+
saved = await persist({ ...record.launch, acpArgs: options.acpArgs ?? record.launch.acpArgs,
|
|
112
|
+
provider: options.provider ?? null, protocolVersion: verification.protocolVersion, verification,
|
|
113
|
+
bridge: { id: bridgeId, useDefaultArgs: options.acpArgs === undefined }, env: options.launchEnv || {},
|
|
114
|
+
discovery: { method: 'metadata', ...(options.helpArgs ? { helpArgs: options.helpArgs } : {}) } }, record);
|
|
115
|
+
} });
|
|
116
|
+
return saved;
|
|
117
|
+
}
|
|
118
|
+
if (bridgeId) {
|
|
119
|
+
const record = await this.bridges.get(bridgeId);
|
|
120
|
+
if (!spec && options.version && options.version !== record.spec.version) {
|
|
121
|
+
throw error('VERSION_MISMATCH', 'This bridge uses ' + record.spec.version + '. Change it centrally with agentlink bridge update ' + bridgeId + ' --version ' + options.version + '.');
|
|
122
|
+
}
|
|
123
|
+
const launch = { ...record.launch, acpArgs: options.acpArgs ?? record.launch.acpArgs,
|
|
124
|
+
env: { ...record.launch.env, ...options.launchEnv } };
|
|
125
|
+
const discovered = await discoverAgent({ ...options, ...launch, provider: undefined,
|
|
126
|
+
env: { ...(options.env || process.env), ...launch.env } });
|
|
127
|
+
return persist({ ...discovered, provider: options.provider ?? null,
|
|
128
|
+
bridge: { id: bridgeId, useDefaultArgs: options.acpArgs === undefined },
|
|
129
|
+
env: options.launchEnv || {}, discovery: { ...discovered.discovery, method: 'metadata' } });
|
|
130
|
+
}
|
|
131
|
+
const discovered = await discoverAgent({ ...options, env: { ...(options.env || process.env), ...options.launchEnv } });
|
|
132
|
+
return persist(options.launchEnv ? { ...discovered, env: options.launchEnv } : discovered);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
async saveProfile(profile, existing, record) {
|
|
136
|
+
const save = () => this.store.save(profile, { replace: Boolean(existing) });
|
|
137
|
+
if (!record) return save();
|
|
138
|
+
// Readers of managed profiles share this brief lock. Preparation and ACP
|
|
139
|
+
// verification happen before it, so downloads never block new connections.
|
|
140
|
+
return withLock(join(this.home, 'leases.lock'), async () => {
|
|
141
|
+
const saved = await save();
|
|
142
|
+
try { await this.bridges.publish(record); }
|
|
143
|
+
catch (cause) {
|
|
144
|
+
try {
|
|
145
|
+
if (existing) await this.store.save(existing, { replace: true });
|
|
146
|
+
else await this.store.remove(profile.name);
|
|
147
|
+
} catch (rollback) {
|
|
148
|
+
throw error('ROLLBACK_FAILED', 'Bridge publication failed and profile recovery failed: ' +
|
|
149
|
+
cause.message + '; ' + rollback.message + '. Inspect profile ' + profile.name + ' before retrying.');
|
|
150
|
+
}
|
|
151
|
+
throw cause;
|
|
152
|
+
}
|
|
153
|
+
return saved;
|
|
154
|
+
}, 180000, this.signal);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
async add(name, options) {
|
|
158
|
+
return this.mutate(async () => {
|
|
159
|
+
profileName(name);
|
|
160
|
+
try { await this.get(name); throw error('PROFILE_EXISTS', 'Profile "' + name + '" already exists. Use update or refresh.'); }
|
|
161
|
+
catch (cause) { if (cause.code !== 'PROFILE_NOT_FOUND') throw cause; }
|
|
162
|
+
return this.discoverForSave(name, options, (discovered, record) => {
|
|
163
|
+
const now = new Date().toISOString();
|
|
164
|
+
return this.saveProfile({ schemaVersion: 1, name, ...discovered, createdAt: now, updatedAt: now }, undefined, record);
|
|
165
|
+
});
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
async update(name, options = {}) {
|
|
170
|
+
return this.mutate(async () => {
|
|
171
|
+
const existing = await this.get(name);
|
|
172
|
+
const changedLaunch = ['command', 'prefixArgs', 'provider', 'bridge', 'spec', 'manifest', 'external'].some(key => Object.hasOwn(options, key));
|
|
173
|
+
let defaults;
|
|
174
|
+
if (!changedLaunch && existing.bridge) {
|
|
175
|
+
defaults = { bridge: existing.bridge.id, provider: existing.provider ?? undefined,
|
|
176
|
+
acpArgs: existing.bridge.useDefaultArgs ? undefined : existing.acpArgs };
|
|
177
|
+
} else if (changedLaunch) {
|
|
178
|
+
defaults = { command: options.provider === undefined && !options.bridge && !options.spec && !options.manifest ? existing.command : undefined,
|
|
179
|
+
prefixArgs: options.command === undefined && options.provider === undefined && !options.bridge && !options.spec && !options.manifest ? existing.prefixArgs : [] };
|
|
180
|
+
} else defaults = { command: existing.command, prefixArgs: existing.prefixArgs, acpArgs: existing.acpArgs, provider: existing.provider ?? undefined };
|
|
181
|
+
return this.discoverForSave(name, {
|
|
182
|
+
helpArgs: existing.discovery.helpArgs, launchEnv: existing.env, ...defaults, ...options
|
|
183
|
+
}, (discovered, record) => {
|
|
184
|
+
const { bridge, env, ...previous } = existing;
|
|
185
|
+
return this.saveProfile({ ...previous, ...discovered, updatedAt: new Date().toISOString() }, existing, record);
|
|
186
|
+
});
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
async refresh(name, options = {}) {
|
|
191
|
+
return this.mutate(async () => {
|
|
192
|
+
const existing = await this.get(name), current = await this.resolveProfile(existing);
|
|
193
|
+
// Exact user argv and managed bridge recipes remain authoritative. Only
|
|
194
|
+
// help/known external profiles need command discovery again on refresh.
|
|
195
|
+
const keepArgs = existing.bridge || existing.discovery.method === 'manual';
|
|
196
|
+
const discovered = await discoverAgent({ command: current.command, prefixArgs: current.prefixArgs,
|
|
197
|
+
provider: existing.provider ?? undefined, helpArgs: existing.discovery.helpArgs,
|
|
198
|
+
acpArgs: keepArgs ? current.acpArgs : undefined, ...options,
|
|
199
|
+
env: { ...(options.env || process.env), ...current.env } });
|
|
200
|
+
const bridge = existing.bridge ? { ...existing.bridge,
|
|
201
|
+
useDefaultArgs: JSON.stringify(discovered.acpArgs) === JSON.stringify((await this.bridges.get(existing.bridge.id)).launch.acpArgs) } : undefined;
|
|
202
|
+
return this.store.save({ ...existing, ...discovered, ...(bridge ? { bridge } : {}), updatedAt: new Date().toISOString() }, { replace: true });
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
async check(name, options = {}) {
|
|
207
|
+
const { launch, release } = await this.acquire(name);
|
|
208
|
+
try { return await inProbeDirectory(cwd => verifyAgent(launch, { ...options, cwd })); }
|
|
209
|
+
finally { await release(); }
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// Compatibility API for the original text-only ACP v1 prototype. New
|
|
213
|
+
// applications use the standard ACP gateway instead of depending on this SDK.
|
|
214
|
+
async connect(name, { cwd = process.cwd(), env = process.env, timeoutMs = 10000,
|
|
215
|
+
authMethodId, onUpdate, onPermission, ...limits } = {}) {
|
|
216
|
+
const { launch, release } = await this.acquire(name);
|
|
217
|
+
let client;
|
|
218
|
+
try {
|
|
219
|
+
client = new AcpClient({ ...limits, command: launch.command, args: [...launch.prefixArgs, ...launch.acpArgs],
|
|
220
|
+
cwd, env: { ...env, ...launch.env }, onUpdate, onPermission });
|
|
221
|
+
const close = client.close.bind(client);
|
|
222
|
+
client.close = async () => { try { await close(); } finally { await release(); } };
|
|
223
|
+
await client.initialize({ timeoutMs });
|
|
224
|
+
if (authMethodId !== undefined) await client.authenticate(authMethodId, { timeoutMs });
|
|
225
|
+
await client.newSession({ timeoutMs });
|
|
226
|
+
return client;
|
|
227
|
+
} catch (cause) { if (client) await client.close(); else await release(); throw cause; }
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
export const createAgentLink = options => new AgentLink(options);
|
|
232
|
+
export const agentlink = new AgentLink();
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
import { parseArgs } from 'node:util';
|
|
2
|
+
import { fileURLToPath } from 'node:url';
|
|
3
|
+
import { AgentLink, providers } from './index.mjs';
|
|
4
|
+
import { manifestSpec } from './bridges.mjs';
|
|
5
|
+
import { doctor } from './doctor.mjs';
|
|
6
|
+
|
|
7
|
+
const usage = 'AgentLink — shared ACP connections and centrally managed bridges\n\n' +
|
|
8
|
+
' agentlink [--home PATH] acp <profile> Standard ACP over stdin/stdout\n' +
|
|
9
|
+
' agentlink add <profile> --provider codex|claude\n' +
|
|
10
|
+
' agentlink add <profile> --command <installed-cli>\n' +
|
|
11
|
+
' agentlink add <profile> --bridge <managed-bridge>\n' +
|
|
12
|
+
' agentlink add <profile> --manifest <ACP-registry-entry.json-or-URL>\n' +
|
|
13
|
+
' agentlink inspect --command <installed-cli>\n' +
|
|
14
|
+
' agentlink update <profile> [launch options]\n' +
|
|
15
|
+
' agentlink refresh <profile> | check <profile>\n' +
|
|
16
|
+
' agentlink doctor Read-only local health checks\n' +
|
|
17
|
+
' agentlink list | show <profile> | config <profile> | remove <profile> | providers | where\n\n' +
|
|
18
|
+
' agentlink bridge install <id> --package <npm-package> [--version <version-or-tag>]\n' +
|
|
19
|
+
' agentlink bridge install <id> --manifest <file-or-URL>\n' +
|
|
20
|
+
' agentlink bridge update <id> [--version <version-or-tag>]\n' +
|
|
21
|
+
' agentlink bridge list | show <id> | remove <id> | prune [--cache]\n\n' +
|
|
22
|
+
'Launch options:\n' +
|
|
23
|
+
' --command PATH Installed executable (external management)\n' +
|
|
24
|
+
' --provider NAME Known recipe; Codex/Claude bridges are managed by default\n' +
|
|
25
|
+
' --external Use the installed provider bridge instead of managing it\n' +
|
|
26
|
+
' --bridge ID Reference a centrally managed bridge\n' +
|
|
27
|
+
' --prefix-args JSON String array before ACP arguments (e.g. Node entry script)\n' +
|
|
28
|
+
' --acp-args JSON Exact ACP arguments; [] for a standalone bridge\n' +
|
|
29
|
+
' --help-args JSON Custom help invocation, e.g. ["help"] or ["/?"]\n' +
|
|
30
|
+
' --env JSON Explicit non-secret launch settings, saved locally\n' +
|
|
31
|
+
' --skip-check Save a direct launch as pending; managed installs are checked\n\n' +
|
|
32
|
+
'Installation options:\n' +
|
|
33
|
+
' --package NAME Install a package; --kind npm (default) or python\n' +
|
|
34
|
+
' --version VERSION Pin a version; npm defaults to resolving latest once\n' +
|
|
35
|
+
' --bin NAME Package executable (needed when ambiguous)\n' +
|
|
36
|
+
' --source PATH|URL Explicit package artifact, including local offline fixtures\n' +
|
|
37
|
+
' --manifest PATH|URL Individual standard ACP registry entry\n' +
|
|
38
|
+
' --distribution KIND Choose binary, npm, or python from a manifest\n' +
|
|
39
|
+
' --offline Use offline package-manager mode and local artifacts/cache\n' +
|
|
40
|
+
' --install-timeout MS Installer deadline (default 180000)\n\n' +
|
|
41
|
+
'Management options: --home PATH, --json, --timeout MS (probe default 3000), --help/-h\n' +
|
|
42
|
+
'For ACP, put --home BEFORE acp. Arguments after the profile are forwarded unchanged\n' +
|
|
43
|
+
'for standard ACP terminal authentication. Logs and failures go to stderr.\n' +
|
|
44
|
+
'No application SDK, background daemon, prompt storage, or live task is required.\n';
|
|
45
|
+
|
|
46
|
+
function array(value, name) {
|
|
47
|
+
const parsed = JSON.parse(value);
|
|
48
|
+
if (!Array.isArray(parsed) || parsed.some(item => typeof item !== 'string')) throw new TypeError(name + ' must be an array of strings.');
|
|
49
|
+
return parsed;
|
|
50
|
+
}
|
|
51
|
+
function positive(value, name) {
|
|
52
|
+
const parsed = Number(value);
|
|
53
|
+
if (!Number.isSafeInteger(parsed) || parsed < 1) throw new TypeError(name + ' must be a positive integer.');
|
|
54
|
+
return parsed;
|
|
55
|
+
}
|
|
56
|
+
export const printHelp = () => process.stdout.write(usage);
|
|
57
|
+
|
|
58
|
+
export async function runManagement(argv, { signal, cliURL } = {}) {
|
|
59
|
+
let json = false;
|
|
60
|
+
try {
|
|
61
|
+
const { values: v, positionals } = parseArgs({ args: argv, allowPositionals: true, options: {
|
|
62
|
+
command: { type: 'string' }, provider: { type: 'string' }, bridge: { type: 'string' },
|
|
63
|
+
'prefix-args': { type: 'string' }, 'acp-args': { type: 'string' }, 'help-args': { type: 'string' },
|
|
64
|
+
env: { type: 'string' }, external: { type: 'boolean' }, 'skip-check': { type: 'boolean' },
|
|
65
|
+
package: { type: 'string' }, version: { type: 'string' }, bin: { type: 'string' }, source: { type: 'string' },
|
|
66
|
+
kind: { type: 'string' }, manifest: { type: 'string' }, distribution: { type: 'string' },
|
|
67
|
+
offline: { type: 'boolean' }, cache: { type: 'boolean' }, 'install-timeout': { type: 'string' },
|
|
68
|
+
timeout: { type: 'string' }, home: { type: 'string' }, json: { type: 'boolean' },
|
|
69
|
+
help: { type: 'boolean', short: 'h' }
|
|
70
|
+
} });
|
|
71
|
+
json = Boolean(v.json);
|
|
72
|
+
const [action = 'help', first, second, ...rest] = positionals;
|
|
73
|
+
if (v.help || action === 'help') process.stdout.write(usage);
|
|
74
|
+
else {
|
|
75
|
+
const manager = new AgentLink({ ...(v.home ? { home: v.home } : {}), signal: signal });
|
|
76
|
+
const launchFlags = ['command', 'provider', 'bridge', 'prefix-args', 'acp-args', 'help-args', 'env', 'external', 'skip-check'];
|
|
77
|
+
const installFlags = ['package', 'version', 'bin', 'source', 'kind', 'manifest', 'distribution', 'offline', 'install-timeout'];
|
|
78
|
+
const allowed = {
|
|
79
|
+
add: [...launchFlags, ...installFlags], update: [...launchFlags, ...installFlags],
|
|
80
|
+
inspect: ['command', 'provider', 'prefix-args', 'acp-args', 'help-args', 'skip-check'],
|
|
81
|
+
refresh: [], check: [], list: [], show: [], config: [], remove: [], providers: [], where: [], doctor: [],
|
|
82
|
+
bridge: [...installFlags, 'acp-args', 'env', 'cache']
|
|
83
|
+
};
|
|
84
|
+
if (!Object.hasOwn(allowed, action)) throw new TypeError('Unknown command. Run agentlink --help.');
|
|
85
|
+
for (const key of Object.keys(v)) {
|
|
86
|
+
if (!['home', 'json', 'help', 'timeout', ...allowed[action]].includes(key)) throw new TypeError('--' + key + ' is not supported by ' + action + '.');
|
|
87
|
+
}
|
|
88
|
+
const options = { signal: signal };
|
|
89
|
+
for (const key of ['command', 'provider', 'bridge', 'external', 'manifest', 'distribution', 'version', 'source', 'bin', 'offline']) {
|
|
90
|
+
if (v[key] !== undefined) options[key] = v[key];
|
|
91
|
+
}
|
|
92
|
+
for (const [flag, key] of [['prefix-args', 'prefixArgs'], ['acp-args', 'acpArgs'], ['help-args', 'helpArgs']]) {
|
|
93
|
+
if (v[flag] !== undefined) options[key] = array(v[flag], '--' + flag);
|
|
94
|
+
}
|
|
95
|
+
if (v.env !== undefined) options.launchEnv = JSON.parse(v.env);
|
|
96
|
+
if (v['skip-check']) options.verify = false;
|
|
97
|
+
if (v.timeout) options.timeoutMs = positive(v.timeout, '--timeout');
|
|
98
|
+
if (v['install-timeout']) options.installTimeoutMs = positive(v['install-timeout'], '--install-timeout');
|
|
99
|
+
if (v.package) options.spec = { kind: v.kind || 'npm', package: v.package, version: v.version,
|
|
100
|
+
bin: v.bin, source: v.source, args: options.acpArgs || [], env: options.launchEnv || {} };
|
|
101
|
+
if (v.package && v.manifest) throw new TypeError('Choose --package or --manifest.');
|
|
102
|
+
if (v.command && (v.package || v.manifest || v.bridge)) throw new TypeError('Choose an installed command or a managed bridge.');
|
|
103
|
+
if (v.external && (v.package || v.manifest || v.bridge)) throw new TypeError('--external cannot select a managed distribution.');
|
|
104
|
+
let result;
|
|
105
|
+
if (action === 'bridge') {
|
|
106
|
+
const operation = first, id = second;
|
|
107
|
+
const named = ['install', 'update', 'show', 'remove'].includes(operation);
|
|
108
|
+
if (!['install', 'update', 'show', 'remove', 'list', 'prune'].includes(operation) || rest.length || (named ? !id : id !== undefined)) {
|
|
109
|
+
throw new TypeError('Invalid bridge command. Run agentlink --help.');
|
|
110
|
+
}
|
|
111
|
+
const flags = ['install', 'update'].includes(operation) ? [...installFlags, 'acp-args', 'env'] : operation === 'prune' ? ['cache'] : [];
|
|
112
|
+
for (const key of Object.keys(v)) {
|
|
113
|
+
if (!['home', 'json', 'help', 'timeout', ...flags].includes(key)) throw new TypeError('--' + key + ' is not supported by bridge ' + operation + '.');
|
|
114
|
+
}
|
|
115
|
+
if (operation === 'install') {
|
|
116
|
+
const spec = v.manifest ? await manifestSpec(v.manifest, options) : options.spec;
|
|
117
|
+
if (!spec) throw new TypeError('Bridge install requires --package or --manifest.');
|
|
118
|
+
result = await manager.installBridge(id, { ...spec, args: options.acpArgs ?? spec.args,
|
|
119
|
+
env: options.launchEnv ?? spec.env, bin: options.bin ?? spec.bin }, options);
|
|
120
|
+
} else if (operation === 'update') result = await manager.updateBridge(id, options);
|
|
121
|
+
else if (operation === 'show') result = await manager.bridges.get(id);
|
|
122
|
+
else if (operation === 'list') result = await manager.bridges.list();
|
|
123
|
+
else if (operation === 'prune') result = await manager.pruneBridges({ cache: Boolean(v.cache) });
|
|
124
|
+
else { await manager.removeBridge(id); result = { removed: id, note: 'Unused files can be removed with bridge prune.' }; }
|
|
125
|
+
} else {
|
|
126
|
+
const named = ['add', 'update', 'refresh', 'check', 'show', 'config', 'remove'].includes(action);
|
|
127
|
+
if (second !== undefined || rest.length || (named ? !first : first !== undefined)) throw new TypeError('Invalid arguments for ' + action + '.');
|
|
128
|
+
switch (action) {
|
|
129
|
+
case 'add': result = await manager.add(first, options); break;
|
|
130
|
+
case 'update': result = await manager.update(first, options); break;
|
|
131
|
+
case 'inspect': result = await manager.inspect(options); break;
|
|
132
|
+
case 'refresh': result = await manager.refresh(first, options); break;
|
|
133
|
+
case 'check': result = { name: first, verification: await manager.check(first, options) }; break;
|
|
134
|
+
case 'show': {
|
|
135
|
+
const profile = await manager.get(first);
|
|
136
|
+
result = { ...profile, resolvedLaunch: await manager.resolveProfile(profile) }; break;
|
|
137
|
+
}
|
|
138
|
+
case 'list': result = await manager.list(); break;
|
|
139
|
+
case 'config':
|
|
140
|
+
await manager.get(first);
|
|
141
|
+
result = { command: process.execPath, args: [fileURLToPath(cliURL), '--home', manager.home, 'acp', first] };
|
|
142
|
+
break;
|
|
143
|
+
case 'remove': await manager.remove(first); result = { removed: first }; break;
|
|
144
|
+
case 'providers': result = providers; break;
|
|
145
|
+
case 'where': result = { home: manager.home, profiles: manager.store.directory, bridges: manager.bridges.directory }; break;
|
|
146
|
+
case 'doctor': result = await doctor(manager); if (!result.ok) process.exitCode = 1; break;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
if (json || action === 'bridge' || ['show', 'config', 'inspect', 'providers'].includes(action)) process.stdout.write(JSON.stringify(result, null, 2) + '\n');
|
|
150
|
+
else if (action === 'list') process.stdout.write(result.length ? result.map(profile =>
|
|
151
|
+
profile.name + '\t' + (profile.error ? profile.error.message : profile.verification.status + '\t' +
|
|
152
|
+
(profile.bridge ? 'managed:' + profile.bridge.id : profile.command))).join('\n') + '\n' : 'No saved profiles.\n');
|
|
153
|
+
else if (action === 'where') process.stdout.write(result.home + '\n');
|
|
154
|
+
else if (action === 'doctor') process.stdout.write((result.ok ? 'Local files look healthy.' : 'Local issues found.') + '\n' +
|
|
155
|
+
result.checks.map(check => check.status + '\t' + check.scope + ' ' + check.name +
|
|
156
|
+
(check.message ? ': ' + check.message : '')).join('\n') + '\n');
|
|
157
|
+
else if (action === 'remove') process.stdout.write('Removed ' + first + '.\n');
|
|
158
|
+
else process.stdout.write((result.name || first) + ': ' + result.verification.status +
|
|
159
|
+
(action === 'check' ? '\n' : '\nSaved ' + manager.store.path(result.name) + '\n'));
|
|
160
|
+
}
|
|
161
|
+
} catch (cause) {
|
|
162
|
+
const detail = { code: cause.code || 'INVALID_ARGUMENT', message: cause.message };
|
|
163
|
+
if (cause.diagnostics?.length) detail.diagnostics = cause.diagnostics;
|
|
164
|
+
process.stderr.write(json ? JSON.stringify({ error: detail }, null, 2) + '\n' : detail.code + ': ' + detail.message + '\n');
|
|
165
|
+
process.exitCode = signal?.aborted ? 130 : 1;
|
|
166
|
+
}
|
|
167
|
+
}
|
package/src/probe.mjs
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { version } from './version.mjs';
|
|
2
|
+
import { spawn } from 'node:child_process';
|
|
3
|
+
import { AcpFrames } from './wire.mjs';
|
|
4
|
+
import { stopProcess } from './process.mjs';
|
|
5
|
+
import { error } from './profiles.mjs';
|
|
6
|
+
|
|
7
|
+
// Initialization only. Unlike the legacy text client, this probe can negotiate
|
|
8
|
+
// v1 and the v2 draft without implementing their different prompt flows.
|
|
9
|
+
export async function probeAcp(launch, { cwd, env = process.env, timeoutMs = 3000, signal } = {}) {
|
|
10
|
+
signal?.throwIfAborted();
|
|
11
|
+
const child = spawn(launch.command, [...launch.prefixArgs, ...launch.acpArgs], {
|
|
12
|
+
cwd, env: { ...env, ...launch.env }, shell: false, windowsHide: true,
|
|
13
|
+
detached: process.platform !== 'win32', stdio: ['pipe', 'pipe', 'pipe']
|
|
14
|
+
});
|
|
15
|
+
let timer, abort;
|
|
16
|
+
try {
|
|
17
|
+
return await new Promise((resolve, reject) => {
|
|
18
|
+
timer = setTimeout(() => reject(error('INITIALIZE_TIMEOUT', 'ACP initialization timed out.')), timeoutMs);
|
|
19
|
+
abort = () => reject(error('CANCELLED', 'ACP initialization cancelled.'));
|
|
20
|
+
signal?.addEventListener('abort', abort, { once: true });
|
|
21
|
+
const frames = new AcpFrames({ maxMessageBytes: 1024 * 1024, onMessage(message) {
|
|
22
|
+
if (message.id !== 'agentlink-probe' || message.method) return;
|
|
23
|
+
if (message.error) {
|
|
24
|
+
reject(Object.assign(error('INITIALIZE_REJECTED', message.error.message || 'Agent rejected initialization.'), {
|
|
25
|
+
remoteCode: message.error.code
|
|
26
|
+
}));
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
const value = message.result;
|
|
30
|
+
const capabilities = value?.protocolVersion === 2 ? value.capabilities : value?.agentCapabilities;
|
|
31
|
+
const info = value?.protocolVersion === 2 ? value.info : value?.agentInfo;
|
|
32
|
+
if (!value || ![1, 2].includes(value.protocolVersion) || !capabilities ||
|
|
33
|
+
typeof capabilities !== 'object' || Array.isArray(capabilities)) {
|
|
34
|
+
reject(error('UNSUPPORTED_PROTOCOL', 'Agent did not negotiate ACP v1 or v2.'));
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
const agentInfo = {};
|
|
38
|
+
for (const field of ['name', 'version', 'title']) {
|
|
39
|
+
if (typeof info?.[field] === 'string') agentInfo[field] = info[field].slice(0, 256);
|
|
40
|
+
}
|
|
41
|
+
resolve({ status: 'initialize-passed', checkedAt: new Date().toISOString(),
|
|
42
|
+
protocolVersion: value.protocolVersion, agentInfo, capabilities,
|
|
43
|
+
authMethods: Array.isArray(value.authMethods) ? value.authMethods : [] });
|
|
44
|
+
} });
|
|
45
|
+
frames.resume();
|
|
46
|
+
frames.on('error', reject);
|
|
47
|
+
child.stdout.pipe(frames);
|
|
48
|
+
child.stderr.resume();
|
|
49
|
+
child.stdout.on('error', reject);
|
|
50
|
+
child.stdin.on('error', cause => { if (cause.code !== 'EPIPE') reject(cause); });
|
|
51
|
+
child.once('error', () => reject(error('SPAWN_FAILED', 'Could not start the configured ACP executable.')));
|
|
52
|
+
child.once('exit', code => reject(error('PROCESS_EXIT', 'Agent exited during initialization (' + code + ').')));
|
|
53
|
+
child.stdin.write(JSON.stringify({ jsonrpc: '2.0', id: 'agentlink-probe', method: 'initialize',
|
|
54
|
+
params: { protocolVersion: 2, capabilities: {}, info: { name: 'agentlink-discovery', version } } }) + '\n');
|
|
55
|
+
});
|
|
56
|
+
} finally { clearTimeout(timer); signal?.removeEventListener('abort', abort); await stopProcess(child); }
|
|
57
|
+
}
|
package/src/process.mjs
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { access, readFile, stat } from 'node:fs/promises';
|
|
3
|
+
import { constants } from 'node:fs';
|
|
4
|
+
import { basename, delimiter, dirname, extname, isAbsolute, join, resolve } from 'node:path';
|
|
5
|
+
import { stripVTControlCharacters } from 'node:util';
|
|
6
|
+
import { error, strings } from './profiles.mjs';
|
|
7
|
+
import { stopProcess } from './child-process.mjs';
|
|
8
|
+
export { stopProcess } from './child-process.mjs';
|
|
9
|
+
|
|
10
|
+
export async function resolveCommand(command, prefixArgs = [], env = process.env) {
|
|
11
|
+
if (typeof command !== 'string' || !command || command.includes('\0') || !strings(prefixArgs)) {
|
|
12
|
+
throw new TypeError('Supply a command and an array of prefix arguments.');
|
|
13
|
+
}
|
|
14
|
+
const explicit = isAbsolute(command) || command.includes('/') || command.includes('\\');
|
|
15
|
+
const pathValue = Object.entries(env).find(([key]) => key.toLowerCase() === 'path')?.[1] || '';
|
|
16
|
+
const extensions = process.platform === 'win32' && !extname(command) ? ['.exe', '.com', '.cmd', ''] : [''];
|
|
17
|
+
const directories = explicit ? [''] : pathValue.split(delimiter).filter(Boolean).map(part => part.replace(/^"|"$/g, ''));
|
|
18
|
+
let executable;
|
|
19
|
+
for (const directory of directories) {
|
|
20
|
+
for (const extension of extensions) {
|
|
21
|
+
const candidate = explicit ? resolve(command + extension) : resolve(directory, command + extension);
|
|
22
|
+
try {
|
|
23
|
+
if (!(await stat(candidate)).isFile()) continue;
|
|
24
|
+
if (process.platform !== 'win32') await access(candidate, constants.X_OK);
|
|
25
|
+
executable = candidate; break;
|
|
26
|
+
} catch (cause) {
|
|
27
|
+
if (!['ENOENT', 'ENOTDIR', 'EACCES'].includes(cause.code)) throw cause;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
if (executable) break;
|
|
31
|
+
}
|
|
32
|
+
if (!executable) throw error('COMMAND_NOT_FOUND', `Cannot find installed executable "${command}".`);
|
|
33
|
+
if (process.platform === 'win32' && /\.(cmd|bat|ps1)$/i.test(executable)) {
|
|
34
|
+
// Recognize only the standard npm Node shim. Never run its shell body.
|
|
35
|
+
const metadata = await stat(executable);
|
|
36
|
+
const shim = metadata.size <= 32768 ? await readFile(executable, 'utf8') : '';
|
|
37
|
+
const match = /"%_prog%"\s+"%dp0%\\([^"\r\n]+\.(?:js|cjs|mjs))"\s+%\*/i.exec(shim);
|
|
38
|
+
if (extname(executable).toLowerCase() !== '.cmd' || !match || !/SET\s+"_prog=node"/i.test(shim)) {
|
|
39
|
+
throw error('UNSUPPORTED_LAUNCHER', 'Use a native executable, a standard npm Node launcher, or node with --prefix-args pointing to the installed entry script.');
|
|
40
|
+
}
|
|
41
|
+
const script = resolve(dirname(executable), match[1]);
|
|
42
|
+
if (!(await stat(script)).isFile()) throw error('COMMAND_NOT_FOUND', 'The npm launcher entry script is missing.');
|
|
43
|
+
const localNode = join(dirname(executable), 'node.exe');
|
|
44
|
+
let node;
|
|
45
|
+
try { node = (await stat(localNode)).isFile() ? localNode : undefined; }
|
|
46
|
+
catch (cause) { if (cause.code !== 'ENOENT') throw cause; }
|
|
47
|
+
node ??= (await resolveCommand('node.exe', [], env)).command;
|
|
48
|
+
return { command: node, prefixArgs: [script, ...prefixArgs], executableName: basename(executable, '.cmd') };
|
|
49
|
+
}
|
|
50
|
+
return { command: executable, prefixArgs: [...prefixArgs], executableName: basename(executable).replace(/\.(exe|com)$/i, '') };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export async function readHelp({ command, args, cwd, env = process.env, timeoutMs = 3000, maxBytes = 65536, signal }) {
|
|
54
|
+
if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || !Number.isSafeInteger(maxBytes) || maxBytes < 1) {
|
|
55
|
+
throw new TypeError('Help probe limits must be positive integers.');
|
|
56
|
+
}
|
|
57
|
+
signal?.throwIfAborted();
|
|
58
|
+
const child = spawn(command, args, { cwd, env, shell: false, windowsHide: true,
|
|
59
|
+
detached: process.platform !== 'win32', stdio: ['pipe', 'pipe', 'pipe'] });
|
|
60
|
+
const buffers = [];
|
|
61
|
+
let bytes = 0;
|
|
62
|
+
let abort;
|
|
63
|
+
try {
|
|
64
|
+
const code = await new Promise((resolveCode, reject) => {
|
|
65
|
+
const timer = setTimeout(() => fail(error('HELP_TIMEOUT', 'The CLI did not finish its help response.')), timeoutMs);
|
|
66
|
+
const fail = cause => { clearTimeout(timer); reject(cause); };
|
|
67
|
+
abort = () => fail(error('CANCELLED', 'Help discovery cancelled.'));
|
|
68
|
+
signal?.addEventListener('abort', abort, { once: true });
|
|
69
|
+
const collect = chunk => {
|
|
70
|
+
bytes += chunk.length;
|
|
71
|
+
if (bytes > maxBytes) { fail(error('HELP_LIMIT', 'CLI help exceeds the output limit.')); return; }
|
|
72
|
+
buffers.push(chunk);
|
|
73
|
+
};
|
|
74
|
+
child.stdout.on('data', collect); child.stderr.on('data', collect);
|
|
75
|
+
child.stdout.once('error', fail); child.stderr.once('error', fail);
|
|
76
|
+
child.stdin.once('error', cause => { if (cause.code !== 'EPIPE') fail(cause); });
|
|
77
|
+
child.once('error', () => fail(error('SPAWN_FAILED', 'Could not start the help process.')));
|
|
78
|
+
child.once('close', exitCode => { clearTimeout(timer); resolveCode(exitCode); });
|
|
79
|
+
child.stdin.end();
|
|
80
|
+
});
|
|
81
|
+
return { code, text: stripVTControlCharacters(Buffer.concat(buffers).toString('utf8')) };
|
|
82
|
+
} finally { signal?.removeEventListener('abort', abort); await stopProcess(child); }
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export async function runCommand(command, args, { cwd, env = process.env, timeoutMs = 180000, signal } = {}) {
|
|
86
|
+
signal?.throwIfAborted();
|
|
87
|
+
const child = spawn(command, args, { cwd, env, shell: false, windowsHide: true,
|
|
88
|
+
detached: process.platform !== 'win32', stdio: ['ignore', 'pipe', 'pipe'] });
|
|
89
|
+
let timer, abort;
|
|
90
|
+
const stdout = []; let bytes = 0, stderr = Buffer.alloc(0);
|
|
91
|
+
try {
|
|
92
|
+
return await new Promise((resolveRun, reject) => {
|
|
93
|
+
timer = setTimeout(() => reject(error('INSTALL_TIMEOUT', 'Installer exceeded its deadline.')), timeoutMs);
|
|
94
|
+
abort = () => reject(error('CANCELLED', 'Installation cancelled.'));
|
|
95
|
+
signal?.addEventListener('abort', abort, { once: true });
|
|
96
|
+
child.stdout.on('data', chunk => {
|
|
97
|
+
bytes += chunk.length;
|
|
98
|
+
if (bytes > 8 * 1024 * 1024) reject(error('OUTPUT_LIMIT', 'Installer output exceeds its limit.'));
|
|
99
|
+
else stdout.push(chunk);
|
|
100
|
+
});
|
|
101
|
+
child.stderr.on('data', chunk => { stderr = Buffer.concat([stderr, chunk]).subarray(-8192); });
|
|
102
|
+
child.once('error', () => reject(error('SPAWN_FAILED', 'Could not start installer: ' + command)));
|
|
103
|
+
child.once('close', code => {
|
|
104
|
+
if (code !== 0) reject(error('INSTALL_FAILED', 'Installer exited with ' + code + ': ' + stderr.toString('utf8').trim()));
|
|
105
|
+
else resolveRun(Buffer.concat(stdout).toString('utf8'));
|
|
106
|
+
});
|
|
107
|
+
});
|
|
108
|
+
} finally {
|
|
109
|
+
clearTimeout(timer); signal?.removeEventListener('abort', abort);
|
|
110
|
+
await stopProcess(child);
|
|
111
|
+
}
|
|
112
|
+
}
|