@prplkane/agentlink 0.3.0-beta.2 → 0.3.0-beta.4

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 CHANGED
@@ -1,18 +1,14 @@
1
1
  # AgentLink
2
2
 
3
- A small, centrally installed **ACP gateway for agent CLIs**. Configure an agent
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
- JavaScript / Node.js 22+. Zero npm runtime dependencies. Public beta
9
- `0.3.0-beta.2`; the API and CLI may change before a stable release.
10
- Offline fixtures pass on Windows, Linux and macOS with Node 22 and 24.
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
- Source repository: [prplkane/agentlink](https://github.com/prplkane/agentlink).
9
+ Requires Node.js 22 or newer. The public beta, `0.3.0-beta.4`, 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
- Roundtable's ACP integration selects a saved profile for each seat and chairman.
84
- Its client uses ACP v1 with fresh sessions for stateless reviews. See
85
- [Roundtable testing](docs/laptop-testing.md#roundtable-integration) for the offline
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,43 @@ 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. AgentLink can only detect a retired
131
+ model once the bridge stops advertising that ID. While a bridge still lists
132
+ it, the saved choice is accepted and any failure comes from the vendor. If
133
+ the profile file cannot be read when a session is created, only that request
134
+ fails; the connection and its other sessions stay open. Bridge updates still
135
+ check ACP initialization. Actual model and effort support is checked in the session.
136
+
105
137
  ## Discover an unfamiliar agent
106
138
 
107
139
  ~~~sh
@@ -251,7 +283,8 @@ Current boundaries:
251
283
  its owner and path; remove a stale lock only after that process has stopped.
252
284
 
253
285
  `agentlink doctor [--json]` checks local profiles, launch files, managed
254
- installation metadata and locks without starting agents or changing anything.
286
+ installation metadata, connection leases and locks without starting agents or changing anything.
287
+ An abandoned lease appears as a note. Run `agentlink bridge prune` to remove it.
255
288
  It exits with status 1 for detected errors. It does not test sign-in or ACP
256
289
  compatibility; use `check PROFILE` for initialization.
257
290
 
@@ -259,17 +292,21 @@ compatibility; use `check PROFILE` for initialization.
259
292
 
260
293
  ~~~sh
261
294
  npm test
295
+ npm run test:maturity
262
296
  npm pack
263
297
  ~~~
264
298
 
265
299
  Tests use local fixture agents and locally produced npm packages, wheels and
266
300
  binary archives. They cover independent ACP clients, shared updates, rollback,
267
301
  leases/pruning, discovery, authentication forwarding and process cleanup.
302
+ The separate maturity check starts 50 batches of eight managed clients with
303
+ synthetic profiles, checks model and effort inheritance on every prompt, and
304
+ verifies lease cleanup after each batch.
268
305
  Python installation coverage runs when Python is available. No vendor account
269
306
  or paid model call is needed.
270
- A GitHub Actions workflow is included for Windows/Linux/macOS with Node 22/24
271
- and Python 3.13; it needs to run in the hosted repository before those platforms
272
- can be claimed as validated.
307
+ A GitHub Actions workflow runs the offline suite on Windows, Linux and macOS
308
+ with Node 22 and 24 and Python 3.13. Results are on the repository's
309
+ [Actions page](https://github.com/prplkane/agentlink/actions).
273
310
 
274
311
  See [laptop testing](docs/laptop-testing.md) for real-agent checks and
275
312
  [architecture](docs/architecture.md) for the maintenance boundaries.
@@ -281,9 +318,9 @@ the standard gateway; the helper's limitations do not define the gateway.
281
318
  ## Working on this repository
282
319
 
283
320
  Read [CONTRIBUTING.md](https://github.com/prplkane/agentlink/blob/main/CONTRIBUTING.md) and the shared
284
- [AGENTS.md](https://github.com/prplkane/agentlink/blob/main/AGENTS.md). Non-trivial changes use the
285
- [engineering work ledger](https://github.com/prplkane/agentlink/blob/main/docs/work/README.md). This is repository coordination,
286
- not an AgentLink runtime feature.
321
+ [AGENTS.md](https://github.com/prplkane/agentlink/blob/main/AGENTS.md). Work records for
322
+ non-trivial changes are kept locally and are not part of the repository; see the
323
+ [working agreement](https://github.com/prplkane/agentlink/blob/main/docs/work/README.md).
287
324
 
288
325
  The [source-document review](https://github.com/prplkane/agentlink/blob/main/docs/process/source-document-review.md) describes
289
326
  the guidance adapted from Roundtable and Career Hub, grouped by project, with
@@ -294,4 +331,3 @@ explicit reasons for each inclusion and exclusion. See
294
331
 
295
332
  [Apache License 2.0](LICENSE), copyright 2026 prplkane.
296
333
  [NOTICE](NOTICE) retains attribution for adapted process documentation.
297
- The license does not change the repository's private visibility.
@@ -1,5 +1,21 @@
1
1
  # ACP and Roundtable qualification — 2026-11-09
2
2
 
3
+ > **Addendum, 2026-11-21.** This document describes the 2026-11-09 run and is
4
+ > kept as history. Two things have changed since:
5
+ >
6
+ > - Since `0.3.0-beta.3` a profile can hold a model and effort default
7
+ > (`agentlink models` and `agentlink defaults`, described in the README).
8
+ > That supersedes the statement below that no effort setting is needed in
9
+ > AgentLink. The `CODEX_CONFIG` route used here still works.
10
+ > - The bridge versions in the table are the ones tested on 2026-11-09. On
11
+ > 2026-11-21 the maintainer's machine had `codex-acp` 2.7.0 and
12
+ > `claude-agent-acp` 0.109.0 installed.
13
+ >
14
+ > Saved defaults were checked live with Codex, Claude and Antigravity on
15
+ > Windows before `0.3.0-beta.3` was published. Each bridge confirmed the
16
+ > selected model and effort in its session response. The bridge versions
17
+ > used in that check were not recorded.
18
+
3
19
  The three real providers completed text prompts and two discussion rounds through
4
20
  AgentLink and Roundtable. The deterministic small-agent mimic did too. The live
5
21
  Codex chairman initially reached the test's 60-second deadline. The user-requested
@@ -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
- The exception to byte-preserving forwarding is an initialize response containing
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,9 +35,34 @@ 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
- The connection owns one bridge process. On client EOF it allows a short exit
39
- grace, then stops the process tree where the host supports it. Existing ACP
40
- sessions stay with that process when profiles or installations change.
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
+ If the gateway cannot prepare a creation, for example because the profile
48
+ file is unreadable at that moment, it answers that request with JSON-RPC
49
+ error `-32603` and the AgentLink or OS code in `data.code`. The request is
50
+ not forwarded to the bridge, and the reason is also written to stderr. The
51
+ connection and its other sessions continue.
52
+
53
+ Each configured creation keeps its own outstanding request ID. The gateway
54
+ reuses that ID upstream after the bridge's creation response and holds the
55
+ downstream response until configuration finishes. It replaces only the JSON
56
+ span for the options. Session notifications received during this exchange
57
+ follow the creation reply. Intermediate configuration notifications are
58
+ superseded by the setter's complete option list. Pending setup and buffered
59
+ notifications have per-connection limits.
60
+
61
+ The connection owns one bridge process. When the client closes stdin, the
62
+ gateway forwards EOF and allows up to five seconds for the bridge to finish
63
+ and report its own exit status. If the bridge is still running, the gateway
64
+ stops its process tree where the host supports it. Existing ACP sessions
65
+ stay with that process when profiles or installations change.
41
66
  Normal shutdown drains queued responses even for slow readers. Explicit
42
67
  termination cancels both pumps and interrupts a blocked output drain, allowing
43
68
  the connection to release its installation lease.
@@ -80,6 +105,9 @@ survive a machine restart when its owning process cannot survive either.
80
105
  On Windows, atomic replacement retries file-sharing conflicts up to five times
81
106
  with at most 750 ms of retry delay. A persistent failure leaves the old file in
82
107
  place and reports the error; replacement never deletes the destination first.
108
+ Lock acquisition and cleanup also retry short-lived Windows sharing errors.
109
+ An acquisition respects the remaining lock deadline and cancellation. A
110
+ persistent access error reports its original operating system code.
83
111
 
84
112
  No automatic deletion of previous versions occurs during an update. Users can
85
113
  prune after sessions finish and optionally clear the download cache. External
@@ -115,10 +143,11 @@ the profile instead of dropping its options and activating a different launch.
115
143
  |---|---|
116
144
  | `cli.mjs`, `runtime.mjs` | Small ACP launch entry, saved records and live-process leases |
117
145
  | `management-cli.mjs`, `doctor.mjs` | Management commands and read-only local diagnostics |
118
- | `gateway.mjs`, `wire.mjs`, `terminal-auth.mjs` | ACP forwarding, framing, backpressure and lossless auth argument edits |
146
+ | `gateway.mjs`, `wire.mjs`, `terminal-auth.mjs`, `json-spans.mjs` | ACP forwarding, framing, backpressure and lossless JSON edits |
147
+ | `session-defaults.mjs`, `session-options.mjs` | Per-session defaults and bridge-advertised model and effort choices |
119
148
  | `profiles.mjs`, `storage.mjs` | User profiles, atomic records and operation locks |
120
149
  | `bridges.mjs`, `artifacts.mjs` | Selected distributions, shared installations, integrity and bounded extraction |
121
- | `discovery.mjs`, `probe.mjs` | Help/metadata matching and initialization-only checks |
150
+ | `discovery.mjs`, `probe.mjs` | Help/metadata matching, initialization checks and explicit option inspection |
122
151
  | `process.mjs`, `child-process.mjs` | Executable resolution, bounded probes/installers and shared process cleanup |
123
152
  | `providers.mjs` | Small documented launch/install recipes |
124
153
  | `index.mjs` | Management coordination and compatibility library exports |
@@ -137,7 +166,9 @@ Windows process-tree cleanup uses taskkill while the owned bridge is alive.
137
166
  Native Job Object containment is not implemented, so descendants orphaned by a
138
167
  previously exited parent are a known limitation. Process ownership is not a
139
168
  sandbox. Abrupt process death may leave a lock or lease; stale locks produce a
140
- diagnostic, and pruning removes leases whose process no longer exists.
169
+ diagnostic. Doctor reports a lease whose process has exited as a note, and
170
+ pruning removes it. A management probe, help command or installer retains
171
+ its result if process cleanup fails. A warning on stderr identifies the PID.
141
172
  Very deep Python virtual environments can exceed Windows launcher limits.
142
173
  Installation detects an interpreter path of 260 or more characters before
143
174
  running venv/pip and requests a shorter store. No path virtualization layer,
@@ -1,6 +1,6 @@
1
1
  # Testing the AgentLink public beta on another laptop
2
2
 
3
- Use `@prplkane/agentlink@0.3.0-beta.2`. Node.js 22 or newer with npm is required.
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.2
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.2`. Installation of AgentLink alone downloads no
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. No real user store or vendor CLI is used.
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:
@@ -157,6 +160,10 @@ The requested rerun used a separate temporary profile with
157
160
  the same model then completed chairman synthesis in 12.2 seconds. No AgentLink
158
161
  runtime change was needed. Bridge defaults are provider-specific; merge the
159
162
  setting with the profile's existing configuration rather than discarding it.
163
+
164
+ Since `0.3.0-beta.3`, `agentlink defaults PROFILE --effort ID` saves the same
165
+ choice on the profile and checks it against the bridge's advertised levels.
166
+ Prefer it for new setups; the environment route above still works.
160
167
  Choose a suitable profile default and a realistic per-call deadline before a live
161
168
  review; do not automatically retry a timed-out verdict. Unknown usage remains unknown.
162
169
 
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@prplkane/agentlink",
3
- "version": "0.3.0-beta.2",
3
+ "version": "0.3.0-beta.4",
4
4
  "type": "module",
5
- "description": "Lightweight standard ACP gateway with centrally managed bridges and local discovery",
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/bridges.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { createHash } from 'node:crypto';
2
- import { chmod, mkdir, open, readdir, realpath, rm, stat, unlink, writeFile } from 'node:fs/promises';
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';
@@ -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 leases = [], installations = [];
232
- try { leases = await readdir(this.leases); } catch (cause) { if (cause.code !== 'ENOENT') throw cause; }
233
- for (const name of leases) {
234
- if (!name.endsWith('.json')) continue;
235
- const file = inside(this.leases, name), lease = await readJson(file);
236
- if (!Number.isSafeInteger(lease.pid) || lease.pid < 1) throw error('INVALID_BRIDGE', 'Invalid running-connection lease.');
237
- let alive = true;
238
- try { process.kill(lease.pid, 0); } catch (cause) { if (cause.code === 'ESRCH') alive = false; else throw cause; }
239
- if (alive) used.add(lease.installKey); else await unlink(file);
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 = [];
@@ -11,7 +11,7 @@ function waitForExit(child, timeoutMs) {
11
11
  });
12
12
  }
13
13
 
14
- export async function stopProcess(child) {
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
- const timer = setTimeout(() => { killer.kill(); finish(); }, 1500);
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
- try { await waitForExit(child, 1500); }
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/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
- process.exitCode = (await runGateway(launch, { extraArgs: gateway.extraArgs, signal: abort.signal })).exitCode;
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/discovery.mjs CHANGED
@@ -63,9 +63,11 @@ export async function inProbeDirectory(callback) {
63
63
  finally {
64
64
  if (dirname(directory) !== base || !basename(directory).startsWith('agentlink-probe-')) throw error('INVALID_PATH', 'Unexpected probe directory.');
65
65
  // Windows may retain a just-stopped descendant's cwd for a short time.
66
- // Retry only transient filesystem errors; do not replace the probe outcome
67
- // with a one-off EBUSY, and still surface a persistent cleanup failure.
68
- await rm(directory, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
66
+ try { await rm(directory, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }); }
67
+ catch (cause) {
68
+ process.emitWarning('Could not remove probe directory ' + directory + ': ' + cause.message,
69
+ { code: 'PROBE_CLEANUP_FAILED' });
70
+ }
69
71
  }
70
72
  }
71
73
 
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, whitespace } from './json-spans.mjs';
8
+
9
+ // The reply to a session/new that AgentLink could not prepare, for example
10
+ // because the profile file was unreadable at that moment. The request ID is
11
+ // copied as raw text so large numeric IDs keep their exact bytes.
12
+ function sessionSetupError(source, cause) {
13
+ const id = source.slice(...member(source, whitespace(source, 0), 'id'));
14
+ // The request itself was valid, so this is an internal error (-32603), not
15
+ // invalid params. data.code carries the stable AgentLink or OS error code.
16
+ const detail = { code: -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
- signal, extraArgs = [], interactive = Boolean(process.stdin.isTTY),
13
- maxMessageBytes = 16 * 1024 * 1024, shutdownGraceMs = 750 } = {}) {
14
- if (!strings(extraArgs) || !Number.isSafeInteger(shutdownGraceMs) || shutdownGraceMs < 1) {
25
+ signal, readDefaults, extraArgs = [], interactive = Boolean(process.stdin.isTTY),
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.
@@ -43,21 +59,50 @@ export async function runGateway(launch, { cwd = process.cwd(), env = process.en
43
59
  let inputPump = Promise.resolve();
44
60
  let outputFrames;
45
61
  if (!terminal) {
62
+ let defaultsRelay, protocolVersion, refusal;
63
+ async function prepareSession(message, source) {
64
+ try {
65
+ const defaults = readDefaults ? await readDefaults() : launch.defaults;
66
+ if (!defaults || !Object.keys(defaults).length) return;
67
+ if (!defaultsRelay) {
68
+ const { SessionDefaults } = await import('./session-defaults.mjs');
69
+ defaultsRelay = new SessionDefaults(frame => child.stdin.write(frame), maxMessageBytes);
70
+ }
71
+ defaultsRelay.expectSession(message, source, defaults, protocolVersion);
72
+ } catch (cause) {
73
+ // Only this creation fails. The bridge never sees it, and the other
74
+ // sessions on this connection keep running.
75
+ refusal = sessionSetupError(source, cause);
76
+ // The client may not show error details, so the reason also goes to the log.
77
+ diagnostics.write((cause.code || 'SESSION_SETUP_FAILED') + ': ' + cause.message + '\n');
78
+ }
79
+ }
46
80
  const initializeIds = new Set();
47
- inputPump = pipeline(input, new AcpFrames({ maxMessageBytes, onMessage(message) {
81
+ inputPump = pipeline(input, new AcpFrames({ maxMessageBytes, onMessage(message, source) {
82
+ if (message.method === 'session/new' && Object.hasOwn(message, 'id')) return prepareSession(message, source);
48
83
  if (message.method === 'initialize' && Object.hasOwn(message, 'id')) initializeIds.add(message.id);
84
+ }, mapMessage() {
85
+ if (!refusal) return;
86
+ // Reply through the output pump so the frame keeps its place in the stream.
87
+ if (!outputFrames.writableEnded && !outputFrames.destroyed) outputFrames.push(refusal);
88
+ refusal = undefined;
89
+ return null;
49
90
  } }), child.stdin, { signal: pumps.signal }).then(() => {
50
- if (!closing) inputTimer = setTimeout(() => { void stop(); }, shutdownGraceMs);
91
+ if (!closing && child.exitCode === null && child.signalCode === null) {
92
+ inputTimer = setTimeout(() => { void stop(); }, eofGraceMs);
93
+ }
51
94
  }, cause => {
52
95
  if (closing) return;
53
96
  // A normally exiting bridge can close its stdin before the exit event.
54
97
  // Give it time to finish and drain stdout instead of destroying its reply.
55
98
  if (['EPIPE', 'ERR_STREAM_PREMATURE_CLOSE', 'ERR_STREAM_DESTROYED'].includes(cause.code)) {
56
- if (child.exitCode === null && child.signalCode === null) inputTimer = setTimeout(() => fail(cause), shutdownGraceMs);
99
+ if (child.exitCode === null && child.signalCode === null) inputTimer = setTimeout(() => fail(cause), pipeGraceMs);
57
100
  } else fail(cause);
58
101
  });
59
102
  outputFrames = new AcpFrames({ maxMessageBytes, mapMessage(message, source) {
60
- if (message.method || !initializeIds.delete(message.id) || !Array.isArray(message.result?.authMethods)) return;
103
+ if (message.method || !initializeIds.delete(message.id)) return defaultsRelay?.agentMessage(message, source);
104
+ protocolVersion = message.result?.protocolVersion;
105
+ if (!Array.isArray(message.result?.authMethods)) return;
61
106
  // The client relaunches AgentLink, not the underlying executable. A marker
62
107
  // identifies terminal auth even when the upstream method has only env.
63
108
  return terminalAuthReply(message, source);
@@ -81,13 +126,13 @@ export async function runGateway(launch, { cwd = process.cwd(), env = process.en
81
126
  if (done) return;
82
127
  if (!failure && !output.destroyed && (output.writableLength || output.writableNeedDrain || child.stdout?.readableLength ||
83
128
  outputFrames?.readableLength || outputFrames?.writableLength)) {
84
- flushTimer = setTimeout(idle, shutdownGraceMs);
129
+ flushTimer = setTimeout(idle, pipeGraceMs);
85
130
  } else finish();
86
131
  };
87
132
  // end:false leaves the caller's stream open and may resolve before its
88
133
  // final write callback; also wait for that queued output to drain.
89
134
  outputPump.then(() => { if (failure || !output.writableLength || output.destroyed) finish(); });
90
- flushTimer = setTimeout(idle, shutdownGraceMs);
135
+ flushTimer = setTimeout(idle, pipeGraceMs);
91
136
  });
92
137
  if (failure) throw failure;
93
138
  return { exitCode };
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
+ }
@@ -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
@@ -1,12 +1,13 @@
1
1
  import { version } from './version.mjs';
2
2
  import { spawn } from 'node:child_process';
3
3
  import { AcpFrames } from './wire.mjs';
4
- import { stopProcess } from './process.mjs';
4
+ import { finishCommand } from './child-process.mjs';
5
5
  import { error } from './profiles.mjs';
6
+ import { describeOptions, sessionSelections } from './session-options.mjs';
6
7
 
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 } = {}) {
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
- timer = setTimeout(() => reject(error('INITIALIZE_TIMEOUT', 'ACP initialization timed out.')), timeoutMs);
19
- abort = () => reject(error('CANCELLED', 'ACP initialization cancelled.'));
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.id !== 'agentlink-probe' || message.method) return;
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('INITIALIZE_REJECTED', message.error.message || 'Agent rejected initialization.'), {
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 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');
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
- } finally { clearTimeout(timer); signal?.removeEventListener('abort', abort); await stopProcess(child); }
83
+ } finally { clearTimeout(timer); signal?.removeEventListener('abort', abort); await finishCommand(child); }
57
84
  }
package/src/process.mjs CHANGED
@@ -4,7 +4,7 @@ import { constants } from 'node:fs';
4
4
  import { basename, delimiter, dirname, extname, isAbsolute, join, resolve } from 'node:path';
5
5
  import { stripVTControlCharacters } from 'node:util';
6
6
  import { error, strings } from './profiles.mjs';
7
- import { stopProcess } from './child-process.mjs';
7
+ import { finishCommand } from './child-process.mjs';
8
8
  export { stopProcess } from './child-process.mjs';
9
9
 
10
10
  export async function resolveCommand(command, prefixArgs = [], env = process.env) {
@@ -79,7 +79,7 @@ export async function readHelp({ command, args, cwd, env = process.env, timeoutM
79
79
  child.stdin.end();
80
80
  });
81
81
  return { code, text: stripVTControlCharacters(Buffer.concat(buffers).toString('utf8')) };
82
- } finally { signal?.removeEventListener('abort', abort); await stopProcess(child); }
82
+ } finally { signal?.removeEventListener('abort', abort); await finishCommand(child); }
83
83
  }
84
84
 
85
85
  export async function runCommand(command, args, { cwd, env = process.env, timeoutMs = 180000, signal } = {}) {
@@ -107,6 +107,6 @@ export async function runCommand(command, args, { cwd, env = process.env, timeou
107
107
  });
108
108
  } finally {
109
109
  clearTimeout(timer); signal?.removeEventListener('abort', abort);
110
- await stopProcess(child);
110
+ await finishCommand(child);
111
111
  }
112
112
  }
package/src/profiles.mjs CHANGED
@@ -8,6 +8,14 @@ export const error = (code, message) => Object.assign(new Error(message), { code
8
8
  export const strings = value => Array.isArray(value) && value.every(item => typeof item === 'string' && !item.includes('\0'));
9
9
  const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
10
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
+
11
19
  export function profileName(name) {
12
20
  if (typeof name !== 'string' || !/^[a-z0-9][a-z0-9_-]{0,63}$/.test(name) ||
13
21
  /^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/.test(name)) {
@@ -30,6 +38,7 @@ export function validateProfile(profile) {
30
38
  if (!object(profile.bridge) || typeof profile.bridge.useDefaultArgs !== 'boolean') throw error('INVALID_PROFILE', 'Invalid managed bridge reference.');
31
39
  profileName(profile.bridge.id);
32
40
  }
41
+ if (profile.defaults !== undefined) validateDefaults(profile.defaults);
33
42
  if (profile.env !== undefined && (!object(profile.env) || Object.entries(profile.env).some(([key, value]) =>
34
43
  !/^[A-Za-z_][A-Za-z0-9_]*$/.test(key) || typeof value !== 'string' || value.includes('\0')))) {
35
44
  throw error('INVALID_PROFILE', 'Invalid launch environment.');
@@ -1,14 +1,20 @@
1
1
  import { rename } from 'node:fs/promises';
2
2
  import { setTimeout as delay } from 'node:timers/promises';
3
3
 
4
- // Windows readers can briefly prevent replacing an otherwise writable file.
5
- // Retry the same atomic rename; never unlink the destination to make it succeed.
6
- export async function replaceFile(source, destination) {
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
7
  for (let attempt = 0; ; attempt++) {
8
- try { return await rename(source, destination); }
8
+ signal?.throwIfAborted();
9
+ try { return await operation(); }
9
10
  catch (cause) {
10
- if (process.platform !== 'win32' || attempt === 5 || !['EACCES', 'EPERM', 'EBUSY'].includes(cause.code)) throw cause;
11
- await delay(50 * (attempt + 1));
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 });
12
14
  }
13
15
  }
14
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
@@ -2,7 +2,7 @@ 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 } from './replace-file.mjs';
5
+ import { replaceFile, retryWindowsSharing } from './replace-file.mjs';
6
6
 
7
7
  export function inside(root, path) {
8
8
  const target = resolve(root, path);
@@ -38,7 +38,7 @@ export async function withLock(path, callback, timeoutMs = 180000, signal) {
38
38
  let handle;
39
39
  while (!handle) {
40
40
  signal?.throwIfAborted();
41
- try { handle = await open(path, 'wx', 0o600); }
41
+ try { handle = await retryWindowsSharing(() => open(path, 'wx', 0o600), deadline, signal); }
42
42
  catch (cause) {
43
43
  if (cause.code !== 'EEXIST') throw cause;
44
44
  try {
@@ -59,5 +59,5 @@ export async function withLock(path, callback, timeoutMs = 180000, signal) {
59
59
  await handle.writeFile(JSON.stringify({ pid: process.pid, createdAt: new Date().toISOString() }));
60
60
  signal?.throwIfAborted();
61
61
  return await callback();
62
- } finally { await handle.close(); await unlink(path); }
62
+ } finally { await handle.close(); await retryWindowsSharing(() => unlink(path)); }
63
63
  }
@@ -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.2';
1
+ export const version = '0.3.0-beta.4';
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
- const line = Buffer.concat(this.parts, this.bytes);
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(line);
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
- this.push(mapped === undefined ? line : Buffer.isBuffer(mapped) ? mapped : Buffer.from(JSON.stringify(mapped)));
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));