@prplkane/agentlink 0.3.0-beta.1 → 0.3.0-beta.3
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 +47 -15
- package/docs/architecture.md +27 -3
- package/docs/laptop-testing.md +7 -4
- package/package.json +3 -2
- package/src/cli.mjs +10 -1
- package/src/client.mjs +11 -1
- package/src/gateway.mjs +16 -3
- package/src/index.mjs +33 -2
- package/src/json-spans.mjs +31 -0
- package/src/management-cli.mjs +18 -2
- package/src/probe.mjs +37 -10
- package/src/profiles.mjs +12 -2
- package/src/replace-file.mjs +20 -0
- package/src/session-defaults.mjs +106 -0
- package/src/session-options.mjs +63 -0
- package/src/storage.mjs +5 -4
- package/src/terminal-auth.mjs +1 -32
- package/src/version.mjs +1 -1
- package/src/wire.mjs +8 -6
package/README.md
CHANGED
|
@@ -1,18 +1,14 @@
|
|
|
1
1
|
# AgentLink
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
once, then use its saved name from any ACP client. AgentLink manages selected
|
|
5
|
-
bridges in your user account and exposes their actual capabilities through
|
|
6
|
-
standard ACP.
|
|
3
|
+
Connect ACP clients to agent CLIs through named profiles and centrally managed bridges.
|
|
7
4
|
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
[Live ACP qualification](docs/acp-qualification.md) records Codex, Claude and agy
|
|
12
|
-
results through Roundtable, including the initial chairman timeout, the successful
|
|
13
|
-
low-effort rerun and remaining limits.
|
|
5
|
+
AgentLink saves the launch command for each profile. Any client that speaks the
|
|
6
|
+
Agent Client Protocol (ACP) can use that name to open a session with the selected
|
|
7
|
+
agent. The client owns the conversation, and the agent supplies its capabilities.
|
|
14
8
|
|
|
15
|
-
|
|
9
|
+
Requires Node.js 22 or newer. The public beta, `0.3.0-beta.3`, has no npm runtime
|
|
10
|
+
dependencies. See the [qualification results](docs/acp-qualification.md) for tested
|
|
11
|
+
providers, platforms and known limits.
|
|
16
12
|
|
|
17
13
|
## Install and configure
|
|
18
14
|
|
|
@@ -80,10 +76,9 @@ sessions. Profiles, installed bridge versions and configuration are shared.
|
|
|
80
76
|
Clients retain ownership of session setup, working directories, permission
|
|
81
77
|
decisions, task deadlines and their own conversation history.
|
|
82
78
|
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
[
|
|
86
|
-
cross-project check and real-agent qualification steps.
|
|
79
|
+
For example, Codex can coordinate a Roundtable review while each seat and the
|
|
80
|
+
chairman use a saved AgentLink profile. See the [illustrated Roundtable workflow](https://github.com/prplkane/roundtable#review-in-codex-with-agentlink-seats)
|
|
81
|
+
or the [cross-project testing guide](docs/laptop-testing.md#roundtable-integration).
|
|
87
82
|
|
|
88
83
|
The gateway forwards JSON-RPC in both directions: initialization/version
|
|
89
84
|
negotiation, capabilities, authentication, prompts, streaming, cancellation,
|
|
@@ -102,6 +97,39 @@ The ACP entry point loads only the runtime modules. Installation, discovery and
|
|
|
102
97
|
the compatibility client load only for management commands. External profiles
|
|
103
98
|
do not need the installation lease lock; managed profiles briefly acquire it.
|
|
104
99
|
|
|
100
|
+
## Choose a model and effort once for a profile
|
|
101
|
+
|
|
102
|
+
Use the provider profile your projects already launch. Inspect the bridge's
|
|
103
|
+
live choices, then replace the example IDs below with values from the output.
|
|
104
|
+
|
|
105
|
+
~~~sh
|
|
106
|
+
agentlink models agy
|
|
107
|
+
agentlink models agy --model MODEL_ID
|
|
108
|
+
agentlink defaults agy --model MODEL_ID --effort EFFORT_ID
|
|
109
|
+
agentlink defaults agy
|
|
110
|
+
agentlink defaults agy --clear-model --clear-effort
|
|
111
|
+
~~~
|
|
112
|
+
|
|
113
|
+
`models` opens a temporary session with the profile's launch settings and an
|
|
114
|
+
empty working directory. It sends no prompt. The JSON shows the saved defaults,
|
|
115
|
+
the bridge's current model and effort, and each advertised choice's ID and
|
|
116
|
+
name. Use `--model` to preview the effort levels for a particular model.
|
|
117
|
+
An unavailable selector appears as `null`. Inspection ignores saved pins so it
|
|
118
|
+
can show replacements after a vendor retires a model.
|
|
119
|
+
|
|
120
|
+
`defaults` with no flags shows the saved choices. Setting a model or effort
|
|
121
|
+
validates the resulting pair in a temporary session before saving it. An
|
|
122
|
+
omitted flag keeps its previous setting. Use `--clear-effort` alongside a
|
|
123
|
+
model change to follow that model's own reasoning default. Clearing both
|
|
124
|
+
returns to vendor defaults and works offline.
|
|
125
|
+
|
|
126
|
+
All ACP clients launching that profile inherit the choices on their next
|
|
127
|
+
`session/new`, including on an open connection. Running and resumed sessions
|
|
128
|
+
keep their settings. A client may explicitly override a choice for its session.
|
|
129
|
+
If a saved ID disappears, session creation reports the unavailable choice so
|
|
130
|
+
you can replace it once for every project. Bridge updates still check ACP
|
|
131
|
+
initialization. Actual model and effort support is checked in the session.
|
|
132
|
+
|
|
105
133
|
## Discover an unfamiliar agent
|
|
106
134
|
|
|
107
135
|
~~~sh
|
|
@@ -259,12 +287,16 @@ compatibility; use `check PROFILE` for initialization.
|
|
|
259
287
|
|
|
260
288
|
~~~sh
|
|
261
289
|
npm test
|
|
290
|
+
npm run test:maturity
|
|
262
291
|
npm pack
|
|
263
292
|
~~~
|
|
264
293
|
|
|
265
294
|
Tests use local fixture agents and locally produced npm packages, wheels and
|
|
266
295
|
binary archives. They cover independent ACP clients, shared updates, rollback,
|
|
267
296
|
leases/pruning, discovery, authentication forwarding and process cleanup.
|
|
297
|
+
The separate maturity check starts 50 batches of eight managed clients with
|
|
298
|
+
synthetic profiles, checks model and effort inheritance on every prompt, and
|
|
299
|
+
verifies lease cleanup after each batch.
|
|
268
300
|
Python installation coverage runs when Python is available. No vendor account
|
|
269
301
|
or paid model call is needed.
|
|
270
302
|
A GitHub Actions workflow is included for Windows/Linux/macOS with Node 22/24
|
package/docs/architecture.md
CHANGED
|
@@ -27,7 +27,7 @@ methods. Backpressure follows Node streams. It does not initialize or create a
|
|
|
27
27
|
session on the application's behalf, approve tools, retry a prompt, or record
|
|
28
28
|
conversation content.
|
|
29
29
|
|
|
30
|
-
|
|
30
|
+
One exception to byte-preserving forwarding is an initialize response containing
|
|
31
31
|
terminal authentication methods. Their argv receives an AgentLink marker so a
|
|
32
32
|
client's subsequent standard interactive relaunch is recognized even if the
|
|
33
33
|
upstream method only supplies environment variables. The launcher strips that
|
|
@@ -35,6 +35,23 @@ marker and appends the original arguments to the original bridge invocation.
|
|
|
35
35
|
Only the affected argument spans are rewritten. Large numeric IDs, numeric
|
|
36
36
|
extensions, unrelated fields and whitespace retain their original JSON bytes.
|
|
37
37
|
|
|
38
|
+
On each new session the gateway reads the profile's optional model and effort
|
|
39
|
+
defaults. With pins present, it waits for the bridge's session options and
|
|
40
|
+
uses standard ACP setters to apply the model, then the effort advertised for
|
|
41
|
+
that model. It returns the confirmed options to the client before the first
|
|
42
|
+
prompt. A rejected or unconfirmed choice fails that session creation. Future
|
|
43
|
+
sessions on the same connection read later edits. Existing sessions, resume
|
|
44
|
+
operations and explicit client setters pass through. The connection keeps
|
|
45
|
+
its original bridge lease throughout.
|
|
46
|
+
|
|
47
|
+
Each configured creation keeps its own outstanding request ID. The gateway
|
|
48
|
+
reuses that ID upstream after the bridge's creation response and holds the
|
|
49
|
+
downstream response until configuration finishes. It replaces only the JSON
|
|
50
|
+
span for the options. Session notifications received during this exchange
|
|
51
|
+
follow the creation reply. Intermediate configuration notifications are
|
|
52
|
+
superseded by the setter's complete option list. Pending setup and buffered
|
|
53
|
+
notifications have per-connection limits.
|
|
54
|
+
|
|
38
55
|
The connection owns one bridge process. On client EOF it allows a short exit
|
|
39
56
|
grace, then stops the process tree where the host supports it. Existing ACP
|
|
40
57
|
sessions stay with that process when profiles or installations change.
|
|
@@ -77,6 +94,12 @@ only checked descendants of the managed installation directory.
|
|
|
77
94
|
Profile and bridge metadata are flushed before publication. A live-process
|
|
78
95
|
lease is atomically written without a durability flush: it does not need to
|
|
79
96
|
survive a machine restart when its owning process cannot survive either.
|
|
97
|
+
On Windows, atomic replacement retries file-sharing conflicts up to five times
|
|
98
|
+
with at most 750 ms of retry delay. A persistent failure leaves the old file in
|
|
99
|
+
place and reports the error; replacement never deletes the destination first.
|
|
100
|
+
Lock acquisition and cleanup also retry short-lived Windows sharing errors.
|
|
101
|
+
An acquisition respects the remaining lock deadline and cancellation. A
|
|
102
|
+
persistent access error reports its original operating system code.
|
|
80
103
|
|
|
81
104
|
No automatic deletion of previous versions occurs during an update. Users can
|
|
82
105
|
prune after sessions finish and optionally clear the download cache. External
|
|
@@ -112,10 +135,11 @@ the profile instead of dropping its options and activating a different launch.
|
|
|
112
135
|
|---|---|
|
|
113
136
|
| `cli.mjs`, `runtime.mjs` | Small ACP launch entry, saved records and live-process leases |
|
|
114
137
|
| `management-cli.mjs`, `doctor.mjs` | Management commands and read-only local diagnostics |
|
|
115
|
-
| `gateway.mjs`, `wire.mjs`, `terminal-auth.mjs` | ACP forwarding, framing, backpressure and lossless
|
|
138
|
+
| `gateway.mjs`, `wire.mjs`, `terminal-auth.mjs`, `json-spans.mjs` | ACP forwarding, framing, backpressure and lossless JSON edits |
|
|
139
|
+
| `session-defaults.mjs`, `session-options.mjs` | Per-session defaults and bridge-advertised model and effort choices |
|
|
116
140
|
| `profiles.mjs`, `storage.mjs` | User profiles, atomic records and operation locks |
|
|
117
141
|
| `bridges.mjs`, `artifacts.mjs` | Selected distributions, shared installations, integrity and bounded extraction |
|
|
118
|
-
| `discovery.mjs`, `probe.mjs` | Help/metadata matching
|
|
142
|
+
| `discovery.mjs`, `probe.mjs` | Help/metadata matching, initialization checks and explicit option inspection |
|
|
119
143
|
| `process.mjs`, `child-process.mjs` | Executable resolution, bounded probes/installers and shared process cleanup |
|
|
120
144
|
| `providers.mjs` | Small documented launch/install recipes |
|
|
121
145
|
| `index.mjs` | Management coordination and compatibility library exports |
|
package/docs/laptop-testing.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Testing the AgentLink public beta on another laptop
|
|
2
2
|
|
|
3
|
-
Use `@prplkane/agentlink@0.3.0-beta.
|
|
3
|
+
Use `@prplkane/agentlink@0.3.0-beta.3`. Node.js 22 or newer with npm is required.
|
|
4
4
|
AgentLink has no npm runtime dependencies; the agents and selected bridges have
|
|
5
5
|
their own dependencies. Do not copy profiles blindly between machines because
|
|
6
6
|
external executable paths are machine-specific.
|
|
@@ -8,14 +8,14 @@ external executable paths are machine-specific.
|
|
|
8
8
|
## Install once
|
|
9
9
|
|
|
10
10
|
~~~sh
|
|
11
|
-
npm install -g @prplkane/agentlink@0.3.0-beta.
|
|
11
|
+
npm install -g @prplkane/agentlink@0.3.0-beta.3
|
|
12
12
|
agentlink --version
|
|
13
13
|
agentlink --help
|
|
14
14
|
agentlink where
|
|
15
15
|
agentlink doctor
|
|
16
16
|
~~~
|
|
17
17
|
|
|
18
|
-
The version should be `0.3.0-beta.
|
|
18
|
+
The version should be `0.3.0-beta.3`. Installation of AgentLink alone downloads no
|
|
19
19
|
vendor bridge.
|
|
20
20
|
|
|
21
21
|
## Configure the agents you have
|
|
@@ -118,7 +118,10 @@ node scripts/test-roundtable.mjs /absolute/path/to/roundtable
|
|
|
118
118
|
|
|
119
119
|
It creates temporary profiles and managed fake bridges, verifies two discussion
|
|
120
120
|
rounds and a ready chairman verdict, updates a bridge centrally, then checks
|
|
121
|
-
cancellation and missing-usage behavior.
|
|
121
|
+
cancellation and missing-usage behavior. It also packs the current AgentLink checkout
|
|
122
|
+
and installs it offline under a temporary npm prefix. A Roundtable seat must find
|
|
123
|
+
that installation on the search path and receive its selected profile's reply.
|
|
124
|
+
On Windows this exercises the ordinary `Path` spelling with the launcher override unset.
|
|
122
125
|
The integration script is developer tooling and is not included in the npm package.
|
|
123
126
|
|
|
124
127
|
For real agents on the other laptop:
|
package/package.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prplkane/agentlink",
|
|
3
|
-
"version": "0.3.0-beta.
|
|
3
|
+
"version": "0.3.0-beta.3",
|
|
4
4
|
"type": "module",
|
|
5
|
-
"description": "
|
|
5
|
+
"description": "Connect ACP clients to agent CLIs through named profiles and centrally managed bridges.",
|
|
6
6
|
"exports": {
|
|
7
7
|
".": "./src/index.mjs",
|
|
8
8
|
"./client": "./src/client.mjs"
|
|
@@ -22,6 +22,7 @@
|
|
|
22
22
|
],
|
|
23
23
|
"scripts": {
|
|
24
24
|
"test": "node --test test/*.test.mjs",
|
|
25
|
+
"test:maturity": "node --test scripts/test-maturity.mjs",
|
|
25
26
|
"check:repo": "node scripts/check-repository.mjs"
|
|
26
27
|
},
|
|
27
28
|
"engines": {
|
package/src/cli.mjs
CHANGED
|
@@ -27,7 +27,16 @@ try {
|
|
|
27
27
|
const runtime = new AgentRuntime({ ...(gateway.home ? { home: gateway.home } : {}), signal: abort.signal });
|
|
28
28
|
const { launch, release } = await runtime.acquire(gateway.name);
|
|
29
29
|
try {
|
|
30
|
-
|
|
30
|
+
// A connection keeps its bridge lease, but new sessions can inherit a
|
|
31
|
+
// later preference edit. An explicitly removed profile keeps its last
|
|
32
|
+
// observed settings for the lifetime of this connection.
|
|
33
|
+
let defaults = launch.defaults;
|
|
34
|
+
const readDefaults = async () => {
|
|
35
|
+
try { defaults = (await runtime.get(gateway.name)).defaults; }
|
|
36
|
+
catch (cause) { if (cause.code !== 'PROFILE_NOT_FOUND') throw cause; }
|
|
37
|
+
return defaults;
|
|
38
|
+
};
|
|
39
|
+
process.exitCode = (await runGateway(launch, { readDefaults, extraArgs: gateway.extraArgs, signal: abort.signal })).exitCode;
|
|
31
40
|
} finally { await release(); }
|
|
32
41
|
} else {
|
|
33
42
|
await (await import('./management-cli.mjs')).runManagement(process.argv.slice(2), { signal: abort.signal, cliURL: import.meta.url });
|
package/src/client.mjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { version } from './version.mjs';
|
|
2
2
|
import { spawn } from 'node:child_process';
|
|
3
3
|
import { isAbsolute, join } from 'node:path';
|
|
4
|
+
import { sessionSelections } from './session-options.mjs';
|
|
4
5
|
export { providers, planProvider } from './providers.mjs';
|
|
5
6
|
|
|
6
7
|
const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
@@ -92,7 +93,7 @@ export class AcpClient {
|
|
|
92
93
|
finally { this.#setupMethod = undefined; }
|
|
93
94
|
}
|
|
94
95
|
|
|
95
|
-
async newSession(options) {
|
|
96
|
+
async newSession(options, defaults) {
|
|
96
97
|
if (!this.#initialized || this.#sessionId || this.#setupMethod) throw fault('INVALID_STATE', 'Initialize before creating one session.');
|
|
97
98
|
this.#setupMethod = 'session/new';
|
|
98
99
|
let result;
|
|
@@ -102,6 +103,15 @@ export class AcpClient {
|
|
|
102
103
|
const error = fault('PROTOCOL_ERROR', 'Missing session ID.'); this.#fail(error); throw error;
|
|
103
104
|
}
|
|
104
105
|
this.#sessionId = result.sessionId;
|
|
106
|
+
if (defaults) {
|
|
107
|
+
const selections = sessionSelections(result.configOptions, defaults);
|
|
108
|
+
let step = selections.next();
|
|
109
|
+
while (!step.done) {
|
|
110
|
+
const reply = await this.#request('session/set_config_option', { sessionId: this.#sessionId, ...step.value }, options);
|
|
111
|
+
step = selections.next(reply?.configOptions);
|
|
112
|
+
}
|
|
113
|
+
result.configOptions = step.value;
|
|
114
|
+
}
|
|
105
115
|
return result;
|
|
106
116
|
}
|
|
107
117
|
|
package/src/gateway.mjs
CHANGED
|
@@ -9,7 +9,7 @@ import { authMarker, terminalAuthReply } from './terminal-auth.mjs';
|
|
|
9
9
|
// No initialize, session/new, task, approval, download or discovery is injected.
|
|
10
10
|
export async function runGateway(launch, { cwd = process.cwd(), env = process.env,
|
|
11
11
|
input = process.stdin, output = process.stdout, diagnostics = process.stderr,
|
|
12
|
-
signal, extraArgs = [], interactive = Boolean(process.stdin.isTTY),
|
|
12
|
+
signal, readDefaults, extraArgs = [], interactive = Boolean(process.stdin.isTTY),
|
|
13
13
|
maxMessageBytes = 16 * 1024 * 1024, shutdownGraceMs = 750 } = {}) {
|
|
14
14
|
if (!strings(extraArgs) || !Number.isSafeInteger(shutdownGraceMs) || shutdownGraceMs < 1) {
|
|
15
15
|
throw new TypeError('Invalid gateway arguments.');
|
|
@@ -43,8 +43,19 @@ export async function runGateway(launch, { cwd = process.cwd(), env = process.en
|
|
|
43
43
|
let inputPump = Promise.resolve();
|
|
44
44
|
let outputFrames;
|
|
45
45
|
if (!terminal) {
|
|
46
|
+
let defaultsRelay, protocolVersion;
|
|
47
|
+
async function prepareSession(message, source) {
|
|
48
|
+
const defaults = readDefaults ? await readDefaults() : launch.defaults;
|
|
49
|
+
if (!defaults || !Object.keys(defaults).length) return;
|
|
50
|
+
if (!defaultsRelay) {
|
|
51
|
+
const { SessionDefaults } = await import('./session-defaults.mjs');
|
|
52
|
+
defaultsRelay = new SessionDefaults(frame => child.stdin.write(frame), maxMessageBytes);
|
|
53
|
+
}
|
|
54
|
+
defaultsRelay.expectSession(message, source, defaults, protocolVersion);
|
|
55
|
+
}
|
|
46
56
|
const initializeIds = new Set();
|
|
47
|
-
inputPump = pipeline(input, new AcpFrames({ maxMessageBytes, onMessage(message) {
|
|
57
|
+
inputPump = pipeline(input, new AcpFrames({ maxMessageBytes, onMessage(message, source) {
|
|
58
|
+
if (message.method === 'session/new' && Object.hasOwn(message, 'id')) return prepareSession(message, source);
|
|
48
59
|
if (message.method === 'initialize' && Object.hasOwn(message, 'id')) initializeIds.add(message.id);
|
|
49
60
|
} }), child.stdin, { signal: pumps.signal }).then(() => {
|
|
50
61
|
if (!closing) inputTimer = setTimeout(() => { void stop(); }, shutdownGraceMs);
|
|
@@ -57,7 +68,9 @@ export async function runGateway(launch, { cwd = process.cwd(), env = process.en
|
|
|
57
68
|
} else fail(cause);
|
|
58
69
|
});
|
|
59
70
|
outputFrames = new AcpFrames({ maxMessageBytes, mapMessage(message, source) {
|
|
60
|
-
if (message.method || !initializeIds.delete(message.id)
|
|
71
|
+
if (message.method || !initializeIds.delete(message.id)) return defaultsRelay?.agentMessage(message, source);
|
|
72
|
+
protocolVersion = message.result?.protocolVersion;
|
|
73
|
+
if (!Array.isArray(message.result?.authMethods)) return;
|
|
61
74
|
// The client relaunches AgentLink, not the underlying executable. A marker
|
|
62
75
|
// identifies terminal auth even when the upstream method has only env.
|
|
63
76
|
return terminalAuthReply(message, source);
|
package/src/index.mjs
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { join } from 'node:path';
|
|
2
2
|
import { AcpClient } from './client.mjs';
|
|
3
3
|
import { discoverAgent, validateDiscoveryOptions, inProbeDirectory, verifyAgent } from './discovery.mjs';
|
|
4
|
-
import { profileName, error } from './profiles.mjs';
|
|
4
|
+
import { profileName, error, validateDefaults } from './profiles.mjs';
|
|
5
|
+
import { probeAcp } from './probe.mjs';
|
|
5
6
|
import { AgentRuntime } from './runtime.mjs';
|
|
6
7
|
import { BridgeStore, environment, manifestSpec } from './bridges.mjs';
|
|
7
8
|
import { withLock } from './storage.mjs';
|
|
@@ -22,6 +23,36 @@ export class AgentLink extends AgentRuntime {
|
|
|
22
23
|
remove(name) { return this.mutate(() => this.store.remove(name)); }
|
|
23
24
|
inspect(options) { return discoverAgent(options); } // Never installs or saves.
|
|
24
25
|
|
|
26
|
+
async models(name, { model, timeoutMs = 15000, signal = this.signal } = {}) {
|
|
27
|
+
const defaults = validateDefaults(model === undefined ? {} : { model });
|
|
28
|
+
const { launch, release } = await this.acquire(name);
|
|
29
|
+
try {
|
|
30
|
+
const options = await inProbeDirectory(cwd => probeAcp(launch, { cwd, defaults, timeoutMs, signal }));
|
|
31
|
+
return { name, defaults: launch.defaults ?? {}, ...options };
|
|
32
|
+
} finally { await release(); }
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
async setDefaults(name, changes, { timeoutMs = 15000, signal = this.signal } = {}) {
|
|
36
|
+
return this.mutate(async () => {
|
|
37
|
+
const profile = await this.get(name);
|
|
38
|
+
const defaults = { ...profile.defaults };
|
|
39
|
+
for (const [key, value] of Object.entries(changes)) {
|
|
40
|
+
if (!['model', 'effort'].includes(key)) throw new TypeError('Unknown session default.');
|
|
41
|
+
if (value === null) delete defaults[key];
|
|
42
|
+
else defaults[key] = value;
|
|
43
|
+
}
|
|
44
|
+
validateDefaults(defaults);
|
|
45
|
+
if (Object.keys(defaults).length) {
|
|
46
|
+
const launch = await this.resolveProfile(profile);
|
|
47
|
+
await inProbeDirectory(cwd => probeAcp(launch, { cwd, defaults, timeoutMs, signal }));
|
|
48
|
+
}
|
|
49
|
+
profile.defaults = defaults;
|
|
50
|
+
if (!Object.keys(defaults).length) delete profile.defaults;
|
|
51
|
+
await this.store.save({ ...profile, updatedAt: new Date().toISOString() }, { replace: true });
|
|
52
|
+
return { name, defaults };
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
|
|
25
56
|
async installBridge(id, spec, options = {}) {
|
|
26
57
|
return this.mutate(() => this.installBridgeUnlocked(id, spec, options));
|
|
27
58
|
}
|
|
@@ -222,7 +253,7 @@ export class AgentLink extends AgentRuntime {
|
|
|
222
253
|
client.close = async () => { try { await close(); } finally { await release(); } };
|
|
223
254
|
await client.initialize({ timeoutMs });
|
|
224
255
|
if (authMethodId !== undefined) await client.authenticate(authMethodId, { timeoutMs });
|
|
225
|
-
await client.newSession({ timeoutMs });
|
|
256
|
+
await client.newSession({ timeoutMs }, launch.defaults);
|
|
226
257
|
return client;
|
|
227
258
|
} catch (cause) { if (client) await client.close(); else await release(); throw cause; }
|
|
228
259
|
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// The wire layer has already validated JSON. Locate spans instead of
|
|
2
|
+
// reserializing the response: JSON.parse/stringify would round large numeric
|
|
3
|
+
// IDs and opaque extension values. Nesting is scanned iteratively.
|
|
4
|
+
export const whitespace = (text, at) => { while (/\s/.test(text[at] || '') && at < text.length) at++; return at; };
|
|
5
|
+
export function valueEnd(text, start) {
|
|
6
|
+
let depth = 0, quoted = false;
|
|
7
|
+
for (let at = start; at < text.length; at++) {
|
|
8
|
+
const char = text[at];
|
|
9
|
+
if (quoted) {
|
|
10
|
+
if (char === '\\') at++;
|
|
11
|
+
else if (char === '"') { quoted = false; if (!depth) return at + 1; }
|
|
12
|
+
} else if (char === '"') quoted = true;
|
|
13
|
+
else if (char === '{' || char === '[') depth++;
|
|
14
|
+
else if (char === '}' || char === ']') { if (!depth) return at; if (!--depth) return at + 1; }
|
|
15
|
+
else if (!depth && (char === ',' || /\s/.test(char))) return at;
|
|
16
|
+
}
|
|
17
|
+
return text.length;
|
|
18
|
+
}
|
|
19
|
+
export function member(text, start, name) {
|
|
20
|
+
if (text[start] !== '{') return;
|
|
21
|
+
let found, at = whitespace(text, start + 1);
|
|
22
|
+
while (text[at] !== '}') {
|
|
23
|
+
const end = valueEnd(text, at), key = JSON.parse(text.slice(at, end));
|
|
24
|
+
const value = whitespace(text, whitespace(text, end) + 1);
|
|
25
|
+
const finish = valueEnd(text, value);
|
|
26
|
+
if (key === name) found = [value, finish]; // JSON's last duplicate key wins.
|
|
27
|
+
at = whitespace(text, finish);
|
|
28
|
+
if (text[at] === ',') at = whitespace(text, at + 1);
|
|
29
|
+
}
|
|
30
|
+
return found;
|
|
31
|
+
}
|
package/src/management-cli.mjs
CHANGED
|
@@ -13,6 +13,8 @@ const usage = 'AgentLink — shared ACP connections and centrally managed bridge
|
|
|
13
13
|
' agentlink inspect --command <installed-cli>\n' +
|
|
14
14
|
' agentlink update <profile> [launch options]\n' +
|
|
15
15
|
' agentlink refresh <profile> | check <profile>\n' +
|
|
16
|
+
' agentlink models <profile> [--model ID] Inspect live model and effort choices\n' +
|
|
17
|
+
' agentlink defaults <profile> [--model ID | --clear-model] [--effort ID | --clear-effort]\n' +
|
|
16
18
|
' agentlink doctor Read-only local health checks\n' +
|
|
17
19
|
' agentlink list | show <profile> | config <profile> | remove <profile> | providers | where\n\n' +
|
|
18
20
|
' agentlink bridge install <id> --package <npm-package> [--version <version-or-tag>]\n' +
|
|
@@ -66,6 +68,7 @@ export async function runManagement(argv, { signal, cliURL } = {}) {
|
|
|
66
68
|
kind: { type: 'string' }, manifest: { type: 'string' }, distribution: { type: 'string' },
|
|
67
69
|
offline: { type: 'boolean' }, cache: { type: 'boolean' }, 'install-timeout': { type: 'string' },
|
|
68
70
|
timeout: { type: 'string' }, home: { type: 'string' }, json: { type: 'boolean' },
|
|
71
|
+
model: { type: 'string' }, effort: { type: 'string' }, 'clear-model': { type: 'boolean' }, 'clear-effort': { type: 'boolean' },
|
|
69
72
|
help: { type: 'boolean', short: 'h' }
|
|
70
73
|
} });
|
|
71
74
|
json = Boolean(v.json);
|
|
@@ -79,6 +82,7 @@ export async function runManagement(argv, { signal, cliURL } = {}) {
|
|
|
79
82
|
add: [...launchFlags, ...installFlags], update: [...launchFlags, ...installFlags],
|
|
80
83
|
inspect: ['command', 'provider', 'prefix-args', 'acp-args', 'help-args', 'skip-check'],
|
|
81
84
|
refresh: [], check: [], list: [], show: [], config: [], remove: [], providers: [], where: [], doctor: [],
|
|
85
|
+
models: ['model'], defaults: ['model', 'effort', 'clear-model', 'clear-effort'],
|
|
82
86
|
bridge: [...installFlags, 'acp-args', 'env', 'cache']
|
|
83
87
|
};
|
|
84
88
|
if (!Object.hasOwn(allowed, action)) throw new TypeError('Unknown command. Run agentlink --help.');
|
|
@@ -123,7 +127,7 @@ export async function runManagement(argv, { signal, cliURL } = {}) {
|
|
|
123
127
|
else if (operation === 'prune') result = await manager.pruneBridges({ cache: Boolean(v.cache) });
|
|
124
128
|
else { await manager.removeBridge(id); result = { removed: id, note: 'Unused files can be removed with bridge prune.' }; }
|
|
125
129
|
} else {
|
|
126
|
-
const named = ['add', 'update', 'refresh', 'check', 'show', 'config', 'remove'].includes(action);
|
|
130
|
+
const named = ['add', 'update', 'refresh', 'check', 'show', 'config', 'remove', 'models', 'defaults'].includes(action);
|
|
127
131
|
if (second !== undefined || rest.length || (named ? !first : first !== undefined)) throw new TypeError('Invalid arguments for ' + action + '.');
|
|
128
132
|
switch (action) {
|
|
129
133
|
case 'add': result = await manager.add(first, options); break;
|
|
@@ -131,6 +135,18 @@ export async function runManagement(argv, { signal, cliURL } = {}) {
|
|
|
131
135
|
case 'inspect': result = await manager.inspect(options); break;
|
|
132
136
|
case 'refresh': result = await manager.refresh(first, options); break;
|
|
133
137
|
case 'check': result = { name: first, verification: await manager.check(first, options) }; break;
|
|
138
|
+
case 'models': result = await manager.models(first, { ...options, model: v.model }); break;
|
|
139
|
+
case 'defaults': {
|
|
140
|
+
const changes = {};
|
|
141
|
+
for (const key of ['model', 'effort']) {
|
|
142
|
+
if (v['clear-' + key] && v[key] !== undefined) throw new TypeError('Choose --' + key + ' or --clear-' + key + '.');
|
|
143
|
+
if (v['clear-' + key]) changes[key] = null;
|
|
144
|
+
else if (v[key] !== undefined) changes[key] = v[key];
|
|
145
|
+
}
|
|
146
|
+
result = Object.keys(changes).length ? await manager.setDefaults(first, changes, options)
|
|
147
|
+
: { name: first, defaults: (await manager.get(first)).defaults ?? {} };
|
|
148
|
+
break;
|
|
149
|
+
}
|
|
134
150
|
case 'show': {
|
|
135
151
|
const profile = await manager.get(first);
|
|
136
152
|
result = { ...profile, resolvedLaunch: await manager.resolveProfile(profile) }; break;
|
|
@@ -146,7 +162,7 @@ export async function runManagement(argv, { signal, cliURL } = {}) {
|
|
|
146
162
|
case 'doctor': result = await doctor(manager); if (!result.ok) process.exitCode = 1; break;
|
|
147
163
|
}
|
|
148
164
|
}
|
|
149
|
-
if (json || action === 'bridge' || ['show', 'config', 'inspect', 'providers'].includes(action)) process.stdout.write(JSON.stringify(result, null, 2) + '\n');
|
|
165
|
+
if (json || action === 'bridge' || ['show', 'config', 'inspect', 'providers', 'models', 'defaults'].includes(action)) process.stdout.write(JSON.stringify(result, null, 2) + '\n');
|
|
150
166
|
else if (action === 'list') process.stdout.write(result.length ? result.map(profile =>
|
|
151
167
|
profile.name + '\t' + (profile.error ? profile.error.message : profile.verification.status + '\t' +
|
|
152
168
|
(profile.bridge ? 'managed:' + profile.bridge.id : profile.command))).join('\n') + '\n' : 'No saved profiles.\n');
|
package/src/probe.mjs
CHANGED
|
@@ -3,10 +3,11 @@ import { spawn } from 'node:child_process';
|
|
|
3
3
|
import { AcpFrames } from './wire.mjs';
|
|
4
4
|
import { stopProcess } from './process.mjs';
|
|
5
5
|
import { error } from './profiles.mjs';
|
|
6
|
+
import { describeOptions, sessionSelections } from './session-options.mjs';
|
|
6
7
|
|
|
7
|
-
//
|
|
8
|
-
//
|
|
9
|
-
export async function probeAcp(launch, { cwd, env = process.env, timeoutMs = 3000, signal } = {}) {
|
|
8
|
+
// Discovery stops after initialize. Explicit option inspection continues into
|
|
9
|
+
// one disposable session and never sends a prompt.
|
|
10
|
+
export async function probeAcp(launch, { cwd, env = process.env, defaults, timeoutMs = 3000, signal } = {}) {
|
|
10
11
|
signal?.throwIfAborted();
|
|
11
12
|
const child = spawn(launch.command, [...launch.prefixArgs, ...launch.acpArgs], {
|
|
12
13
|
cwd, env: { ...env, ...launch.env }, shell: false, windowsHide: true,
|
|
@@ -15,18 +16,41 @@ export async function probeAcp(launch, { cwd, env = process.env, timeoutMs = 300
|
|
|
15
16
|
let timer, abort;
|
|
16
17
|
try {
|
|
17
18
|
return await new Promise((resolve, reject) => {
|
|
18
|
-
|
|
19
|
-
|
|
19
|
+
let pending, sessionId, selections, protocolVersion, sequence = 0;
|
|
20
|
+
const request = (method, params) => {
|
|
21
|
+
pending = method;
|
|
22
|
+
child.stdin.write(JSON.stringify({ jsonrpc: '2.0', id: ++sequence, method, params }) + '\n');
|
|
23
|
+
};
|
|
24
|
+
timer = setTimeout(() => reject(defaults ? error('OPTIONS_TIMEOUT', 'ACP option inspection timed out.') :
|
|
25
|
+
error('INITIALIZE_TIMEOUT', 'ACP initialization timed out.')), timeoutMs);
|
|
26
|
+
abort = () => reject(error('CANCELLED', 'ACP probe cancelled.'));
|
|
20
27
|
signal?.addEventListener('abort', abort, { once: true });
|
|
21
28
|
const frames = new AcpFrames({ maxMessageBytes: 1024 * 1024, onMessage(message) {
|
|
22
|
-
if (message.
|
|
29
|
+
if (message.method) {
|
|
30
|
+
if (defaults && Object.hasOwn(message, 'id')) child.stdin.write(JSON.stringify({ jsonrpc: '2.0', id: message.id,
|
|
31
|
+
error: { code: -32601, message: 'Client operations are unavailable during option inspection.' } }) + '\n');
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
if (message.id !== sequence) return;
|
|
23
35
|
if (message.error) {
|
|
24
|
-
reject(Object.assign(error('
|
|
36
|
+
reject(Object.assign(error(pending === 'initialize' ? 'INITIALIZE_REJECTED' : 'OPTIONS_REJECTED',
|
|
37
|
+
message.error.message || 'Agent rejected ' + pending + '.'), {
|
|
25
38
|
remoteCode: message.error.code
|
|
26
39
|
}));
|
|
27
40
|
return;
|
|
28
41
|
}
|
|
29
42
|
const value = message.result;
|
|
43
|
+
if (pending !== 'initialize') {
|
|
44
|
+
if (pending === 'session/new') {
|
|
45
|
+
sessionId = value?.sessionId;
|
|
46
|
+
if (typeof sessionId !== 'string' || !sessionId) throw error('PROTOCOL_ERROR', 'Agent did not return a session ID.');
|
|
47
|
+
selections = sessionSelections(value.configOptions, defaults, protocolVersion);
|
|
48
|
+
}
|
|
49
|
+
const next = selections.next(value?.configOptions);
|
|
50
|
+
if (next.done) resolve(describeOptions(next.value));
|
|
51
|
+
else request('session/set_config_option', { sessionId, ...next.value });
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
30
54
|
const capabilities = value?.protocolVersion === 2 ? value.capabilities : value?.agentCapabilities;
|
|
31
55
|
const info = value?.protocolVersion === 2 ? value.info : value?.agentInfo;
|
|
32
56
|
if (!value || ![1, 2].includes(value.protocolVersion) || !capabilities ||
|
|
@@ -38,6 +62,10 @@ export async function probeAcp(launch, { cwd, env = process.env, timeoutMs = 300
|
|
|
38
62
|
for (const field of ['name', 'version', 'title']) {
|
|
39
63
|
if (typeof info?.[field] === 'string') agentInfo[field] = info[field].slice(0, 256);
|
|
40
64
|
}
|
|
65
|
+
if (defaults) {
|
|
66
|
+
protocolVersion = value.protocolVersion;
|
|
67
|
+
return request('session/new', { cwd, mcpServers: [] });
|
|
68
|
+
}
|
|
41
69
|
resolve({ status: 'initialize-passed', checkedAt: new Date().toISOString(),
|
|
42
70
|
protocolVersion: value.protocolVersion, agentInfo, capabilities,
|
|
43
71
|
authMethods: Array.isArray(value.authMethods) ? value.authMethods : [] });
|
|
@@ -49,9 +77,8 @@ export async function probeAcp(launch, { cwd, env = process.env, timeoutMs = 300
|
|
|
49
77
|
child.stdout.on('error', reject);
|
|
50
78
|
child.stdin.on('error', cause => { if (cause.code !== 'EPIPE') reject(cause); });
|
|
51
79
|
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
|
|
53
|
-
|
|
54
|
-
params: { protocolVersion: 2, capabilities: {}, info: { name: 'agentlink-discovery', version } } }) + '\n');
|
|
80
|
+
child.once('exit', code => reject(error('PROCESS_EXIT', 'Agent exited during the ACP probe (' + code + ').')));
|
|
81
|
+
request('initialize', { protocolVersion: 2, capabilities: {}, info: { name: 'agentlink-discovery', version } });
|
|
55
82
|
});
|
|
56
83
|
} finally { clearTimeout(timer); signal?.removeEventListener('abort', abort); await stopProcess(child); }
|
|
57
84
|
}
|
package/src/profiles.mjs
CHANGED
|
@@ -1,12 +1,21 @@
|
|
|
1
1
|
import { homedir } from 'node:os';
|
|
2
2
|
import { isAbsolute, join, resolve } from 'node:path';
|
|
3
|
-
import { link, mkdir, open, readdir, readFile,
|
|
3
|
+
import { link, mkdir, open, readdir, readFile, stat, unlink } from 'node:fs/promises';
|
|
4
4
|
import { randomUUID } from 'node:crypto';
|
|
5
|
+
import { replaceFile } from './replace-file.mjs';
|
|
5
6
|
|
|
6
7
|
export const error = (code, message) => Object.assign(new Error(message), { code });
|
|
7
8
|
export const strings = value => Array.isArray(value) && value.every(item => typeof item === 'string' && !item.includes('\0'));
|
|
8
9
|
const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
9
10
|
|
|
11
|
+
export function validateDefaults(value) {
|
|
12
|
+
if (!object(value) || Object.entries(value).some(([key, id]) =>
|
|
13
|
+
!['model', 'effort'].includes(key) || typeof id !== 'string' || !id.length || /[\u0000-\u001f\u007f]/.test(id))) {
|
|
14
|
+
throw error('INVALID_PROFILE', 'Session defaults must contain model or effort IDs as nonempty strings without control characters.');
|
|
15
|
+
}
|
|
16
|
+
return value;
|
|
17
|
+
}
|
|
18
|
+
|
|
10
19
|
export function profileName(name) {
|
|
11
20
|
if (typeof name !== 'string' || !/^[a-z0-9][a-z0-9_-]{0,63}$/.test(name) ||
|
|
12
21
|
/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/.test(name)) {
|
|
@@ -29,6 +38,7 @@ export function validateProfile(profile) {
|
|
|
29
38
|
if (!object(profile.bridge) || typeof profile.bridge.useDefaultArgs !== 'boolean') throw error('INVALID_PROFILE', 'Invalid managed bridge reference.');
|
|
30
39
|
profileName(profile.bridge.id);
|
|
31
40
|
}
|
|
41
|
+
if (profile.defaults !== undefined) validateDefaults(profile.defaults);
|
|
32
42
|
if (profile.env !== undefined && (!object(profile.env) || Object.entries(profile.env).some(([key, value]) =>
|
|
33
43
|
!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key) || typeof value !== 'string' || value.includes('\0')))) {
|
|
34
44
|
throw error('INVALID_PROFILE', 'Invalid launch environment.');
|
|
@@ -88,7 +98,7 @@ export class ProfileStore {
|
|
|
88
98
|
finally { await handle.close(); }
|
|
89
99
|
// A hard link publishes a complete new file without overwriting another user's
|
|
90
100
|
// concurrent add. Updates use rename so readers see the old or the new JSON.
|
|
91
|
-
if (replace) await
|
|
101
|
+
if (replace) await replaceFile(temporary, destination);
|
|
92
102
|
else await link(temporary, destination);
|
|
93
103
|
} catch (cause) {
|
|
94
104
|
if (cause.code === 'EEXIST') throw error('PROFILE_EXISTS', `Profile "${profile.name}" already exists. Use update or refresh.`);
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { rename } from 'node:fs/promises';
|
|
2
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
3
|
+
|
|
4
|
+
// Windows may deny opening or replacing a name while another handle is closing.
|
|
5
|
+
// Preserve the operation's original error if access remains denied.
|
|
6
|
+
export async function retryWindowsSharing(operation, deadline = Infinity, signal) {
|
|
7
|
+
for (let attempt = 0; ; attempt++) {
|
|
8
|
+
signal?.throwIfAborted();
|
|
9
|
+
try { return await operation(); }
|
|
10
|
+
catch (cause) {
|
|
11
|
+
const remaining = deadline - Date.now();
|
|
12
|
+
if (process.platform !== 'win32' || remaining <= 0 || attempt === 5 || !['EACCES', 'EPERM', 'EBUSY'].includes(cause.code)) throw cause;
|
|
13
|
+
await delay(Math.min(remaining, 50 * (attempt + 1)), undefined, { signal });
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function replaceFile(source, destination) {
|
|
19
|
+
return retryWindowsSharing(() => rename(source, destination));
|
|
20
|
+
}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { member, whitespace } from './json-spans.mjs';
|
|
2
|
+
import { error } from './profiles.mjs';
|
|
3
|
+
import { sessionSelections } from './session-options.mjs';
|
|
4
|
+
|
|
5
|
+
function field(source, name) {
|
|
6
|
+
return member(source, whitespace(source, 0), name);
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
function requestKey(id, source) {
|
|
10
|
+
if (typeof id === 'number' && !Number.isSafeInteger(id)) return 'number:' + source.slice(...field(source, 'id'));
|
|
11
|
+
return JSON.stringify(id);
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function optionsSpan(source) {
|
|
15
|
+
return member(source, field(source, 'result')[0], 'configOptions');
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// An upstream session/new is complete before we reuse its request ID for a
|
|
19
|
+
// setter. The downstream request stays outstanding until all setters finish.
|
|
20
|
+
export class SessionDefaults {
|
|
21
|
+
constructor(send, limit) {
|
|
22
|
+
this.send = send;
|
|
23
|
+
this.limit = limit;
|
|
24
|
+
this.requests = new Map();
|
|
25
|
+
this.configuring = new Map();
|
|
26
|
+
this.heldBytes = 0;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
expectSession(message, source, defaults, protocolVersion) {
|
|
30
|
+
if (this.requests.size >= 256) throw error('MESSAGE_LIMIT', 'Too many pending session creations.');
|
|
31
|
+
this.requests.set(requestKey(message.id, source), { defaults, protocolVersion, bytes: 0 });
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
hold(state, source) {
|
|
35
|
+
const bytes = Buffer.byteLength(source) + 1;
|
|
36
|
+
if (this.heldBytes + bytes > 4 * this.limit) throw error('MESSAGE_LIMIT', 'Pending session setup exceeds the gateway buffer limit.');
|
|
37
|
+
this.heldBytes += bytes;
|
|
38
|
+
state.bytes += bytes;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
finish(key, state) {
|
|
42
|
+
this.requests.delete(key);
|
|
43
|
+
this.configuring.delete(state.sessionId);
|
|
44
|
+
this.heldBytes -= state.bytes;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
agentMessage(message, source) {
|
|
48
|
+
if (message.method) {
|
|
49
|
+
const state = this.configuring.get(message.params?.sessionId);
|
|
50
|
+
if (state && message.method === 'session/update' && !Object.hasOwn(message, 'id')) {
|
|
51
|
+
// Setter responses contain the complete, newer configuration. Other
|
|
52
|
+
// updates must follow the reply that introduces this session ID.
|
|
53
|
+
if (message.params.update?.sessionUpdate !== 'config_option_update') {
|
|
54
|
+
this.hold(state, source);
|
|
55
|
+
state.updates.push(source);
|
|
56
|
+
}
|
|
57
|
+
return null;
|
|
58
|
+
}
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
if (!this.requests.size) return;
|
|
62
|
+
const key = requestKey(message.id, source);
|
|
63
|
+
const state = this.requests.get(key);
|
|
64
|
+
if (!state) return;
|
|
65
|
+
const first = !state.selections;
|
|
66
|
+
if (message.error) {
|
|
67
|
+
this.finish(key, state);
|
|
68
|
+
return; // The upstream error already carries the original caller's ID.
|
|
69
|
+
}
|
|
70
|
+
if (first) {
|
|
71
|
+
if (typeof message.result?.sessionId !== 'string' || !message.result.sessionId) {
|
|
72
|
+
throw error('PROTOCOL_ERROR', 'Cannot apply profile defaults without a session ID.');
|
|
73
|
+
}
|
|
74
|
+
state.sessionId = message.result.sessionId;
|
|
75
|
+
state.source = source;
|
|
76
|
+
state.id = source.slice(...field(source, 'id'));
|
|
77
|
+
state.selections = sessionSelections(message.result.configOptions, state.defaults, state.protocolVersion);
|
|
78
|
+
state.updates = [];
|
|
79
|
+
}
|
|
80
|
+
let next;
|
|
81
|
+
try { next = state.selections.next(message.result?.configOptions); }
|
|
82
|
+
catch (cause) {
|
|
83
|
+
this.finish(key, state);
|
|
84
|
+
return Buffer.from('{"jsonrpc":"2.0","id":' + state.id + ',"error":' +
|
|
85
|
+
JSON.stringify({ code: -32602, message: cause.message, data: { code: cause.code } }) + '}');
|
|
86
|
+
}
|
|
87
|
+
if (next.done) {
|
|
88
|
+
this.finish(key, state);
|
|
89
|
+
if (first) return; // Both choices already match. Preserve the original bytes.
|
|
90
|
+
const [start, end] = optionsSpan(state.source);
|
|
91
|
+
const options = source.slice(...optionsSpan(source));
|
|
92
|
+
const reply = state.source.slice(0, start) + options + state.source.slice(end);
|
|
93
|
+
if (Buffer.byteLength(reply) > this.limit) throw error('MESSAGE_LIMIT', 'Configured session reply exceeds the frame limit.');
|
|
94
|
+
return Buffer.from([reply, ...state.updates].join('\n'));
|
|
95
|
+
}
|
|
96
|
+
if (first) {
|
|
97
|
+
this.hold(state, source);
|
|
98
|
+
this.configuring.set(state.sessionId, state);
|
|
99
|
+
}
|
|
100
|
+
const frame = '{"jsonrpc":"2.0","id":' + state.id + ',"method":"session/set_config_option","params":' +
|
|
101
|
+
JSON.stringify({ sessionId: state.sessionId, ...next.value }) + '}';
|
|
102
|
+
if (Buffer.byteLength(frame) > this.limit) throw error('MESSAGE_LIMIT', 'Profile selection exceeds the frame limit.');
|
|
103
|
+
this.send(frame + '\n');
|
|
104
|
+
return null;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { error } from './profiles.mjs';
|
|
2
|
+
|
|
3
|
+
const selectors = {
|
|
4
|
+
model: { category: 'model', ids: ['model'] },
|
|
5
|
+
effort: { category: 'thought_level', ids: ['thought_level', 'reasoning_effort', 'effort', 'reasoning'] }
|
|
6
|
+
};
|
|
7
|
+
|
|
8
|
+
function selectOption(options, setting) {
|
|
9
|
+
if (!Array.isArray(options)) return null;
|
|
10
|
+
const { category, ids } = selectors[setting];
|
|
11
|
+
const selects = options.filter(option => option?.type === 'select' && typeof (option.configId ?? option.id) === 'string');
|
|
12
|
+
return selects.find(option => option.category === category)
|
|
13
|
+
?? selects.find(option => !option.category && ids.includes(option.configId ?? option.id));
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function choices(option) {
|
|
17
|
+
if (!Array.isArray(option?.options)) return [];
|
|
18
|
+
return option.options.flatMap(row => Array.isArray(row?.options) ? row.options : [row])
|
|
19
|
+
.filter(row => typeof row?.value === 'string');
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function describeOptions(options) {
|
|
23
|
+
const result = {};
|
|
24
|
+
for (const setting of Object.keys(selectors)) {
|
|
25
|
+
const option = selectOption(options, setting);
|
|
26
|
+
result[setting] = option ? {
|
|
27
|
+
current: option.currentValue,
|
|
28
|
+
choices: choices(option).map(row => ({ id: row.value, name: typeof row.name === 'string' ? row.name : row.value }))
|
|
29
|
+
} : null;
|
|
30
|
+
}
|
|
31
|
+
return result;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// Each set response supplies the complete option list, including the effort
|
|
35
|
+
// levels for the newly selected model. Both the gateway and inspector use it.
|
|
36
|
+
export function* sessionSelections(options, defaults, protocolVersion = 1) {
|
|
37
|
+
for (const setting of Object.keys(selectors)) {
|
|
38
|
+
const value = defaults[setting];
|
|
39
|
+
if (value === undefined) continue;
|
|
40
|
+
const option = selectOption(options, setting);
|
|
41
|
+
const available = choices(option);
|
|
42
|
+
if (!available.some(row => row.value === value)) {
|
|
43
|
+
const examples = available.slice(0, 6).map(row => JSON.stringify(row.value.slice(0, 100))).join(', ');
|
|
44
|
+
throw error('OPTION_UNAVAILABLE', 'The bridge does not offer ' + setting + ' ' + JSON.stringify(value) +
|
|
45
|
+
(examples ? '. Available choices include ' + examples : '. No choices advertised') +
|
|
46
|
+
'. Run agentlink models PROFILE to inspect and agentlink defaults PROFILE to change the selection.');
|
|
47
|
+
}
|
|
48
|
+
if (option.currentValue !== value) {
|
|
49
|
+
options = yield { configId: option.configId ?? option.id, ...(protocolVersion === 2 ? { type: 'id' } : {}), value };
|
|
50
|
+
if (selectOption(options, setting)?.currentValue !== value) throw unconfirmed(setting, value);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
for (const [setting, value] of Object.entries(defaults)) {
|
|
54
|
+
if (selectOption(options, setting)?.currentValue !== value) {
|
|
55
|
+
throw unconfirmed(setting, value);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return options;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function unconfirmed(setting, value) {
|
|
62
|
+
return error('OPTION_UNCONFIRMED', 'The bridge did not confirm the selected ' + setting + ' ' + JSON.stringify(value) + '.');
|
|
63
|
+
}
|
package/src/storage.mjs
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import { mkdir, open, readFile,
|
|
1
|
+
import { mkdir, open, readFile, stat, unlink } from 'node:fs/promises';
|
|
2
2
|
import { dirname, isAbsolute, relative, resolve, sep } from 'node:path';
|
|
3
3
|
import { randomUUID } from 'node:crypto';
|
|
4
4
|
import { error } from './profiles.mjs';
|
|
5
|
+
import { replaceFile, retryWindowsSharing } from './replace-file.mjs';
|
|
5
6
|
|
|
6
7
|
export function inside(root, path) {
|
|
7
8
|
const target = resolve(root, path);
|
|
@@ -27,7 +28,7 @@ export async function writeJson(path, value, { durable = true } = {}) {
|
|
|
27
28
|
if (durable) await handle.sync();
|
|
28
29
|
}
|
|
29
30
|
finally { await handle.close(); }
|
|
30
|
-
await
|
|
31
|
+
await replaceFile(temporary, path);
|
|
31
32
|
} finally { await unlink(temporary).catch(cause => { if (cause.code !== 'ENOENT') throw cause; }); }
|
|
32
33
|
}
|
|
33
34
|
|
|
@@ -37,7 +38,7 @@ export async function withLock(path, callback, timeoutMs = 180000, signal) {
|
|
|
37
38
|
let handle;
|
|
38
39
|
while (!handle) {
|
|
39
40
|
signal?.throwIfAborted();
|
|
40
|
-
try { handle = await open(path, 'wx', 0o600); }
|
|
41
|
+
try { handle = await retryWindowsSharing(() => open(path, 'wx', 0o600), deadline, signal); }
|
|
41
42
|
catch (cause) {
|
|
42
43
|
if (cause.code !== 'EEXIST') throw cause;
|
|
43
44
|
try {
|
|
@@ -58,5 +59,5 @@ export async function withLock(path, callback, timeoutMs = 180000, signal) {
|
|
|
58
59
|
await handle.writeFile(JSON.stringify({ pid: process.pid, createdAt: new Date().toISOString() }));
|
|
59
60
|
signal?.throwIfAborted();
|
|
60
61
|
return await callback();
|
|
61
|
-
} finally { await handle.close(); await unlink(path); }
|
|
62
|
+
} finally { await handle.close(); await retryWindowsSharing(() => unlink(path)); }
|
|
62
63
|
}
|
package/src/terminal-auth.mjs
CHANGED
|
@@ -1,39 +1,8 @@
|
|
|
1
|
+
import { member, valueEnd, whitespace } from './json-spans.mjs';
|
|
1
2
|
import { strings } from './profiles.mjs';
|
|
2
3
|
|
|
3
4
|
export const authMarker = '--agentlink-terminal-auth';
|
|
4
5
|
|
|
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
6
|
export function terminalAuthReply(message, source) {
|
|
38
7
|
const methods = message.result?.authMethods;
|
|
39
8
|
const eligible = method => method?.type === 'terminal' && strings(method.args ?? []);
|
package/src/version.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const version = '0.3.0-beta.
|
|
1
|
+
export const version = '0.3.0-beta.3';
|
package/src/wire.mjs
CHANGED
|
@@ -13,24 +13,26 @@ export class AcpFrames extends Transform {
|
|
|
13
13
|
this.onMessage = onMessage;
|
|
14
14
|
this.mapMessage = mapMessage;
|
|
15
15
|
}
|
|
16
|
-
_transform(chunk, encoding, done) {
|
|
16
|
+
async _transform(chunk, encoding, done) {
|
|
17
17
|
try {
|
|
18
18
|
let start = 0;
|
|
19
19
|
for (let index = 0; index < chunk.length; index++) {
|
|
20
20
|
if (chunk[index] !== 10) continue;
|
|
21
21
|
this.append(chunk.subarray(start, index));
|
|
22
|
-
|
|
22
|
+
this.parts.push(chunk.subarray(index, index + 1));
|
|
23
|
+
const frame = Buffer.concat(this.parts, this.bytes + 1);
|
|
23
24
|
this.parts = []; this.bytes = 0;
|
|
24
|
-
const source = new TextDecoder('utf-8', { fatal: true }).decode(
|
|
25
|
+
const source = new TextDecoder('utf-8', { fatal: true }).decode(frame.subarray(0, -1));
|
|
25
26
|
const message = JSON.parse(source);
|
|
26
27
|
if (!message || typeof message !== 'object' || Array.isArray(message) || message.jsonrpc !== '2.0' ||
|
|
27
28
|
!(typeof message.method === 'string' || Object.hasOwn(message, 'result') || Object.hasOwn(message, 'error'))) {
|
|
28
29
|
throw error('PROTOCOL_ERROR', 'Expected an ACP JSON-RPC message.');
|
|
29
30
|
}
|
|
30
|
-
this.onMessage?.(message);
|
|
31
|
+
const ready = this.onMessage?.(message, source);
|
|
32
|
+
if (ready?.then) await ready;
|
|
31
33
|
const mapped = this.mapMessage?.(message, source);
|
|
32
|
-
|
|
33
|
-
this.push(Buffer.from('\n'));
|
|
34
|
+
if (mapped === undefined) this.push(frame);
|
|
35
|
+
else if (mapped !== null) this.push(Buffer.concat([Buffer.isBuffer(mapped) ? mapped : Buffer.from(JSON.stringify(mapped)), Buffer.from('\n')]));
|
|
34
36
|
start = index + 1;
|
|
35
37
|
}
|
|
36
38
|
this.append(chunk.subarray(start));
|