@prplkane/agentlink 0.3.0-beta.3 → 0.3.0-beta.5
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/README.md +80 -320
- package/docs/acp-qualification.md +16 -0
- package/docs/architecture.md +95 -9
- package/docs/laptop-testing.md +38 -8
- package/package.json +1 -1
- package/src/bridges.mjs +28 -12
- package/src/child-process.mjs +19 -3
- package/src/discovery.mjs +47 -6
- package/src/doctor.mjs +6 -0
- package/src/gateway.mjs +125 -29
- package/src/json-spans.mjs +42 -0
- package/src/management-cli.mjs +8 -2
- package/src/probe.mjs +48 -14
- package/src/process.mjs +3 -3
- package/src/session-defaults.mjs +5 -7
- package/src/session-history.mjs +279 -0
- package/src/version.mjs +1 -1
- package/src/wire.mjs +6 -2
package/docs/laptop-testing.md
CHANGED
|
@@ -1,22 +1,21 @@
|
|
|
1
|
-
#
|
|
1
|
+
# AgentLink setup and troubleshooting
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
external executable paths are machine-specific.
|
|
3
|
+
Install the public beta with Node.js 22 or newer and npm. AgentLink ships with zero
|
|
4
|
+
npm runtime dependencies. Agents and bridges have their own prerequisites. When moving
|
|
5
|
+
to a new machine, configure local executable paths for any externally installed agents.
|
|
7
6
|
|
|
8
7
|
## Install once
|
|
9
8
|
|
|
10
9
|
~~~sh
|
|
11
|
-
npm install -g @prplkane/agentlink@
|
|
10
|
+
npm install -g @prplkane/agentlink@beta
|
|
12
11
|
agentlink --version
|
|
13
12
|
agentlink --help
|
|
14
13
|
agentlink where
|
|
15
14
|
agentlink doctor
|
|
16
15
|
~~~
|
|
17
16
|
|
|
18
|
-
|
|
19
|
-
|
|
17
|
+
Compare `agentlink --version` with `npm view @prplkane/agentlink@beta version`.
|
|
18
|
+
Managed bridges install when you add the corresponding provider.
|
|
20
19
|
|
|
21
20
|
## Configure the agents you have
|
|
22
21
|
|
|
@@ -59,6 +58,33 @@ For a known existing distribution outside the built-in recipes, use
|
|
|
59
58
|
`agentlink add NAME --manifest PATH-OR-URL` with an individual ACP registry entry.
|
|
60
59
|
Only use a distribution you intend to install and execute.
|
|
61
60
|
|
|
61
|
+
## Custom bridges and offline installs
|
|
62
|
+
|
|
63
|
+
To share a specific bridge version, install it under a bridge ID, then point one or
|
|
64
|
+
more profiles at that ID. Replace `PACKAGE_NAME` and `VERSION` with a published npm
|
|
65
|
+
package and version.
|
|
66
|
+
|
|
67
|
+
```sh
|
|
68
|
+
agentlink bridge install review-bridge --package PACKAGE_NAME --version VERSION
|
|
69
|
+
agentlink add review --bridge review-bridge
|
|
70
|
+
agentlink bridge show review-bridge
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
An ACP registry entry can supply an npm package (`npx`), a native artifact (`binary`),
|
|
74
|
+
or a Python package (`uvx`). Python installs use a shared virtual environment and
|
|
75
|
+
require Python with venv and pip. Use `--bin` to select an executable from a package.
|
|
76
|
+
For an offline install, supply a local tarball or wheel with `--source`, or use the
|
|
77
|
+
package manager's cache. Set `--offline` to disable registry downloads by AgentLink.
|
|
78
|
+
Third-party install hooks and agent processes run with the current user's permissions.
|
|
79
|
+
|
|
80
|
+
Native artifacts can be raw executables, ZIP files, or tar.gz archives. The default
|
|
81
|
+
limits are 256 MiB per download, 512 MiB of extracted data, and 10,000 entries.
|
|
82
|
+
For other installer formats, use an externally installed executable.
|
|
83
|
+
|
|
84
|
+
Use `agentlink bridge update review-bridge --version VERSION` to switch versions.
|
|
85
|
+
Once sessions finish, `agentlink bridge prune` removes unused installations.
|
|
86
|
+
Add `--cache` to clear the package cache as well.
|
|
87
|
+
|
|
62
88
|
## Check the standard ACP connection
|
|
63
89
|
|
|
64
90
|
~~~sh
|
|
@@ -160,6 +186,10 @@ The requested rerun used a separate temporary profile with
|
|
|
160
186
|
the same model then completed chairman synthesis in 12.2 seconds. No AgentLink
|
|
161
187
|
runtime change was needed. Bridge defaults are provider-specific; merge the
|
|
162
188
|
setting with the profile's existing configuration rather than discarding it.
|
|
189
|
+
|
|
190
|
+
Since `0.3.0-beta.3`, `agentlink defaults PROFILE --effort ID` saves the same
|
|
191
|
+
choice on the profile and checks it against the bridge's advertised levels.
|
|
192
|
+
Prefer it for new setups; the environment route above still works.
|
|
163
193
|
Choose a suitable profile default and a realistic per-call deadline before a live
|
|
164
194
|
review; do not automatically retry a timed-out verdict. Unknown usage remains unknown.
|
|
165
195
|
|
package/package.json
CHANGED
package/src/bridges.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto';
|
|
2
|
-
import { chmod, mkdir, open, readdir, realpath, rm, stat,
|
|
2
|
+
import { chmod, mkdir, open, readdir, realpath, rm, stat, writeFile } from 'node:fs/promises';
|
|
3
3
|
import { basename, delimiter, dirname, join, resolve } from 'node:path';
|
|
4
4
|
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
5
5
|
import { error, profileName, strings } from './profiles.mjs';
|
|
@@ -100,7 +100,7 @@ function validateSpec(input) {
|
|
|
100
100
|
}
|
|
101
101
|
|
|
102
102
|
export class BridgeStore extends BridgeRegistry {
|
|
103
|
-
async install(id, input, { env = process.env, timeoutMs = 3000, installTimeoutMs = 180000,
|
|
103
|
+
async install(id, input, { env = process.env, timeoutMs = 3000, maxHelpBytes = 65536, installTimeoutMs = 180000,
|
|
104
104
|
offline = false, signal, validate, publish = record => this.publish(record) } = {}) {
|
|
105
105
|
profileName(id);
|
|
106
106
|
let spec = validateSpec(input);
|
|
@@ -201,7 +201,7 @@ export class BridgeStore extends BridgeRegistry {
|
|
|
201
201
|
if (!Object.hasOwn(metadata.bins, bin)) throw error('EXECUTABLE_MISSING', 'Select an executable with --bin. Available: ' + names.join(', '));
|
|
202
202
|
const launch = { ...metadata.bins[bin], acpArgs: spec.args, env: spec.env };
|
|
203
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 }));
|
|
204
|
+
const verification = await inProbeDirectory(cwd => verifyAgent(launch, { cwd, env, timeoutMs, maxHelpBytes, signal }));
|
|
205
205
|
await validate?.(launch);
|
|
206
206
|
signal?.throwIfAborted();
|
|
207
207
|
const record = { schemaVersion: 1, id, installKey, spec, launch, verification, updatedAt: new Date().toISOString() };
|
|
@@ -220,6 +220,26 @@ export class BridgeStore extends BridgeRegistry {
|
|
|
220
220
|
}
|
|
221
221
|
}, installTimeoutMs, signal);
|
|
222
222
|
}
|
|
223
|
+
async *inspectLeases() {
|
|
224
|
+
let names;
|
|
225
|
+
try { names = await readdir(this.leases); } catch (cause) { if (cause.code === 'ENOENT') return; throw cause; }
|
|
226
|
+
for (const name of names) {
|
|
227
|
+
if (!name.endsWith('.json')) continue;
|
|
228
|
+
const file = inside(this.leases, name);
|
|
229
|
+
try {
|
|
230
|
+
const lease = await readJson(file);
|
|
231
|
+
if (!Number.isSafeInteger(lease?.pid) || lease.pid < 1 || !/^[a-f0-9]{64}$/.test(lease.installKey)) {
|
|
232
|
+
throw error('INVALID_BRIDGE', 'Invalid running-connection lease.');
|
|
233
|
+
}
|
|
234
|
+
let alive = true;
|
|
235
|
+
try { process.kill(lease.pid, 0); } catch (cause) { if (cause.code === 'ESRCH') alive = false; else throw cause; }
|
|
236
|
+
yield { file, pid: lease.pid, installKey: lease.installKey, alive };
|
|
237
|
+
} catch (cause) {
|
|
238
|
+
// A connection can release its lease between readdir and readJson.
|
|
239
|
+
if (cause.code !== 'ENOENT') yield { file, error: cause };
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
}
|
|
223
243
|
async prune({ cache = false, profiles = [] } = {}) {
|
|
224
244
|
const records = await this.list();
|
|
225
245
|
if (records.some(record => record.error)) throw error('INVALID_BRIDGE', 'Repair unreadable bridge records before pruning installations.');
|
|
@@ -228,15 +248,11 @@ export class BridgeStore extends BridgeRegistry {
|
|
|
228
248
|
if (profile.bridge) continue; // Managed profiles resolve the active record, not their old snapshot.
|
|
229
249
|
for (const key of this.referencedInstallations(profile)) used.add(key);
|
|
230
250
|
}
|
|
231
|
-
let
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
if (
|
|
235
|
-
|
|
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);
|
|
251
|
+
let installations = [];
|
|
252
|
+
for await (const lease of this.inspectLeases()) {
|
|
253
|
+
if (lease.error) throw lease.error;
|
|
254
|
+
if (lease.alive) used.add(lease.installKey);
|
|
255
|
+
else await rm(lease.file, { force: true });
|
|
240
256
|
}
|
|
241
257
|
try { installations = await readdir(this.installations); } catch (cause) { if (cause.code !== 'ENOENT') throw cause; }
|
|
242
258
|
const removed = [];
|
package/src/child-process.mjs
CHANGED
|
@@ -11,7 +11,7 @@ function waitForExit(child, timeoutMs) {
|
|
|
11
11
|
});
|
|
12
12
|
}
|
|
13
13
|
|
|
14
|
-
|
|
14
|
+
async function stopTree(child) {
|
|
15
15
|
if (child.pid) {
|
|
16
16
|
if (process.platform === 'win32') {
|
|
17
17
|
if (child.exitCode === null && child.signalCode === null) {
|
|
@@ -19,7 +19,8 @@ export async function stopProcess(child) {
|
|
|
19
19
|
['/PID', String(child.pid), '/T', '/F'], { shell: false, windowsHide: true, stdio: 'ignore' });
|
|
20
20
|
await new Promise(resolveStop => {
|
|
21
21
|
const finish = () => { clearTimeout(timer); resolveStop(); };
|
|
22
|
-
|
|
22
|
+
// A busy Windows host can take several seconds to start taskkill.
|
|
23
|
+
const timer = setTimeout(() => { killer.kill(); finish(); }, 5000);
|
|
23
24
|
killer.once('error', finish); killer.once('exit', finish);
|
|
24
25
|
});
|
|
25
26
|
}
|
|
@@ -28,6 +29,21 @@ export async function stopProcess(child) {
|
|
|
28
29
|
catch (cause) { if (cause.code !== 'ESRCH') throw cause; }
|
|
29
30
|
}
|
|
30
31
|
}
|
|
31
|
-
|
|
32
|
+
await waitForExit(child, 1500);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export async function stopProcess(child) {
|
|
36
|
+
try { await stopTree(child); }
|
|
32
37
|
finally { child.stdin?.destroy(); child.stdout?.destroy(); child.stderr?.destroy(); }
|
|
33
38
|
}
|
|
39
|
+
|
|
40
|
+
// Management commands have a result of their own. Keep it (including its
|
|
41
|
+
// error code) while reporting a separate failure to terminate the owned PID.
|
|
42
|
+
export async function finishCommand(child) {
|
|
43
|
+
try { await stopProcess(child); }
|
|
44
|
+
catch (cause) {
|
|
45
|
+
child.unref();
|
|
46
|
+
process.emitWarning('Could not confirm cleanup of child PID ' + child.pid + ': ' + cause.message,
|
|
47
|
+
{ code: 'PROCESS_STOP_FAILED' });
|
|
48
|
+
}
|
|
49
|
+
}
|
package/src/discovery.mjs
CHANGED
|
@@ -6,6 +6,7 @@ import { probeAcp } from './probe.mjs';
|
|
|
6
6
|
import { providers } from './providers.mjs';
|
|
7
7
|
import { error, strings } from './profiles.mjs';
|
|
8
8
|
import { readHelp, resolveCommand } from './process.mjs';
|
|
9
|
+
import { codexAgentName } from './session-history.mjs';
|
|
9
10
|
|
|
10
11
|
function knownRecipe(provider, executableName) {
|
|
11
12
|
if (provider !== undefined) {
|
|
@@ -52,8 +53,46 @@ export function inspectHelp(text) {
|
|
|
52
53
|
return { candidates, subcommands: [...new Set(subcommands)].slice(0, 2) };
|
|
53
54
|
}
|
|
54
55
|
|
|
55
|
-
|
|
56
|
-
|
|
56
|
+
async function codexExecEphemeral(launch, { cwd, env, timeoutMs, maxBytes, signal }) {
|
|
57
|
+
// The stock adapter's "cli" subcommand uses its own bundled Codex. When an
|
|
58
|
+
// operator selects CODEX_PATH, run that executable directly without a shell.
|
|
59
|
+
const key = process.platform === 'win32' ? Object.keys(env).sort().find(key => key.toUpperCase() === 'CODEX_PATH') : 'CODEX_PATH';
|
|
60
|
+
const override = key && env[key];
|
|
61
|
+
try {
|
|
62
|
+
const executable = override && /[/\\]/.test(override) ? resolve(cwd, override) : override;
|
|
63
|
+
const direct = executable ? await resolveCommand(executable, [], env) : undefined;
|
|
64
|
+
const args = direct ? direct.prefixArgs : [...launch.prefixArgs, ...launch.acpArgs, 'cli'];
|
|
65
|
+
const { code, text } = await readHelp({ command: direct?.command ?? launch.command, args: [...args, 'exec', '--help'],
|
|
66
|
+
cwd, env, timeoutMs, maxBytes, signal });
|
|
67
|
+
const options = text.split(/^Options:[ \t]*\r?$/m)[1]?.split(/^\S/m, 1)[0];
|
|
68
|
+
if (code !== 0 || !/^Usage:[ \t]+codex(?:\.exe)?[ \t]+exec(?:[ \t]|$)/m.test(text) || !options?.trim()) return 'unknown';
|
|
69
|
+
return /^[ \t]{1,8}(?:-\w,[ \t]+)?--ephemeral(?:[ \t]{2,}[^\r\n]*)?[ \t]*\r?$/m.test(options) ? 'advertised' : 'not-advertised';
|
|
70
|
+
} catch (cause) {
|
|
71
|
+
if (signal?.aborted) throw cause;
|
|
72
|
+
return 'unknown';
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export async function verifyAgent(launch, { cwd = process.cwd(), env = process.env, timeoutMs = 3000, maxHelpBytes = 65536, signal } = {}) {
|
|
77
|
+
const options = { cwd, env, timeoutMs, signal };
|
|
78
|
+
const verification = await probeAcp(launch, options);
|
|
79
|
+
const codex = verification.agentInfo.name === codexAgentName;
|
|
80
|
+
// Apps negotiate history on v1. A v2 result or a Codex downgrade that
|
|
81
|
+
// never received the v1 opt-in cannot establish what that client will see.
|
|
82
|
+
if (verification.protocolVersion === 2 || codex) {
|
|
83
|
+
try {
|
|
84
|
+
verification.sessionHistory = (await probeAcp(launch, { ...options, historyV1: true })).sessionHistory;
|
|
85
|
+
} catch (cause) {
|
|
86
|
+
if (signal?.aborted) throw cause;
|
|
87
|
+
verification.sessionHistory.acpV1Strategy = 'unknown';
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
if (codex) {
|
|
91
|
+
verification.sessionHistory.codexExecEphemeral = await codexExecEphemeral(launch, {
|
|
92
|
+
...options, env: { ...env, ...launch.env }, maxBytes: maxHelpBytes
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
return verification;
|
|
57
96
|
}
|
|
58
97
|
|
|
59
98
|
export async function inProbeDirectory(callback) {
|
|
@@ -63,9 +102,11 @@ export async function inProbeDirectory(callback) {
|
|
|
63
102
|
finally {
|
|
64
103
|
if (dirname(directory) !== base || !basename(directory).startsWith('agentlink-probe-')) throw error('INVALID_PATH', 'Unexpected probe directory.');
|
|
65
104
|
// Windows may retain a just-stopped descendant's cwd for a short time.
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
105
|
+
try { await rm(directory, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }); }
|
|
106
|
+
catch (cause) {
|
|
107
|
+
process.emitWarning('Could not remove probe directory ' + directory + ': ' + cause.message,
|
|
108
|
+
{ code: 'PROBE_CLEANUP_FAILED' });
|
|
109
|
+
}
|
|
69
110
|
}
|
|
70
111
|
}
|
|
71
112
|
|
|
@@ -99,7 +140,7 @@ export async function discoverAgent({ command, prefixArgs = [], acpArgs, provide
|
|
|
99
140
|
if (helpArgs) candidate.discovery.helpArgs = [...helpArgs];
|
|
100
141
|
if (help) candidate.discovery.helpSha256 = createHash('sha256').update(help).digest('hex');
|
|
101
142
|
try {
|
|
102
|
-
candidate.verification = verify ? await verifyAgent(candidate, { cwd, env, timeoutMs, signal }) : { status: 'pending' };
|
|
143
|
+
candidate.verification = verify ? await verifyAgent(candidate, { cwd, env, timeoutMs, maxHelpBytes, signal }) : { status: 'pending' };
|
|
103
144
|
candidate.protocolVersion = candidate.verification.protocolVersion || 1;
|
|
104
145
|
return candidate;
|
|
105
146
|
} catch (cause) {
|
package/src/doctor.mjs
CHANGED
|
@@ -34,6 +34,12 @@ export async function doctor(runtime) {
|
|
|
34
34
|
await launchFiles(record.launch);
|
|
35
35
|
});
|
|
36
36
|
}
|
|
37
|
+
for await (const lease of runtime.bridges.inspectLeases()) {
|
|
38
|
+
if (lease.error) checks.push({ scope: 'lease', name: lease.file, status: 'error',
|
|
39
|
+
code: 'INVALID_LEASE', message: 'Cannot verify connection lease: ' + lease.error.message });
|
|
40
|
+
else if (!lease.alive) checks.push({ scope: 'lease', name: lease.file, status: 'note', pid: lease.pid,
|
|
41
|
+
code: 'STALE_LEASE', message: 'Connection owner has exited. Run agentlink bridge prune to remove its lease.' });
|
|
42
|
+
}
|
|
37
43
|
const lockFiles = [join(runtime.home, 'management.lock'), join(runtime.home, 'leases.lock')];
|
|
38
44
|
try {
|
|
39
45
|
for (const name of await readdir(join(runtime.home, 'locks'))) {
|
package/src/gateway.mjs
CHANGED
|
@@ -4,16 +4,32 @@ import { AcpFrames } from './wire.mjs';
|
|
|
4
4
|
import { stopProcess } from './child-process.mjs';
|
|
5
5
|
import { error, strings } from './profiles.mjs';
|
|
6
6
|
import { authMarker, terminalAuthReply } from './terminal-auth.mjs';
|
|
7
|
+
import { member, requestKey, setField, whitespace } from './json-spans.mjs';
|
|
8
|
+
import { clientWantsHistory, codexKey, historyKey, SessionHistory } from './session-history.mjs';
|
|
9
|
+
|
|
10
|
+
// The reply to a session/new that AgentLink could not prepare, for example
|
|
11
|
+
// because the profile file was unreadable at that moment. The request ID is
|
|
12
|
+
// copied as raw text so large numeric IDs keep their exact bytes.
|
|
13
|
+
function sessionSetupError(source, cause) {
|
|
14
|
+
const id = source.slice(...member(source, whitespace(source, 0), 'id'));
|
|
15
|
+
const historyError = ['INVALID_SESSION_HISTORY', 'SESSION_HISTORY_UNSUPPORTED', 'INVALID_REQUEST_ID'].includes(cause.code);
|
|
16
|
+
const detail = { code: historyError ? -32602 : -32603, message: 'AgentLink could not prepare this session: ' + cause.message,
|
|
17
|
+
data: { code: cause.code || 'SESSION_SETUP_FAILED' } };
|
|
18
|
+
return Buffer.from('{"jsonrpc":"2.0","id":' + id + ',"error":' + JSON.stringify(detail) + '}\n');
|
|
19
|
+
}
|
|
7
20
|
|
|
8
21
|
// One process/connection per caller; installed bridges and profiles are shared.
|
|
9
22
|
// No initialize, session/new, task, approval, download or discovery is injected.
|
|
10
23
|
export async function runGateway(launch, { cwd = process.cwd(), env = process.env,
|
|
11
24
|
input = process.stdin, output = process.stdout, diagnostics = process.stderr,
|
|
12
25
|
signal, readDefaults, extraArgs = [], interactive = Boolean(process.stdin.isTTY),
|
|
13
|
-
maxMessageBytes = 16 * 1024 * 1024, shutdownGraceMs
|
|
14
|
-
if (!strings(extraArgs) || !Number.isSafeInteger(shutdownGraceMs) || shutdownGraceMs < 1) {
|
|
26
|
+
maxMessageBytes = 16 * 1024 * 1024, shutdownGraceMs } = {}) {
|
|
27
|
+
if (!strings(extraArgs) || (shutdownGraceMs !== undefined && (!Number.isSafeInteger(shutdownGraceMs) || shutdownGraceMs < 1))) {
|
|
15
28
|
throw new TypeError('Invalid gateway arguments.');
|
|
16
29
|
}
|
|
30
|
+
// A healthy bridge can spend several seconds cleaning up after EOF.
|
|
31
|
+
const eofGraceMs = shutdownGraceMs ?? 5000;
|
|
32
|
+
const pipeGraceMs = shutdownGraceMs ?? 750;
|
|
17
33
|
signal?.throwIfAborted();
|
|
18
34
|
// ACP terminal-auth methods append argv to the configured launch command.
|
|
19
35
|
// Append those bytes to the bridge's base argv, not to management option parsing.
|
|
@@ -23,15 +39,21 @@ export async function runGateway(launch, { cwd = process.cwd(), env = process.en
|
|
|
23
39
|
cwd, env: terminal ? { ...launch.env, ...env } : { ...env, ...launch.env }, shell: false, windowsHide: !terminal,
|
|
24
40
|
detached: process.platform !== 'win32', stdio: terminal ? 'inherit' : ['pipe', 'pipe', 'pipe']
|
|
25
41
|
});
|
|
26
|
-
let failure, inputTimer, closing = false;
|
|
42
|
+
let failure, inputTimer, history, closing = false;
|
|
27
43
|
const pumps = new AbortController();
|
|
28
44
|
let stopPromise;
|
|
29
45
|
const stop = () => stopPromise ??= stopProcess(child).catch(cause => { failure ??= cause; });
|
|
30
46
|
const fail = cause => {
|
|
31
|
-
failure
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
47
|
+
if (failure) return;
|
|
48
|
+
failure = cause;
|
|
49
|
+
const halt = () => {
|
|
50
|
+
pumps.abort();
|
|
51
|
+
if (!terminal) output.destroy(); // Interrupt blocked final writes.
|
|
52
|
+
void stop();
|
|
53
|
+
};
|
|
54
|
+
if (!history) return halt();
|
|
55
|
+
input.pause();
|
|
56
|
+
void history.disconnect().finally(halt);
|
|
35
57
|
};
|
|
36
58
|
const aborted = () => fail(error('CANCELLED', 'AgentLink connection was terminated.'));
|
|
37
59
|
signal?.addEventListener('abort', aborted, { once: true });
|
|
@@ -43,37 +65,110 @@ export async function runGateway(launch, { cwd = process.cwd(), env = process.en
|
|
|
43
65
|
let inputPump = Promise.resolve();
|
|
44
66
|
let outputFrames;
|
|
45
67
|
if (!terminal) {
|
|
46
|
-
let defaultsRelay, protocolVersion;
|
|
68
|
+
let defaultsRelay, protocolVersion, refusal, prepared, awaitingHistory = false, outputClosed = false;
|
|
69
|
+
const send = frame => {
|
|
70
|
+
if (closing || child.stdin.destroyed || child.stdin.writableEnded) return false;
|
|
71
|
+
child.stdin.write(frame);
|
|
72
|
+
return true;
|
|
73
|
+
};
|
|
74
|
+
const publish = frame => {
|
|
75
|
+
if (!closing && !outputClosed && !outputFrames.destroyed) outputFrames.push(frame);
|
|
76
|
+
};
|
|
77
|
+
function rejectRequest(source, cause) {
|
|
78
|
+
refusal = sessionSetupError(source, cause);
|
|
79
|
+
diagnostics.write((cause.code || 'SESSION_SETUP_FAILED') + ': ' + cause.message + '\n');
|
|
80
|
+
}
|
|
47
81
|
async function prepareSession(message, source) {
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
82
|
+
try {
|
|
83
|
+
if (Object.hasOwn(message.params?._meta ?? {}, historyKey)) {
|
|
84
|
+
if (!history) throw error('SESSION_HISTORY_UNSUPPORTED', 'Per-session history requires ACP v1 negotiation.');
|
|
85
|
+
prepared = history.prepare(message, source);
|
|
86
|
+
}
|
|
87
|
+
const defaults = readDefaults ? await readDefaults() : launch.defaults;
|
|
88
|
+
if (!defaults || !Object.keys(defaults).length) return;
|
|
89
|
+
if (!defaultsRelay) {
|
|
90
|
+
const { SessionDefaults } = await import('./session-defaults.mjs');
|
|
91
|
+
defaultsRelay = new SessionDefaults(send, maxMessageBytes, sessionId => history?.failedSetup(sessionId));
|
|
92
|
+
}
|
|
93
|
+
defaultsRelay.expectSession(message, source, defaults, protocolVersion);
|
|
94
|
+
} catch (cause) {
|
|
95
|
+
// Only this creation fails. The bridge never sees it, and the other
|
|
96
|
+
// sessions on this connection keep running.
|
|
97
|
+
history?.forgetRequest(message, source);
|
|
98
|
+
rejectRequest(source, cause);
|
|
53
99
|
}
|
|
54
|
-
defaultsRelay.expectSession(message, source, defaults, protocolVersion);
|
|
55
100
|
}
|
|
56
|
-
const initializeIds = new
|
|
101
|
+
const initializeIds = new Map();
|
|
57
102
|
inputPump = pipeline(input, new AcpFrames({ maxMessageBytes, onMessage(message, source) {
|
|
58
|
-
if (
|
|
59
|
-
if (message.method
|
|
60
|
-
|
|
61
|
-
|
|
103
|
+
if (failure) return;
|
|
104
|
+
if (message.method && history?.reserved(message.id)) {
|
|
105
|
+
return rejectRequest(source, error('INVALID_REQUEST_ID', 'This request ID is reserved by the gateway.'));
|
|
106
|
+
}
|
|
107
|
+
if (message.method === 'initialize' && Object.hasOwn(message, 'id')) {
|
|
108
|
+
const wants = clientWantsHistory(message.params);
|
|
109
|
+
// Changing upstream AIR capabilities on a live connection can turn an
|
|
110
|
+
// archive into permanent deletion. A negotiated client initializes once.
|
|
111
|
+
if (history || awaitingHistory || (wants && (protocolVersion || initializeIds.size))) {
|
|
112
|
+
return rejectRequest(source, error('INVALID_SESSION_HISTORY', 'History negotiation requires a fresh connection.'));
|
|
113
|
+
}
|
|
114
|
+
awaitingHistory = wants;
|
|
115
|
+
const air = message.params?.clientCapabilities?._meta?.jetbrains?.air?.capabilities;
|
|
116
|
+
initializeIds.set(requestKey(message.id, source), { wants, airIndex: Array.isArray(air) && air.includes('sessionIndex') });
|
|
117
|
+
if (wants) {
|
|
118
|
+
const upstream = setField(source, ['params', 'clientCapabilities', '_meta', historyKey], undefined);
|
|
119
|
+
prepared = Buffer.from(setField(upstream, ['params', 'clientCapabilities', '_meta', codexKey], { version: 1 }));
|
|
120
|
+
}
|
|
121
|
+
} else if (message.method === 'session/new' && Object.hasOwn(message, 'id')) {
|
|
122
|
+
return prepareSession(message, source);
|
|
123
|
+
} else if (history && message.method) {
|
|
124
|
+
return history.beforeClient(message, source).catch(cause => rejectRequest(source, cause));
|
|
125
|
+
}
|
|
126
|
+
}, mapMessage() {
|
|
127
|
+
const frame = prepared;
|
|
128
|
+
prepared = undefined;
|
|
129
|
+
if (failure) return null;
|
|
130
|
+
if (!refusal) return frame;
|
|
131
|
+
publish(refusal);
|
|
132
|
+
refusal = undefined;
|
|
133
|
+
return null;
|
|
134
|
+
} }), child.stdin, { end: false, signal: pumps.signal }).then(async () => {
|
|
135
|
+
await history?.disconnect();
|
|
136
|
+
if (!child.stdin.destroyed && !child.stdin.writableEnded) child.stdin.end();
|
|
137
|
+
if (!closing && child.exitCode === null && child.signalCode === null) {
|
|
138
|
+
inputTimer = setTimeout(() => { void stop(); }, eofGraceMs);
|
|
139
|
+
}
|
|
62
140
|
}, cause => {
|
|
63
141
|
if (closing) return;
|
|
64
142
|
// A normally exiting bridge can close its stdin before the exit event.
|
|
65
143
|
// Give it time to finish and drain stdout instead of destroying its reply.
|
|
66
144
|
if (['EPIPE', 'ERR_STREAM_PREMATURE_CLOSE', 'ERR_STREAM_DESTROYED'].includes(cause.code)) {
|
|
67
|
-
if (child.exitCode === null && child.signalCode === null) inputTimer = setTimeout(() => fail(cause),
|
|
145
|
+
if (child.exitCode === null && child.signalCode === null) inputTimer = setTimeout(() => fail(cause), pipeGraceMs);
|
|
68
146
|
} else fail(cause);
|
|
69
147
|
});
|
|
70
|
-
outputFrames = new AcpFrames({ maxMessageBytes,
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
148
|
+
outputFrames = new AcpFrames({ maxMessageBytes, async onEnd() {
|
|
149
|
+
await history?.endOutput();
|
|
150
|
+
outputClosed = true;
|
|
151
|
+
}, mapMessage(message, source) {
|
|
152
|
+
const key = !message.method && initializeIds.size ? requestKey(message.id, source) : undefined;
|
|
153
|
+
if (initializeIds.has(key)) {
|
|
154
|
+
const { wants, airIndex } = initializeIds.get(key);
|
|
155
|
+
initializeIds.delete(key);
|
|
156
|
+
if (wants) awaitingHistory = false;
|
|
157
|
+
protocolVersion = message.result?.protocolVersion;
|
|
158
|
+
const auth = terminalAuthReply(message, source);
|
|
159
|
+
const caps = message.result?.agentCapabilities;
|
|
160
|
+
if (wants && protocolVersion === 1 && (caps == null || typeof caps === 'object' && !Array.isArray(caps))) {
|
|
161
|
+
history ??= new SessionHistory(message.result, send, body => publish(Buffer.concat([body, Buffer.from('\n')])), maxMessageBytes,
|
|
162
|
+
{ requestedAirIndex: airIndex, warn: detail => diagnostics.write('SESSION_HISTORY_UNCONFIRMED: ' + detail + '\n') });
|
|
163
|
+
return history.capability(auth?.toString() ?? source);
|
|
164
|
+
}
|
|
165
|
+
return auth;
|
|
166
|
+
}
|
|
167
|
+
const annotated = history?.agentMessage(message, source);
|
|
168
|
+
if (annotated === null || !defaultsRelay) return annotated;
|
|
169
|
+
if (annotated) { source = annotated.toString(); message = JSON.parse(source); }
|
|
170
|
+
const configured = defaultsRelay.agentMessage(message, source);
|
|
171
|
+
return configured === undefined ? annotated : configured;
|
|
77
172
|
} });
|
|
78
173
|
outputPump = pipeline(child.stdout, outputFrames, output, { end: false, signal: pumps.signal })
|
|
79
174
|
.catch(cause => { if (!closing) fail(cause); });
|
|
@@ -94,18 +189,19 @@ export async function runGateway(launch, { cwd = process.cwd(), env = process.en
|
|
|
94
189
|
if (done) return;
|
|
95
190
|
if (!failure && !output.destroyed && (output.writableLength || output.writableNeedDrain || child.stdout?.readableLength ||
|
|
96
191
|
outputFrames?.readableLength || outputFrames?.writableLength)) {
|
|
97
|
-
flushTimer = setTimeout(idle,
|
|
192
|
+
flushTimer = setTimeout(idle, pipeGraceMs);
|
|
98
193
|
} else finish();
|
|
99
194
|
};
|
|
100
195
|
// end:false leaves the caller's stream open and may resolve before its
|
|
101
196
|
// final write callback; also wait for that queued output to drain.
|
|
102
197
|
outputPump.then(() => { if (failure || !output.writableLength || output.destroyed) finish(); });
|
|
103
|
-
flushTimer = setTimeout(idle,
|
|
198
|
+
flushTimer = setTimeout(idle, pipeGraceMs);
|
|
104
199
|
});
|
|
105
200
|
if (failure) throw failure;
|
|
106
201
|
return { exitCode };
|
|
107
202
|
} finally {
|
|
108
203
|
closing = true;
|
|
204
|
+
history?.dispose();
|
|
109
205
|
clearTimeout(inputTimer); clearTimeout(flushTimer);
|
|
110
206
|
signal?.removeEventListener('abort', aborted);
|
|
111
207
|
diagnostics.off('error', fail);
|
package/src/json-spans.mjs
CHANGED
|
@@ -16,6 +16,48 @@ export function valueEnd(text, start) {
|
|
|
16
16
|
}
|
|
17
17
|
return text.length;
|
|
18
18
|
}
|
|
19
|
+
// Match requests without rounding JSON integers beyond JavaScript's safe range.
|
|
20
|
+
export function requestKey(id, source) {
|
|
21
|
+
if (typeof id === 'number' && !Number.isSafeInteger(id)) return 'number:' + source.slice(...member(source, whitespace(source, 0), 'id'));
|
|
22
|
+
return JSON.stringify(id);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function withoutMember(source, at, name) {
|
|
26
|
+
const parts = [];
|
|
27
|
+
let start = at + 1, key = whitespace(source, start);
|
|
28
|
+
while (source[key] !== '}') {
|
|
29
|
+
const keyEnd = valueEnd(source, key);
|
|
30
|
+
const value = whitespace(source, whitespace(source, keyEnd) + 1);
|
|
31
|
+
const end = whitespace(source, valueEnd(source, value));
|
|
32
|
+
if (JSON.parse(source.slice(key, keyEnd)) !== name) parts.push(source.slice(start, end));
|
|
33
|
+
if (source[end] === '}') return source.slice(0, at + 1) + parts.join(',') + source.slice(end);
|
|
34
|
+
start = end + 1;
|
|
35
|
+
key = whitespace(source, start);
|
|
36
|
+
}
|
|
37
|
+
return source;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// Set a nested metadata field without reserializing its siblings, which may
|
|
41
|
+
// contain opaque identifiers or large integers. Missing ancestors are objects.
|
|
42
|
+
export function setField(source, path, value) {
|
|
43
|
+
let at = whitespace(source, 0);
|
|
44
|
+
for (const [index, name] of path.entries()) {
|
|
45
|
+
if (source[at] !== '{') throw new TypeError('Expected an ACP metadata object.');
|
|
46
|
+
const span = member(source, at, name);
|
|
47
|
+
if (!span || (index < path.length - 1 && source.startsWith('null', span[0]))) {
|
|
48
|
+
if (value === undefined) return source;
|
|
49
|
+
let tree = value;
|
|
50
|
+
for (let i = path.length - 1; i > index; i--) tree = { [path[i]]: tree };
|
|
51
|
+
if (span) return source.slice(0, span[0]) + JSON.stringify(tree) + source.slice(span[1]);
|
|
52
|
+
const comma = source[whitespace(source, at + 1)] === '}' ? '' : ',';
|
|
53
|
+
return source.slice(0, at + 1) + JSON.stringify(name) + ':' + JSON.stringify(tree) + comma + source.slice(at + 1);
|
|
54
|
+
}
|
|
55
|
+
if (index === path.length - 1) return value === undefined ? withoutMember(source, at, name)
|
|
56
|
+
: source.slice(0, span[0]) + JSON.stringify(value) + source.slice(span[1]);
|
|
57
|
+
at = span[0];
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
19
61
|
export function member(text, start, name) {
|
|
20
62
|
if (text[start] !== '{') return;
|
|
21
63
|
let found, at = whitespace(text, start + 1);
|
package/src/management-cli.mjs
CHANGED
|
@@ -171,8 +171,14 @@ export async function runManagement(argv, { signal, cliURL } = {}) {
|
|
|
171
171
|
result.checks.map(check => check.status + '\t' + check.scope + ' ' + check.name +
|
|
172
172
|
(check.message ? ': ' + check.message : '')).join('\n') + '\n');
|
|
173
173
|
else if (action === 'remove') process.stdout.write('Removed ' + first + '.\n');
|
|
174
|
-
else
|
|
175
|
-
|
|
174
|
+
else {
|
|
175
|
+
const { status, sessionHistory } = result.verification;
|
|
176
|
+
const lines = [(result.name || first) + ': ' + status];
|
|
177
|
+
if (sessionHistory) lines.push('ACP v1 session history: ' + sessionHistory.acpV1Strategy);
|
|
178
|
+
if (sessionHistory?.codexExecEphemeral) lines.push('Codex exec --ephemeral: ' + sessionHistory.codexExecEphemeral);
|
|
179
|
+
if (action !== 'check') lines.push('Saved ' + manager.store.path(result.name));
|
|
180
|
+
process.stdout.write(lines.join('\n') + '\n');
|
|
181
|
+
}
|
|
176
182
|
}
|
|
177
183
|
} catch (cause) {
|
|
178
184
|
const detail = { code: cause.code || 'INVALID_ARGUMENT', message: cause.message };
|